main.py 637 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130
  1. import asyncio
  2. import json
  3. import logging
  4. import math
  5. import os
  6. import posixpath
  7. import re
  8. import secrets
  9. import shutil
  10. import time
  11. from contextlib import asynccontextmanager
  12. from datetime import datetime, timedelta, timezone
  13. from logging.handlers import RotatingFileHandler
  14. from pathlib import Path, PurePosixPath
  15. from typing import cast
  16. from urllib.parse import urlparse
  17. from fastapi import FastAPI
  18. from fastapi.encoders import jsonable_encoder
  19. from fastapi.exceptions import RequestValidationError
  20. from fastapi.responses import FileResponse, JSONResponse
  21. from fastapi.staticfiles import StaticFiles
  22. from sqlalchemy import delete, func, inspect as sa_inspect, or_, select, text, update
  23. from sqlalchemy.engine import CursorResult
  24. from sqlalchemy.exc import IntegrityError
  25. from sqlalchemy.orm.exc import StaleDataError
  26. from backend.app.api.routes import (
  27. ams_history,
  28. announcements,
  29. api_keys,
  30. archive_purge,
  31. archives,
  32. auth,
  33. bug_report,
  34. bulk,
  35. camera,
  36. camwall,
  37. cloud,
  38. connected_apps,
  39. discovery,
  40. external_links,
  41. filaments,
  42. finance,
  43. firmware,
  44. github_backup,
  45. groups,
  46. ha_sensors,
  47. inventory,
  48. kprofiles,
  49. labels,
  50. library,
  51. library_tags,
  52. library_trash,
  53. library_variants,
  54. local_backup,
  55. local_presets,
  56. location_ha_sensors,
  57. maintenance,
  58. makerworld,
  59. manyfold,
  60. metrics,
  61. mfa,
  62. notification_templates,
  63. notifications,
  64. obico,
  65. orca_cloud,
  66. overlay_branding,
  67. pending_uploads,
  68. pipeline_runs,
  69. print_log,
  70. print_queue,
  71. printer_locations,
  72. printer_sensor_history,
  73. printers,
  74. projects,
  75. scheduled_dryings,
  76. settings as settings_routes,
  77. slice_jobs,
  78. slicer_pipelines,
  79. slicer_presets,
  80. smart_plugs,
  81. sponsor_prompt,
  82. spoolbuddy,
  83. spoolman,
  84. spoolman_inventory,
  85. support,
  86. system,
  87. updates,
  88. user_notifications,
  89. users,
  90. virtual_printers,
  91. webhook,
  92. websocket,
  93. )
  94. from backend.app.api.routes.maintenance import (
  95. _get_printer_maintenance_internal,
  96. ensure_default_types,
  97. maintenance_alert_values,
  98. )
  99. from backend.app.api.routes.support import init_debug_logging
  100. from backend.app.core.config import APP_VERSION, settings as app_settings
  101. from backend.app.core.database import async_session, engine, init_db
  102. from backend.app.core.static_assets import AssetStaticFiles
  103. from backend.app.core.tasks import spawn_background_task
  104. from backend.app.core.websocket import ws_manager
  105. from backend.app.services import kprofile_drift, pause_eta, print_dispatch_context, slot_unlink_grace
  106. from backend.app.services.ams_assignment_lock import get_ams_assignment_lock
  107. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  108. from backend.app.services.archive_cost_estimate import (
  109. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  110. settle_archive_cost_estimate as _settle_archive_cost_estimate,
  111. )
  112. from backend.app.services.archive_purge import archive_purge_service
  113. from backend.app.services.bambu_ftp import (
  114. RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  115. FileNotOnPrinterError,
  116. cache_3mf_download,
  117. clear_3mf_cache,
  118. download_file_async,
  119. download_file_try_paths_async,
  120. ftps_handshake_blocked,
  121. get_cached_3mf,
  122. get_ftp_retry_settings,
  123. normalize_3mf_name,
  124. with_ftp_retry,
  125. )
  126. from backend.app.services.bambu_mqtt import PrinterState
  127. from backend.app.services.camera_light import camera_light
  128. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  129. from backend.app.services.github_backup import github_backup_service
  130. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  131. from backend.app.services.library_trash import library_trash_service
  132. from backend.app.services.local_backup import local_backup_service
  133. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  134. from backend.app.services.mqtt_relay import mqtt_relay
  135. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  136. from backend.app.services.notification_service import notification_service
  137. from backend.app.services.notify_live_activities import notify_live_activities
  138. from backend.app.services.notify_widgets import notify_widgets
  139. from backend.app.services.obico_detection import obico_detection_service
  140. from backend.app.services.plug_energy import get_plug_energy as _get_plug_energy
  141. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  142. from backend.app.services.print_scheduler import scheduler as print_scheduler
  143. from backend.app.services.print_storage import (
  144. REASON_FTP_TRANSFER_FAILED,
  145. REASON_FTPS_COOLOFF,
  146. external_storage_present,
  147. ftp_probe_paths,
  148. print_file_reachable_over_ftp,
  149. )
  150. from backend.app.services.printer_manager import (
  151. init_printer_connections,
  152. parse_plate_id,
  153. printer_manager,
  154. printer_state_to_dict,
  155. resolve_plate_id,
  156. )
  157. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  158. from backend.app.services.slot_nozzle import (
  159. nozzle_diameter_for_extruder,
  160. nozzle_flow_for_extruder,
  161. )
  162. from backend.app.services.smart_plug_manager import smart_plug_manager
  163. from backend.app.services.spool_assignment_notifications import (
  164. notify_missing_spool_assignments_on_print_start,
  165. )
  166. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  167. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  168. from backend.app.services.spoolman_tracking import (
  169. cleanup_tracking as _cleanup_spoolman_tracking,
  170. release_archived_slot_rows as _release_archived_spoolman_slots,
  171. report_usage as _report_spoolman_usage,
  172. store_print_data as _store_spoolman_print_data,
  173. )
  174. from backend.app.services.telegram_reactions import telegram_reaction_poller
  175. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  176. from backend.app.utils.ams_humidity import ams_humidity_percent
  177. from backend.app.utils.filament_types import printer_filament_type
  178. from backend.app.utils.fts_routing import extruder_for_inlet
  179. from backend.app.utils.local_time import to_naive_utc, utcnow_naive
  180. from backend.app.utils.print_jobs import is_internal_printer_job
  181. # =============================================================================
  182. # Dependency Check - runs before other imports to give helpful error messages
  183. # =============================================================================
  184. def _start_error_server(missing_packages: list):
  185. """Start a minimal HTTP server to display dependency errors in browser."""
  186. import os
  187. import signal
  188. from http.server import BaseHTTPRequestHandler, HTTPServer
  189. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  190. html = f"""<!DOCTYPE html>
  191. <html>
  192. <head>
  193. <title>Bambuddy - Setup Required</title>
  194. <style>
  195. body {{
  196. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  197. background: #0f172a; color: #e2e8f0;
  198. display: flex; justify-content: center; align-items: center;
  199. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  200. }}
  201. .container {{
  202. background: #1e293b; border-radius: 12px; padding: 40px;
  203. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  204. }}
  205. h1 {{ color: #f87171; margin-bottom: 10px; }}
  206. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  207. .packages {{
  208. background: #0f172a; border-radius: 8px; padding: 20px;
  209. margin: 20px 0; text-align: left;
  210. }}
  211. .packages ul {{ margin: 0; padding-left: 20px; }}
  212. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  213. .command {{
  214. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  215. margin: 15px 0; font-family: monospace; color: #4ade80;
  216. text-align: left; overflow-x: auto;
  217. }}
  218. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  219. </style>
  220. </head>
  221. <body>
  222. <div class="container">
  223. <h1>Setup Required</h1>
  224. <h2>Missing Python packages</h2>
  225. <div class="packages"><ul>{packages_html}</ul></div>
  226. <p>To fix, run this command on your server:</p>
  227. <div class="command">pip install -r requirements.lock</div>
  228. <p>Or if using a virtual environment:</p>
  229. <div class="command">./venv/bin/pip install -r requirements.lock</div>
  230. <p class="note">After installing, restart Bambuddy:<br>
  231. <code>sudo systemctl restart bambuddy</code></p>
  232. </div>
  233. </body>
  234. </html>"""
  235. class ErrorHandler(BaseHTTPRequestHandler):
  236. def do_GET(self):
  237. self.send_response(503)
  238. self.send_header("Content-type", "text/html")
  239. self.end_headers()
  240. self.wfile.write(html.encode())
  241. def log_message(self, format, *args):
  242. print(f"[Error Server] {args[0]}")
  243. port = int(os.environ.get("PORT", 8000))
  244. print(f"\nStarting error server on http://0.0.0.0:{port}")
  245. print("Visit this URL in your browser to see the error details.\n")
  246. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  247. def shutdown(signum, frame):
  248. print("\nShutting down error server...")
  249. raise SystemExit(0)
  250. signal.signal(signal.SIGTERM, shutdown)
  251. signal.signal(signal.SIGINT, shutdown)
  252. server.serve_forever()
  253. def check_dependencies():
  254. """Check that all required packages are installed."""
  255. missing = []
  256. # Map of import name -> package name (for pip install)
  257. required = {
  258. "jwt": "PyJWT",
  259. "fastapi": "fastapi",
  260. "uvicorn": "uvicorn",
  261. "sqlalchemy": "sqlalchemy",
  262. "aiosqlite": "aiosqlite",
  263. "pydantic": "pydantic",
  264. "paho.mqtt": "paho-mqtt",
  265. }
  266. for module, package in required.items():
  267. try:
  268. __import__(module)
  269. except ImportError:
  270. missing.append(package)
  271. if missing:
  272. print("\n" + "=" * 60)
  273. print("ERROR: Missing required Python packages!")
  274. print("=" * 60)
  275. print(f"\nMissing packages: {', '.join(missing)}")
  276. print("\nTo fix, run:")
  277. print(" pip install -r requirements.lock")
  278. print("\nOr if using a virtual environment:")
  279. print(" ./venv/bin/pip install -r requirements.lock")
  280. print("=" * 60 + "\n")
  281. _start_error_server(missing)
  282. check_dependencies()
  283. # =============================================================================
  284. # Import settings first for logging configuration
  285. # Configure logging based on settings
  286. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  287. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  288. log_level = getattr(logging, log_level_str, logging.INFO)
  289. # Trace ID column ([-] when no request scope is active — startup, MQTT
  290. # callbacks, scheduled tasks not chained from a request — so the column
  291. # stays visually aligned and missing values are obvious in grep). See
  292. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  293. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  294. # Create root logger
  295. root_logger = logging.getLogger()
  296. root_logger.setLevel(log_level)
  297. # Trace-ID injection: this filter populates record.trace_id from the
  298. # per-request ContextVar so the format string above can reference it.
  299. # Attached to each HANDLER (not the root logger) because Python's
  300. # logging semantics only invoke a logger's filters on records that
  301. # *originated* at that logger — records propagated up from child
  302. # loggers (every named logger in the app) never trigger root's filter.
  303. # Putting it on the handlers means every record any handler emits gets
  304. # trace_id injected just before the formatter runs, regardless of which
  305. # logger created the record. Without this, the formatter raises
  306. # KeyError on every child-logger record and the record is silently
  307. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  308. # partially" bug we hit. See backend/app/core/trace.py for the
  309. # ContextVar the filter reads.
  310. from backend.app.core.logging_filters import RefusedHeaderRedactFilter
  311. from backend.app.core.response_redaction import RefusedHeaderResponseMask
  312. from backend.app.core.trace import TraceIDFilter
  313. _trace_id_filter = TraceIDFilter()
  314. # Console handler - always enabled
  315. console_handler = logging.StreamHandler()
  316. console_handler.setLevel(log_level)
  317. console_handler.setFormatter(logging.Formatter(log_format))
  318. console_handler.addFilter(_trace_id_filter)
  319. # A refused header's value (often a token) masked before the line is written.
  320. _refused_header_filter = RefusedHeaderRedactFilter()
  321. console_handler.addFilter(_refused_header_filter)
  322. root_logger.addHandler(console_handler)
  323. def _attach_file_handler_to_uvicorn(handler: logging.Handler) -> None:
  324. """Send uvicorn's own loggers to bambuddy.log as well.
  325. Neither reaches the root handler: uvicorn.access has propagate=False, and
  326. uvicorn.error propagates only to "uvicorn", which has propagate=False.
  327. uvicorn.access is the record of which endpoint changed server state;
  328. uvicorn.error is where an unhandled route error is logged with its
  329. traceback ("Exception in ASGI application").
  330. """
  331. for name in ("uvicorn.access", "uvicorn.error"):
  332. logging.getLogger(name).addHandler(handler)
  333. # File handler - only in production or if explicitly enabled
  334. if app_settings.log_to_file:
  335. log_file = app_settings.log_dir / "bambuddy.log"
  336. file_handler = RotatingFileHandler(
  337. log_file,
  338. maxBytes=app_settings.log_max_bytes,
  339. backupCount=app_settings.log_backup_count,
  340. encoding="utf-8",
  341. )
  342. file_handler.setLevel(log_level)
  343. file_handler.setFormatter(logging.Formatter(log_format))
  344. file_handler.addFilter(_trace_id_filter)
  345. file_handler.addFilter(_refused_header_filter)
  346. root_logger.addHandler(file_handler)
  347. logging.info("Logging to file: %s", log_file)
  348. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  349. # access logger with propagate=False by default, so without this attach
  350. # there is no on-disk record of which endpoint triggered a server-state
  351. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  352. # for exactly this reason. Filtered to write methods only
  353. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  354. # frontend don't churn the rotation window faster than it's useful.
  355. from backend.app.core.logging_filters import (
  356. CancelledPoolNoiseFilter,
  357. WriteRequestsOnlyFilter,
  358. )
  359. _attach_file_handler_to_uvicorn(file_handler)
  360. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  361. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  362. # Uvicorn's access logger has propagate=False (its own default), so the
  363. # root-attached TraceIDFilter never sees these records. Attach a
  364. # second instance directly so HTTP access lines carry the same trace
  365. # ID column as the application logs they correlate with.
  366. uvicorn_access_logger.addFilter(TraceIDFilter())
  367. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  368. # BaseHTTPMiddleware cancelling the inner task scope on client
  369. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  370. # underlying transaction leak; this filter only suppresses the residual
  371. # log records that pre-existing pools still emit during their cleanup.
  372. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  373. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  374. # handler (console included), whether or not file logging is on.
  375. from backend.app.core.logging_filters import ( # noqa: E402
  376. QueryTokenRedactFilter,
  377. ShutdownCancelledRequestFilter,
  378. )
  379. # First, so the traceback of a stream cancelled at shutdown is dropped before
  380. # the filters below render it.
  381. logging.getLogger("uvicorn.error").addFilter(ShutdownCancelledRequestFilter())
  382. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  383. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  384. logging.getLogger(_uvicorn_logger).addFilter(_refused_header_filter)
  385. # These stay at WARNING even in debug mode: at INFO/DEBUG httpx/httpcore log
  386. # full request URLs, and some carry credentials (bot tokens, webhook URLs, API
  387. # keys in the query). Same as the runtime log-level toggle in support.py.
  388. logging.getLogger("httpcore").setLevel(logging.WARNING)
  389. logging.getLogger("httpx").setLevel(logging.WARNING)
  390. # aiosqlite logs every statement with its parameters at DEBUG.
  391. logging.getLogger("aiosqlite").setLevel(logging.WARNING)
  392. # Reduce noise from third-party libraries in production
  393. if not app_settings.debug:
  394. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  395. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  396. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  397. # Track active prints: {(printer_id, filename): archive_id}
  398. _active_prints: dict[tuple[int, str], int] = {}
  399. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  400. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  401. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  402. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  403. # instead of running its own grab-now chain when present, so the finish photo
  404. # captures the better-framed pre-bed-drop moment without us having to force
  405. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  406. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  407. #
  408. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  409. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  410. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  411. # bank and the others are not — so the consumer can't tell them apart and
  412. # must not rotate again.
  413. _stage22_finish_frames: dict[int, bytes] = {}
  414. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  415. # `finally` block (whether it captured a frame or not). The consumer in
  416. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  417. # so the FINISH-state fallback path — where moment and completion are dispatched
  418. # back-to-back — doesn't race past the producer with an empty pop, and the
  419. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  420. # grab (Bambu printers allow only one RTSP client at a time).
  421. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  422. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  423. # layer-change and on print-progress advances (#2547) while the model is still
  424. # printing, then consumed by the FINISH-state finish-photo path when the
  425. # dispatcher recorded that it injected End G-code into this print. Bambu
  426. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  427. # plate-swap) has run, so a live grab there would capture the swapped/empty
  428. # plate.
  429. #
  430. # The load-bearing property: both drivers are print telemetry that stops before
  431. # the End G-code executes — no further layer_num increases, and mc_percent
  432. # freezes — so the last banked frame is always the finished print before the
  433. # swap. Anything added as a third driver must hold that same property.
  434. _inprint_frame_bank: dict[int, bytes] = {}
  435. # Monotonic timestamp of the last banked frame per printer — throttles banking
  436. # so tall prints don't add a camera grab on every layer.
  437. _inprint_frame_bank_ts: dict[int, float] = {}
  438. # Minimum seconds between banked frames, except the final object layer which
  439. # always refreshes for the best framing.
  440. _INPRINT_BANK_MIN_INTERVAL = 25.0
  441. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  442. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  443. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  444. # the first connected status update for that connection; transitions back
  445. # to False whenever we observe `state.connected = False` so the next
  446. # reconnect re-arms reconciliation. Keyed by printer_id.
  447. _printer_reconciled_since_connect: dict[int, bool] = {}
  448. # Same edge, same keying, for priming the printer's calibration table exactly
  449. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  450. # is otherwise filled only when someone opens the Profiles page or Configure
  451. # Slot, when a GitHub backup runs, or when the printer happens to answer
  452. # somebody else's query on the report topic. Until then the AMS slot card has
  453. # no K value to show on the printers whose trays carry none of their own
  454. # (#2854 — H2-series report cali_idx and nothing more).
  455. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  456. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  457. # {(printer_id, filename): archive_id}
  458. _expected_prints: dict[tuple[int, str], int] = {}
  459. # Archives of the running prints Bambuddy dispatched itself: adopted from an
  460. # expected print, or found with Bambuddy's dispatch marker. _active_prints holds
  461. # every print on_print_start archived, those started from Bambu Studio, Handy or
  462. # the printer's screen included, so it is no proof of ownership on its own.
  463. _owned_print_archive_ids: set[int] = set()
  464. # What a dispatch registered for its print, keyed (printer_id, archive_id):
  465. # plates of one archive print on two printers at once, each with its own.
  466. # Track AMS mapping for prints: {(printer_id, archive_id): [global_tray_id_per_slot]}
  467. # Used by usage tracker to map 3MF slots to physical AMS trays
  468. _print_ams_mappings: dict[tuple[int, int], list[int]] = {}
  469. # Track cost center selection for the current print run: {(printer_id, archive_id): cost_center_id}
  470. _print_cost_center_ids: dict[tuple[int, int], int] = {}
  471. # Track plate_id for prints from multi-plate 3MFs: {(printer_id, archive_id): plate_id}
  472. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  473. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  474. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  475. # for the queue path. Cleared on print completion or TTL eviction.
  476. _print_plate_ids: dict[tuple[int, int], int] = {}
  477. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  478. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  479. _last_progress_milestone: dict[int, int] = {}
  480. # Track whether first layer complete notification has been sent for current print
  481. _first_layer_notified: dict[int, bool] = {}
  482. # Track whether we already sent a kill-switch stop for the current unauthorized print
  483. _unauthorized_print_kill_sent: set[int] = set()
  484. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  485. # lookup briefly so an unknown active print does not query the database on
  486. # every status frame. A short TTL keeps settings changes responsive.
  487. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  488. _kill_switch_setting_cache: tuple[bool, float] | None = None
  489. # Provider notification started when the kill switch stops a print. The later
  490. # MQTT print-complete callback awaits this task and only sends its regular
  491. # provider notification when the immediate attempt failed.
  492. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  493. # HMS faults already notified, with when each was last seen:
  494. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  495. # fault that flickers beside a held notice was forgotten on every gap and
  496. # notified on every return (#3226). The window is long because the measured
  497. # gaps reach 64 s.
  498. _notified_hms_errors: dict[int, dict[str, float]] = {}
  499. _HMS_CLEAR_GRACE_SECONDS = 600.0
  500. # The print state each printer was last seen in, and the faults recorded before
  501. # it last changed, which are forgotten as soon as they are gone (see
  502. # _take_new_hms_faults).
  503. _hms_print_state: dict[int, str] = {}
  504. _hms_forget_when_gone: dict[int, set[str]] = {}
  505. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  506. # Used for snapshot-diff detection at print completion
  507. _timelapse_baselines: dict[int, set[str]] = {}
  508. # Printers whose baseline above was taken off a card that could not be read,
  509. # so it is empty without the card being empty (#3412).
  510. _timelapse_baselines_unread: set[int] = set()
  511. # Track printers waiting for bed to cool after print completion.
  512. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  513. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  514. _bed_cool_waiters: dict[int, dict] = {}
  515. # Track printers where the user explicitly stopped the print from the queue UI.
  516. # When on_print_complete fires with status "failed" for these printers we treat it
  517. # as "cancelled" (stopped by user) so the correct notification email is sent.
  518. _user_stopped_printers: set[int] = set()
  519. # Printers whose running print the kill switch stopped. Their completion is a
  520. # cancel with the reason "killSwitch", not the "failed" the printer reports.
  521. _kill_switch_stopped: set[int] = set()
  522. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  523. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  524. # holds the previous observation so we only fire on the True → False edge (a
  525. # False → False repeat doesn't notify; an initial False at startup doesn't
  526. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  527. # holds the per-printer pending asyncio task that fires the notification
  528. # after a debounce window — cancelled if the printer reconnects before the
  529. # window elapses, so transient MQTT blips don't flood the user.
  530. _printer_last_connected: dict[int, bool] = {}
  531. # Printers whose relay offline event went out, so the reconnect publishes the
  532. # matching online event and a blip shorter than the debounce publishes neither.
  533. _printer_offline_published: set[int] = set()
  534. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  535. # Debounce: a printer must stay offline this long before we notify. Sized
  536. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  537. # so a single stale-trigger cooldown isn't enough to fire — only a real
  538. # offline that survives one reconnect attempt notifies.
  539. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  540. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  541. # when status="failed" to label the print's failure_reason in archives.
  542. #
  543. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  544. # which is wrong on two counts:
  545. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  546. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  547. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  548. # the public wiki) as part of its user-cancel sequence. Matching on the module
  549. # alone caused user-cancellations to be archived as "Layer shift" failures.
  550. # We now match by full short code only — anything not in this map leaves
  551. # failure_reason=None rather than guessing.
  552. # Values are the canonical camelCase failure-reason keys, NOT display labels
  553. # (issue #2974). The vocabulary is enforced on writes by
  554. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  555. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  556. # Statistics breakdown. Storing a label here instead put a second spelling of
  557. # the same cause into one column: the Failure Analysis widget groups on the raw
  558. # value, so a print the backend classified and an identical one a user
  559. # classified counted as two different reasons, and the label form could never
  560. # be translated because there was no key for ``t()`` to resolve.
  561. _HMS_FAILURE_REASONS: dict[str, str] = {
  562. # Layer shift / step loss
  563. "0300_4057": "layerShift",
  564. "0300_4068": "layerShift",
  565. "0300_800C": "layerShift",
  566. # Filament runout (printer-side & per-AMS-slot)
  567. "0300_8004": "filamentRunout",
  568. "0700_8011": "filamentRunout",
  569. "0701_8011": "filamentRunout",
  570. "0702_8011": "filamentRunout",
  571. "0703_8011": "filamentRunout",
  572. "0704_8011": "filamentRunout",
  573. "0705_8011": "filamentRunout",
  574. "0706_8011": "filamentRunout",
  575. "0707_8011": "filamentRunout",
  576. "07FF_8011": "filamentRunout",
  577. # Clogged nozzle / extruder
  578. "0300_4006": "cloggedNozzle",
  579. "0300_8016": "cloggedNozzle",
  580. "0300_801C": "cloggedNozzle",
  581. "0700_8003": "cloggedNozzle",
  582. "0700_8007": "cloggedNozzle",
  583. "0700_8013": "cloggedNozzle",
  584. "0701_8003": "cloggedNozzle",
  585. "0701_8007": "cloggedNozzle",
  586. "0701_8013": "cloggedNozzle",
  587. "0702_8003": "cloggedNozzle",
  588. # AI print monitoring — spaghetti / the model coming off the plate.
  589. # `spaghettiDetached` is a key the archive editor already offers for this
  590. # failure mode, not a new one, so a derived reason opens the dropdown on
  591. # that option rather than blank — and survives the next save, which clears
  592. # any value the editor does not recognise.
  593. #
  594. # A module-0x0C row is safe here despite the warning above: that warning is
  595. # about matching on the module alone, and 0C00_8042 is a full short code
  596. # with a documented meaning ("The AI print monitor has detected a spaghetti
  597. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  598. # cannot collide.
  599. #
  600. # 0300_8003's own text ends "before continuing your print", but on an X2D
  601. # it arrives with the print already paused, offering only
  602. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  603. #
  604. # Two neighbours are left out on purpose, so this does not get re-derived:
  605. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  606. # reads as a warning about a print that is still running, not a halt.
  607. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  608. # the waste chute. That is not the print failing.
  609. #
  610. # That line is drawn from the text, not from `severity`, because severity
  611. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  612. # module/error word with no level in it, and bambu_mqtt.py gives every
  613. # print_error entry a flat severity=3. Matching on the short code alone is
  614. # the right shape for derive_failure_reason, not an omission.
  615. "0300_8003": "spaghettiDetached",
  616. "0C00_8042": "spaghettiDetached",
  617. }
  618. def _hms_short_code(attr: int, code: int | str) -> str:
  619. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  620. if isinstance(code, str):
  621. code_int = int(code.replace("0x", ""), 16) if code else 0
  622. else:
  623. code_int = int(code or 0)
  624. attr_int = int(attr or 0)
  625. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  626. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  627. """Derive the failure_reason key for an archived print.
  628. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  629. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  630. no HMS code matches (don't guess — null is honest). The keys are the
  631. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  632. translated at render time.
  633. """
  634. if status in ("aborted", "cancelled"):
  635. return "userCancelled"
  636. if status != "failed":
  637. return None
  638. for err in hms_errors or []:
  639. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  640. if short_code in _HMS_FAILURE_REASONS:
  641. return _HMS_FAILURE_REASONS[short_code]
  642. return None
  643. # Track created_by_id for expected prints so the user email can be sent even when
  644. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  645. # {(printer_id, filename): created_by_id}
  646. _expected_print_creators: dict[tuple[int, str], int] = {}
  647. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  648. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  649. # tag tuple changes for the slot. Cleared when the slot is reported empty
  650. # so remove + reinsert reliably re-prompts the UI.
  651. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  652. async def _broadcast_unknown_tag(
  653. *,
  654. printer_id: int,
  655. ams_id: int,
  656. tray_id: int,
  657. tag_uid: str,
  658. tray_uuid: str,
  659. tray_type: str | None = None,
  660. tray_color: str | None = None,
  661. tray_sub_brands: str | None = None,
  662. tray_count: int | None = None,
  663. ) -> None:
  664. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  665. _logger = logging.getLogger(__name__)
  666. slot_key = (ams_id, tray_id)
  667. tag_key = (tag_uid or "", tray_uuid or "")
  668. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  669. if per_printer.get(slot_key) == tag_key:
  670. _logger.debug(
  671. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  672. printer_id,
  673. ams_id,
  674. tray_id,
  675. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  676. )
  677. return
  678. _logger.info(
  679. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  680. printer_id,
  681. ams_id,
  682. tray_id,
  683. tray_type,
  684. tray_color,
  685. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  686. )
  687. # Broadcast first; only commit the dedup if the WS write succeeds.
  688. # If broadcast raises, the next MQTT push retries instead of being
  689. # permanently silenced by a poisoned dedup entry.
  690. await ws_manager.broadcast(
  691. {
  692. "type": "unknown_tag",
  693. "printer_id": printer_id,
  694. "ams_id": ams_id,
  695. "tray_id": tray_id,
  696. "tag_uid": tag_uid,
  697. "tray_uuid": tray_uuid,
  698. "tray_type": tray_type,
  699. "tray_color": tray_color,
  700. "tray_sub_brands": tray_sub_brands,
  701. "tray_count": tray_count,
  702. }
  703. )
  704. per_printer[slot_key] = tag_key
  705. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  706. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  707. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  708. if per_printer is None:
  709. return
  710. per_printer.pop((ams_id, tray_id), None)
  711. # TTL for expected-print entries: evict registrations older than this to prevent
  712. # unbounded growth when a print is registered but never starts (e.g. printer
  713. # disconnect, app restart, print started from the printer panel).
  714. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  715. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  716. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  717. # Cleanup loop interval
  718. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  719. _expected_prints_cleanup_task: asyncio.Task | None = None
  720. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  721. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  722. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  723. possible_keys: list[tuple[int, str]] = []
  724. filename = (state.gcode_file or state.current_print or "").strip()
  725. subtask_name = (state.subtask_name or "").strip()
  726. if subtask_name:
  727. possible_keys.append((printer_id, subtask_name))
  728. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  729. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  730. if filename:
  731. base_name = filename.rsplit("/", 1)[-1]
  732. if base_name.endswith(".gcode.3mf"):
  733. root_name = base_name[: -len(".gcode.3mf")]
  734. possible_keys.append((printer_id, root_name))
  735. possible_keys.append((printer_id, base_name))
  736. possible_keys.append((printer_id, f"{root_name}.gcode"))
  737. possible_keys.append((printer_id, f"{root_name}.3mf"))
  738. elif base_name.endswith(".3mf"):
  739. root_name = base_name[: -len(".3mf")]
  740. possible_keys.append((printer_id, root_name))
  741. possible_keys.append((printer_id, base_name))
  742. elif base_name.endswith(".gcode"):
  743. root_name = base_name[: -len(".gcode")]
  744. possible_keys.append((printer_id, root_name))
  745. possible_keys.append((printer_id, f"{root_name}.3mf"))
  746. possible_keys.append((printer_id, base_name))
  747. else:
  748. possible_keys.append((printer_id, base_name))
  749. possible_keys.append((printer_id, f"{base_name}.3mf"))
  750. return possible_keys
  751. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  752. """The id of who started the print, unless that user has been deleted since.
  753. Deleting a user forgets them in printer_manager, but a print that ended a
  754. moment before still holds them.
  755. """
  756. if not print_user or print_user.get("user_id") is None:
  757. return None
  758. from backend.app.models.user import User
  759. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  760. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  761. """Check the cheap, process-local print ownership signals."""
  762. if printer_manager.get_current_print_user(printer_id):
  763. return True
  764. return any(
  765. key in _expected_prints or _active_prints.get(key) in _owned_print_archive_ids
  766. for key in _build_status_print_keys(printer_id, state)
  767. )
  768. def _reported_print_names(printer_id: int, state: PrinterState) -> set[str]:
  769. """The names the printer reports for its print, as it echoes them (spaces become underscores)."""
  770. return {_normalise_subtask_name(name) for _pid, name in _build_status_print_keys(printer_id, state)} - {""}
  771. async def _printing_archive_without_job_id(
  772. db, printer_id: int, reported: set[str], *, dispatched_only: bool, live_only: bool = False
  773. ):
  774. """The newest printing archive on ``printer_id`` of a print that reported no job id, under a reported name.
  775. An archive with a real id of its own is a print that reported one: a "0"
  776. print is not it, even under the same name (one whose completion was missed
  777. would otherwise cover it). ``dispatched_only`` keeps to archives carrying
  778. Bambuddy's dispatch marker; ``live_only`` leaves out deleted ones.
  779. """
  780. from backend.app.models.archive import PrintArchive
  781. query = select(PrintArchive).where(
  782. PrintArchive.printer_id == printer_id,
  783. PrintArchive.status == "printing",
  784. or_(PrintArchive.subtask_id.is_(None), PrintArchive.subtask_id.in_(("", "0"))),
  785. )
  786. if dispatched_only:
  787. query = query.where(or_(PrintArchive.billing_run_id.is_not(None), PrintArchive.created_by_id.is_not(None)))
  788. if live_only:
  789. query = query.where(PrintArchive.deleted_at.is_(None))
  790. archives = await db.execute(query.order_by(PrintArchive.created_at.desc()))
  791. return next((a for a in archives.scalars() if _archive_name_forms(a) & reported), None)
  792. async def running_print_archive(db, printer_id: int, state: PrinterState, *, printing_only: bool, by_name: bool):
  793. """The archive of the print running on ``printer_id``, or None (#3327).
  794. By the print's subtask_id first, which the firmware mints per print; with
  795. ``printing_only`` only an archive that is still printing (a leftover row of
  796. a completion never seen must not stand in for another job). A print
  797. started outside the cloud (Bambu Studio over LAN, Handy, the printer's
  798. screen) reports subtask_id "0", which links it to nothing: the archive
  799. Bambuddy bound to the running print comes next, the one completion charges
  800. and photographs. A restart forgets that binding and rebinds only Bambuddy's
  801. own prints, so with ``by_name`` a "0" print last falls back to its printing
  802. archive under the name the printer reports. That can be an earlier run of
  803. the same name whose completion was missed while Bambuddy was down: good
  804. enough for a plate label or a cover, not for which objects skip-objects
  805. offers, so those callers leave it off. None until the archive exists, and
  806. never a deleted one.
  807. """
  808. from backend.app.models.archive import PrintArchive
  809. from backend.app.services.print_log import open_run_on_printer
  810. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  811. if subtask_id not in ("", "0"):
  812. # The run open on the printer for this job: the archive row is shared
  813. # by every plate of it, its printer and job id the latest start's.
  814. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  815. if run is not None and run.archive_id is not None:
  816. archive = await db.scalar(
  817. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  818. )
  819. if archive is not None:
  820. return archive
  821. query = select(PrintArchive).where(
  822. PrintArchive.printer_id == printer_id,
  823. PrintArchive.subtask_id == subtask_id,
  824. PrintArchive.deleted_at.is_(None),
  825. )
  826. if printing_only:
  827. query = query.where(PrintArchive.status == "printing")
  828. archive = await db.scalar(query.order_by(PrintArchive.created_at.desc()).limit(1))
  829. if archive is not None:
  830. return archive
  831. bound = next(
  832. (_active_prints[key] for key in _build_status_print_keys(printer_id, state) if key in _active_prints),
  833. None,
  834. )
  835. if bound is not None:
  836. return await db.scalar(select(PrintArchive).where(PrintArchive.id == bound, PrintArchive.deleted_at.is_(None)))
  837. if not by_name or subtask_id != "0":
  838. return None
  839. reported = _reported_print_names(printer_id, state)
  840. if not reported:
  841. return None
  842. return await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=False, live_only=True)
  843. def _bind_active_print(
  844. printer_id: int,
  845. archive_id: int,
  846. archive_filename: str | None,
  847. filename: str | None = None,
  848. subtask_name: str | None = None,
  849. ) -> None:
  850. """Track a running print under every name its completion may report.
  851. One set for every path that binds a print (new archive, expected print,
  852. restart resume, fallback): the archive's file name, the name the printer
  853. reported, and the subtask with and without ``.3mf``. Paths that registered
  854. fewer names lost the bound archive at completion, and with it the plate
  855. restore's height (#3240), whenever MQTT reported a name they had left out.
  856. """
  857. for name in {archive_filename, filename, f"{subtask_name}.3mf" if subtask_name else None, subtask_name}:
  858. if name:
  859. _active_prints[(printer_id, name)] = archive_id
  860. async def _archive_of_open_run(printer_id: int, subtask_id: str | None = None) -> int | None:
  861. """The archive of the run open on the printer, if it is still there.
  862. With ``subtask_id``, only a run of that job."""
  863. try:
  864. from backend.app.models.archive import PrintArchive
  865. from backend.app.services.print_log import open_run_on_printer
  866. async with async_session() as db:
  867. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  868. if run is None or run.archive_id is None:
  869. return None
  870. return await db.scalar(
  871. select(PrintArchive.id).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  872. )
  873. except Exception as e:
  874. logging.getLogger(__name__).warning("[RUN] Could not read the open run of printer %s: %s", printer_id, e)
  875. return None
  876. async def _announce_discarded_runs(discarded, printer_id: int) -> None:
  877. """Publish the runs ``discard_open_runs`` dropped (archive redesign):
  878. each announced by run/started, now gone without an end."""
  879. if not discarded:
  880. return
  881. try:
  882. from backend.app.models.printer import Printer
  883. async with async_session() as db:
  884. printer = (
  885. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  886. ).first()
  887. if printer is not None:
  888. for run in discarded:
  889. await mqtt_relay.on_run_discarded(run, printer.serial_number, printer.name)
  890. except Exception as e:
  891. logging.getLogger(__name__).debug("[RUN] Could not announce discarded runs on printer %s: %s", printer_id, e)
  892. async def _publish_run_completed(run_id: int | None, printer_id: int) -> None:
  893. """Publish the run a print's end just wrote on the MQTT relay (archive
  894. redesign); nothing without one. Never in the way of the completion."""
  895. if run_id is None:
  896. return
  897. try:
  898. from backend.app.models.archive import PrintArchive
  899. from backend.app.models.print_log import PrintLogEntry
  900. from backend.app.models.printer import Printer
  901. async with async_session() as db:
  902. run = await db.get(PrintLogEntry, run_id)
  903. printer = (
  904. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  905. ).first()
  906. archive = await db.get(PrintArchive, run.archive_id) if run is not None and run.archive_id else None
  907. if run is not None and printer is not None:
  908. await mqtt_relay.on_run_completed(run, archive, printer.serial_number, printer.name)
  909. except Exception as e:
  910. logging.getLogger(__name__).debug("[RUN] Could not publish the end of run %s: %s", run_id, e)
  911. async def _open_run_for(archive_id: int, printer_id: int, subtask_id: str | None = None) -> None:
  912. """Write the run of the print that just started on the archive (archive
  913. redesign). In a session of its own and never in the way of the print
  914. start: until its readers move over, the archive still carries the print.
  915. The archive's start must be committed before. ``subtask_id`` is the
  916. printer's job, which finds the run again at a resume."""
  917. try:
  918. from backend.app.models.archive import PrintArchive
  919. from backend.app.models.printer import Printer
  920. from backend.app.services.print_log import open_run, open_run_on_printer, run_snapshot
  921. async with async_session() as db:
  922. archive = await db.get(PrintArchive, archive_id)
  923. if archive is None:
  924. return
  925. printer = (
  926. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  927. ).first()
  928. printer_name = printer.name if printer is not None else None
  929. already = await open_run_on_printer(db, printer_id)
  930. before = run_snapshot(already) if already is not None else None
  931. run = await open_run(
  932. db,
  933. archive,
  934. printer_id=printer_id,
  935. printer_name=printer_name,
  936. plate_id=_print_plate_ids.get((printer_id, archive_id)),
  937. subtask_id=subtask_id,
  938. )
  939. await db.commit()
  940. # Once per print: a resume or a repeated start finds the run it opened.
  941. # A new one replaced the run still open there (open_run): that one's
  942. # print ended unseen.
  943. # Compared by start too: SQLite can give the new run the id of the one
  944. # it replaced.
  945. replaced = (
  946. run is not None and before is not None and (before.id != run.id or before.started_at != run.started_at)
  947. )
  948. if run is not None and printer is not None and (before is None or replaced):
  949. if replaced:
  950. await _announce_discarded_runs([before], printer_id)
  951. try:
  952. await mqtt_relay.on_run_started(run, archive, printer.serial_number, printer_name)
  953. except Exception:
  954. pass # Don't fail the print start if MQTT fails
  955. except Exception as e:
  956. logging.getLogger(__name__).warning("[RUN] Could not open the run of archive %s: %s", archive_id, e)
  957. async def _drop_replaced_plate_videos(
  958. db, archive_id: int, plate_id: int | None, stale_relpath: str | None, logger: logging.Logger
  959. ) -> None:
  960. """Delete the videos a reprint of a plate replaces: ``stale_relpath``, the
  961. one the archive showed (when print start judged it this plate's), and
  962. those of the archive's earlier runs of the same plate. A plate keeps one
  963. video, as when the archive held the only one; another plate's stays. The
  964. runs that held them lose them. Commits."""
  965. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, PrintLogEntry
  966. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  967. runs = select(PrintLogEntry).where(
  968. PrintLogEntry.archive_id == archive_id, PrintLogEntry.timelapse_path.is_not(None)
  969. )
  970. with_video = list(await db.scalars(runs.execution_options(**{INCLUDE_OPEN_RUNS: True})))
  971. paths = {stale_relpath} if stale_relpath else set()
  972. if plate_id is not None:
  973. paths |= {r.timelapse_path for r in with_video if r.plate_id == plate_id}
  974. # A video another plate's run holds is that plate's.
  975. paths -= {r.timelapse_path for r in with_video if r.plate_id is not None and r.plate_id != plate_id}
  976. if not paths:
  977. return
  978. for run in with_video:
  979. if run.timelapse_path in paths:
  980. run.timelapse_path = None
  981. await db.commit()
  982. for relpath in sorted(p for p in paths if p):
  983. try:
  984. stale_path = safe_join_under(app_settings.base_dir, relpath, http=False)
  985. if stale_path.is_file():
  986. stale_path.unlink()
  987. logger.info("Deleted stale timelapse %s on reprint of archive %s", relpath, archive_id)
  988. except (OSError, PathTraversalError) as e:
  989. logger.warning("Failed to delete stale timelapse %s on reprint: %s", relpath, e)
  990. def _mark_owned_if_dispatched(archive) -> None:
  991. """Remember a running print's archive as Bambuddy's when it carries a
  992. dispatch marker Bambuddy writes itself: ``billing_run_id`` (minted per
  993. dispatch in the scheduler) or ``created_by_id`` (from the queue item)."""
  994. if archive.billing_run_id is not None or archive.created_by_id is not None:
  995. _owned_print_archive_ids.add(archive.id)
  996. async def _is_printer_kill_switch_enabled_cached() -> bool:
  997. """Return the kill-switch setting without querying on every MQTT frame."""
  998. global _kill_switch_setting_cache
  999. now = time.monotonic()
  1000. if _kill_switch_setting_cache is not None:
  1001. enabled, expires_at = _kill_switch_setting_cache
  1002. if now < expires_at:
  1003. return enabled
  1004. async with async_session() as db:
  1005. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  1006. enabled = await is_printer_kill_switch_enabled(db)
  1007. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  1008. return enabled
  1009. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  1010. """Resolve whether the current print was started by Bambuddy.
  1011. ``None`` means identity is not yet safe to decide. The kill switch must
  1012. defer in that case: stopping a print is irreversible, and the first status
  1013. frames after a restart may arrive before all subtask fields are populated.
  1014. """
  1015. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1016. return True
  1017. # The printer's built-in calibration runs (Bambuddy's Calibrate, the
  1018. # printer's screen) play gcode from its read-only system partition, where no
  1019. # user file can be. Only that path counts: a calibration *name* proves
  1020. # nothing, since Bambu Studio's pressure-advance print reports a user-style
  1021. # path, and any print can be given that name.
  1022. if str(getattr(state, "gcode_file", "") or "").startswith("/usr/"):
  1023. return True
  1024. # A1, A1 Mini, P1 and A2L report the same calibration as a bare file name,
  1025. # which nothing distinguishes from a user's file given that name, so it is
  1026. # not exempt: with the kill switch on, calibrate on those printers with the
  1027. # switch off.
  1028. possible_keys = _build_status_print_keys(printer_id, state)
  1029. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  1030. # is on disk. subtask_id is minted per print and pins the answer to the job
  1031. # actually running, rather than to an unrelated one that reuses a filename.
  1032. raw_subtask_id = getattr(state, "subtask_id", None)
  1033. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  1034. if subtask_id == "":
  1035. # Not reported yet: the first frames after a restart can lack it.
  1036. return None
  1037. from backend.app.models.archive import PrintArchive
  1038. if subtask_id == "0":
  1039. # A print started outside the cloud from Bambu Studio, Handy or the
  1040. # printer's screen reports "0", so there is no id to match: one of
  1041. # Bambuddy's printing archives on this printer under the name the
  1042. # printer reports, compared as the printer echoes names (spaces become
  1043. # underscores). Nothing reported to compare yet: wait.
  1044. reported = _reported_print_names(printer_id, state)
  1045. if not reported:
  1046. return None
  1047. archive = await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=True)
  1048. else:
  1049. from backend.app.services.print_log import open_run_on_printer
  1050. # This job's run open on the printer: the archive is shared by every
  1051. # plate of it, and its status, printer and job id are the latest
  1052. # start's, which may be another printer's.
  1053. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  1054. archive = await db.get(PrintArchive, run.archive_id) if run is not None and run.archive_id else None
  1055. if archive is None:
  1056. result = await db.execute(
  1057. select(PrintArchive)
  1058. .where(
  1059. PrintArchive.printer_id == printer_id,
  1060. PrintArchive.status == "printing",
  1061. PrintArchive.subtask_id == subtask_id,
  1062. )
  1063. .order_by(PrintArchive.created_at.desc())
  1064. .limit(1)
  1065. )
  1066. archive = result.scalar_one_or_none()
  1067. # An archive row on its own proves nothing: `on_print_start` archives every
  1068. # print it observes, including ones started from Bambu Studio or Handy, and
  1069. # stamps them with the same status and subtask_id. Authorizing on its mere
  1070. # existence would disable the kill switch the moment the 3MF finishes
  1071. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  1072. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  1073. # (carried over from the queue item that started it).
  1074. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  1075. # Rehydrate the fast in-memory path for subsequent status frames. Include
  1076. # both the archive filename and every normalized key reported by MQTT.
  1077. _owned_print_archive_ids.add(archive.id)
  1078. _active_prints[(printer_id, archive.filename)] = archive.id
  1079. for key in possible_keys:
  1080. _active_prints[key] = archive.id
  1081. return True
  1082. # No dispatch marker. Before calling this someone else's print, check whether
  1083. # Bambuddy has a job of its own running on this printer: a library-file
  1084. # dispatch has no archive at send time, and an archive created seconds later
  1085. # by `on_print_start` carries neither marker. The queue row, which the
  1086. # scheduler commits to status="printing" before the MQTT send, is the one
  1087. # durable record every Bambuddy print has. It cannot be tied to this
  1088. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  1089. # print is irreversible, and refusing to act costs nothing but a log line.
  1090. from backend.app.models.print_queue import PrintQueueItem
  1091. dispatched_here = await db.scalar(
  1092. select(PrintQueueItem.id)
  1093. .where(
  1094. PrintQueueItem.printer_id == printer_id,
  1095. PrintQueueItem.status == "printing",
  1096. )
  1097. .limit(1)
  1098. )
  1099. if dispatched_here is not None:
  1100. return None
  1101. return False
  1102. async def _send_kill_switch_provider_notification(
  1103. printer_id: int,
  1104. printer_name: str,
  1105. data: dict,
  1106. ) -> bool:
  1107. """Send the immediate print-stopped provider notification.
  1108. Returning a success flag lets the normal MQTT completion path retry when
  1109. this early notification could not be delivered.
  1110. """
  1111. logger = logging.getLogger(__name__)
  1112. try:
  1113. async with async_session() as db:
  1114. from backend.app.services.print_log import open_run_on_printer
  1115. # The print it stopped, for {archive_id} / {run_id}: the completion
  1116. # that would name them skips its notification after this one.
  1117. run = await open_run_on_printer(db, printer_id)
  1118. await notification_service.on_print_complete(
  1119. printer_id,
  1120. printer_name,
  1121. "stopped",
  1122. data,
  1123. db,
  1124. archive_data={"archive_id": run.archive_id, "run_id": run.id} if run is not None else None,
  1125. )
  1126. return True
  1127. except Exception as e:
  1128. logger.warning(
  1129. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  1130. printer_id,
  1131. e,
  1132. )
  1133. return False
  1134. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  1135. """Wait for an immediate kill-switch notification, if one was scheduled."""
  1136. if task is None:
  1137. return False
  1138. try:
  1139. return await task
  1140. except Exception as e:
  1141. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  1142. return False
  1143. async def _run_needs_energy_start(archive, printer_id: int, db) -> bool:
  1144. """At a resume: whether the print's run still lacks its energy start
  1145. reading. The archive's may be an earlier print's. Commits a reading
  1146. found on the archive for this run onto it."""
  1147. try:
  1148. from backend.app.services.print_log import run_needs_energy_start
  1149. needs = await run_needs_energy_start(db, archive, printer_id=printer_id)
  1150. await db.commit()
  1151. return needs
  1152. except Exception as e:
  1153. logging.getLogger(__name__).warning("[RUN] Energy start of archive %s's run not checked: %s", archive.id, e)
  1154. return archive.energy_start_kwh is None
  1155. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  1156. """Capture the smart plug lifetime counter on the archive at print start.
  1157. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  1158. tracking survives a backend restart mid-print. The print-end handler reads
  1159. this value back from the DB and computes the delta against the current
  1160. plug counter.
  1161. """
  1162. _logger = logging.getLogger(__name__)
  1163. try:
  1164. candidates = await energy_plug_candidates(db, printer_id)
  1165. if not candidates:
  1166. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  1167. return False
  1168. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  1169. if selected is None:
  1170. # Naming the plugs matters here: with several linked to one printer
  1171. # this is the difference between "the meter is offline" and "you
  1172. # linked only accessories" (#2859).
  1173. _logger.warning(
  1174. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  1175. printer_id,
  1176. archive.id,
  1177. ", ".join(plug.name for plug in candidates),
  1178. )
  1179. return False
  1180. plug, energy = selected
  1181. archive.energy_start_kwh = float(energy["total"])
  1182. # With the plug's snapshots, what lets the cost follow the price over
  1183. # the print rather than take the price at its end (#1251). A price that
  1184. # can't be had must not cost the print its energy reading.
  1185. archive.energy_start_at = utcnow_naive()
  1186. archive.energy_start_plug_id = plug.id
  1187. try:
  1188. from backend.app.services.energy_price import current_price
  1189. archive.energy_start_price = await current_price(db)
  1190. except Exception as e:
  1191. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  1192. archive.energy_start_price = None
  1193. try:
  1194. from backend.app.services.print_log import mirror_energy_start
  1195. await mirror_energy_start(db, archive, printer_id=printer_id)
  1196. except Exception as e:
  1197. _logger.warning("[RUN] Energy start not copied onto the run of archive %s: %s", archive.id, e)
  1198. await db.commit()
  1199. _logger.info(
  1200. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  1201. f" ({context})" if context else "",
  1202. archive.id,
  1203. plug.name,
  1204. energy["total"],
  1205. )
  1206. return True
  1207. except Exception as e:
  1208. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  1209. return False
  1210. def forget_print_creator(user_id: int) -> None:
  1211. """The print-start emails of a deleted user's jobs go to nobody, not to
  1212. whoever is given the id next (SQLite reuses it)."""
  1213. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  1214. del _expected_print_creators[key]
  1215. async def forget_printer(printer_id: int) -> None:
  1216. """Drop what is kept for a deleted printer's id, here and in the services.
  1217. SQLite used to give the id to the next printer created, which inherited it
  1218. all: the running print's owner (its prints passed the kill switch and were
  1219. billed to that user), the plate-clear gate, pending and suppressed
  1220. notifications, the camera feed, the plate references. Ids are no longer
  1221. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  1222. stay. Called after the delete is committed, and again by work that was in
  1223. flight and wrote state back.
  1224. Every printer-keyed map of this module is listed here or, with the reason,
  1225. in tests/unit/test_forget_printer.py.
  1226. """
  1227. from backend.app.api.routes import camera
  1228. from backend.app.services import (
  1229. bambu_ftp,
  1230. kprofile_drift,
  1231. layer_timelapse,
  1232. plate_detection,
  1233. print_dispatch_context,
  1234. usage_tracker,
  1235. )
  1236. from backend.app.services.notify_live_activities import notify_live_activities
  1237. from backend.app.services.obico_detection import obico_detection_service
  1238. from backend.app.services.printer_file_cache import printer_file_cache
  1239. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  1240. archive_ids = set()
  1241. for tracked in (_active_prints, _expected_prints):
  1242. for key in [key for key in tracked if key[0] == printer_id]:
  1243. archive_ids.add(tracked.pop(key))
  1244. for archive_id in archive_ids:
  1245. _owned_print_archive_ids.discard(archive_id)
  1246. for registered in (_print_ams_mappings, _print_cost_center_ids, _print_plate_ids):
  1247. for key in [key for key in registered if key[0] == printer_id]:
  1248. del registered[key]
  1249. for tracked in (_expected_print_creators, _expected_print_registered_at):
  1250. for key in [key for key in tracked if key[0] == printer_id]:
  1251. del tracked[key]
  1252. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  1253. _ams_index_only_logged.discard(key)
  1254. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  1255. del _ams_alarm_cooldown[key]
  1256. # Pending work that would act on the id: an offline notice, a 3MF retry.
  1257. # A kill-switch notice is about a stop that happened and is left to finish.
  1258. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  1259. task = tasks.pop(printer_id, None)
  1260. if task is not None:
  1261. task.cancel()
  1262. for keyed in (
  1263. _stage22_finish_frames,
  1264. _stage22_finish_in_flight,
  1265. _inprint_frame_bank,
  1266. _inprint_frame_bank_ts,
  1267. _printer_reconciled_since_connect,
  1268. _printer_kprofiles_primed_since_connect,
  1269. _last_progress_milestone,
  1270. _first_layer_notified,
  1271. _kill_switch_notification_tasks,
  1272. _notified_hms_errors,
  1273. _hms_print_state,
  1274. _hms_forget_when_gone,
  1275. _timelapse_baselines,
  1276. _bed_cool_waiters,
  1277. _printer_last_connected,
  1278. _unknown_tag_last_broadcast,
  1279. _last_status_broadcast,
  1280. _connection_watchdog_last_attempt,
  1281. ):
  1282. keyed.pop(printer_id, None)
  1283. for marked in (
  1284. _unauthorized_print_kill_sent,
  1285. _user_stopped_printers,
  1286. _kill_switch_stopped,
  1287. _printer_offline_published,
  1288. _nozzle_count_updated,
  1289. _runtime_seen_connected,
  1290. _timelapse_baselines_unread,
  1291. ):
  1292. marked.discard(printer_id)
  1293. printer_manager.forget_printer(printer_id)
  1294. printer_file_cache.forget_printer(printer_id)
  1295. print_dispatch_context.clear(printer_id)
  1296. kprofile_drift.forget_printer(printer_id, deleted=True)
  1297. layer_timelapse.cancel_session(printer_id)
  1298. usage_tracker.forget_printer(printer_id)
  1299. obico_detection_service.forget_printer(printer_id)
  1300. bambu_ftp.clear_3mf_cache(printer_id)
  1301. await camera.forget_printer(printer_id)
  1302. printers.clear_cover_cache(printer_id)
  1303. print_scheduler.forget_printer(printer_id)
  1304. notify_live_activities.forget_printer(printer_id)
  1305. plate_detection.remove_printer_references(printer_id)
  1306. def register_expected_print(
  1307. printer_id: int,
  1308. filename: str,
  1309. archive_id: int,
  1310. ams_mapping: list[int] | None = None,
  1311. created_by_id: int | None = None,
  1312. cost_center_id: int | None = None,
  1313. plate_id: int | None = None,
  1314. ):
  1315. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1316. # Store with multiple filename variations to catch different naming patterns
  1317. _expected_prints[(printer_id, filename)] = archive_id
  1318. # Also store without .3mf extension if present
  1319. if filename.endswith(".3mf"):
  1320. base = filename[:-4]
  1321. _expected_prints[(printer_id, base)] = archive_id
  1322. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1323. # Store AMS mapping for usage tracking at print completion, and plate_id for
  1324. # a single-plate dispatch from a multi-plate 3MF — without it, the direct-Print
  1325. # path attributes the whole file's filament total to the spool instead of just
  1326. # the printed plate (#1697). They describe this dispatch: one that has none
  1327. # drops what an earlier dispatch of the archive left (sent, never started),
  1328. # unless a plate of the archive is printing now and still needs them.
  1329. dispatch = (printer_id, archive_id)
  1330. archive_printing = _printing_here(printer_id, archive_id)
  1331. if ams_mapping is not None:
  1332. _print_ams_mappings[dispatch] = ams_mapping
  1333. elif not archive_printing:
  1334. _print_ams_mappings.pop(dispatch, None)
  1335. if cost_center_id is not None:
  1336. _print_cost_center_ids[dispatch] = cost_center_id
  1337. elif not archive_printing:
  1338. _print_cost_center_ids.pop(dispatch, None)
  1339. if plate_id is not None:
  1340. _print_plate_ids[dispatch] = plate_id
  1341. elif not archive_printing:
  1342. _print_plate_ids.pop(dispatch, None)
  1343. # Store created_by_id so the user start email can be sent even when the archive
  1344. # itself has no created_by_id (e.g. library-file-based queue prints)
  1345. if created_by_id is not None:
  1346. _expected_print_creators[(printer_id, filename)] = created_by_id
  1347. if filename.endswith(".3mf"):
  1348. base = filename[:-4]
  1349. _expected_print_creators[(printer_id, base)] = created_by_id
  1350. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1351. # Record registration time for TTL-based eviction
  1352. _registered_at = time.monotonic()
  1353. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1354. if filename.endswith(".3mf"):
  1355. base = filename[:-4]
  1356. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1357. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1358. logging.getLogger(__name__).info(
  1359. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1360. )
  1361. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1362. """Undo :func:`register_expected_print` when the print never went out.
  1363. Registration has to happen *before* the MQTT print command, because the
  1364. printer can report the print before the line after the send executes. So
  1365. every path that registers and then fails to send — a cancel winning the
  1366. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1367. between — leaves an expectation for a print that will never arrive.
  1368. The TTL sweep evicts those after two hours, which is far longer than it
  1369. takes a user to react to a failed dispatch by pressing print again: that
  1370. reprint would be folded into the *old* archive and take the stale
  1371. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1372. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1373. ``_print_ams_mappings`` / ``_print_plate_ids`` / ``_print_cost_center_ids``
  1374. are keyed by printer and archive, not by file, so they may only be dropped
  1375. once no live key of the printer still points at that archive.
  1376. """
  1377. keys = [(printer_id, filename)]
  1378. if filename.endswith(".3mf"):
  1379. base = filename[:-4]
  1380. keys.append((printer_id, base))
  1381. keys.append((printer_id, f"{base}.gcode"))
  1382. removed = False
  1383. for key in keys:
  1384. if _expected_prints.pop(key, None) is not None:
  1385. removed = True
  1386. _expected_print_creators.pop(key, None)
  1387. _expected_print_registered_at.pop(key, None)
  1388. # Still needed by another expected print of the archive on the printer,
  1389. # or a plate of it printing there, as in the sweep.
  1390. if not _expected_or_printing_here(printer_id, archive_id):
  1391. _drop_dispatch(printer_id, archive_id)
  1392. if removed:
  1393. logging.getLogger(__name__).info(
  1394. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1395. printer_id,
  1396. filename,
  1397. archive_id,
  1398. )
  1399. def _compute_run_filament_grams(
  1400. status: str,
  1401. archive_filament_used_grams: float | None,
  1402. progress: float | int | None,
  1403. usage_results: list[dict] | None,
  1404. ) -> float | None:
  1405. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1406. Priority for every status:
  1407. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1408. weight delta — same source that drives "Total Consumed" on the
  1409. Inventory page, so Stats and Inventory totals stay aligned).
  1410. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1411. back to the canonical "this print used X" value).
  1412. 3. For partial statuses: ``estimate * progress%``.
  1413. 4. ``None`` if nothing is known.
  1414. """
  1415. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1416. if tracked_grams > 0:
  1417. return round(tracked_grams, 1)
  1418. if status == "completed":
  1419. return archive_filament_used_grams
  1420. if archive_filament_used_grams:
  1421. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1422. if scale > 0:
  1423. return round(archive_filament_used_grams * scale, 1)
  1424. return None
  1425. def _printing_here(printer_id: int, archive_id: int) -> bool:
  1426. """Whether a plate of the archive is printing on the printer."""
  1427. return any(key[0] == printer_id and bound == archive_id for key, bound in _active_prints.items())
  1428. def _expected_or_printing_here(printer_id: int, archive_id: int) -> bool:
  1429. """Whether a print of the archive is expected or printing on the printer."""
  1430. return _printing_here(printer_id, archive_id) or any(
  1431. key[0] == printer_id and expected == archive_id for key, expected in _expected_prints.items()
  1432. )
  1433. def _drop_dispatch(printer_id: int, archive_id: int) -> None:
  1434. """Forget what the dispatch of the archive to the printer registered."""
  1435. dispatch = (printer_id, archive_id)
  1436. _print_ams_mappings.pop(dispatch, None)
  1437. _print_cost_center_ids.pop(dispatch, None)
  1438. _print_plate_ids.pop(dispatch, None)
  1439. def _get_start_ams_mapping(data: dict, printer_id: int, archive_id: int | None) -> list[int] | None:
  1440. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1441. stored_ams_mapping = data.get("ams_mapping")
  1442. if not stored_ams_mapping and archive_id:
  1443. stored_ams_mapping = _print_ams_mappings.get((printer_id, archive_id))
  1444. return stored_ams_mapping
  1445. def _get_start_plate_id(printer_id: int, archive_id: int | None) -> int | None:
  1446. """Resolve plate_id for print start without consuming stored direct-Print state.
  1447. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1448. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1449. read it back at print-start without popping (the entry is popped on print
  1450. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1451. """
  1452. if archive_id is None:
  1453. return None
  1454. return _print_plate_ids.get((printer_id, archive_id))
  1455. def _run_print_time_seconds(archive, printer_id: int) -> int | None:
  1456. """The slicer's time for the plate this print prints, for its start
  1457. notification (#3375): ``archive.print_time_seconds`` adds every plate of
  1458. the file up (#1593). The plate is the dispatch's, else the archive's. The
  1459. whole file's time when its plates are not known; None for a plate not
  1460. known of several, and the notification takes the printer's remaining
  1461. time."""
  1462. from backend.app.services.print_cost_estimate import run_estimate
  1463. plate_id = _print_plate_ids.get((printer_id, archive.id), archive.plate_id)
  1464. estimate = run_estimate(archive, plate_id)
  1465. return estimate.seconds if estimate is not None else None
  1466. _plate_estimates_task: asyncio.Task | None = None
  1467. async def _fill_plate_estimates() -> None:
  1468. from backend.app.services.print_cost_estimate import fill_plate_estimates
  1469. try:
  1470. filled = await fill_plate_estimates(async_session)
  1471. except asyncio.CancelledError:
  1472. raise
  1473. except Exception as exc:
  1474. logging.getLogger(__name__).warning("[ARCHIVE] Reading plate estimates failed: %s", exc)
  1475. return
  1476. if filled:
  1477. logging.getLogger(__name__).info("[ARCHIVE] Read the plate estimates of %d archive(s)", filled)
  1478. def _partial_progress_scale(progress: int | float | None) -> float:
  1479. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1480. Used by every site that multiplies a "would-have-used" slicer estimate
  1481. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1482. so the three sites in ``_background_notifications`` (and the per-plate
  1483. override helper) can't drift apart on the coercion shape.
  1484. """
  1485. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1486. def _scope_notification_archive_data_to_plate(
  1487. archive_data: dict,
  1488. archive_file_path: str | None,
  1489. plate_id: int | None,
  1490. print_status: str,
  1491. progress: int | float | None,
  1492. base_dir: Path,
  1493. ) -> dict:
  1494. """Override summed-across-plates totals in ``archive_data`` with the values
  1495. for ``plate_id`` so the completion notification reports what was actually
  1496. printed, not the whole project (#1785).
  1497. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1498. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1499. the archive card's "whole project" headline, wrong for the completion
  1500. notification of a single-plate print. The queue UI already re-reads the
  1501. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1502. notification payload (filament grams, time estimate, per-slot breakdown).
  1503. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1504. no per-plate values — in every fail case the original ``archive_data`` is
  1505. returned unchanged so the notification still sends.
  1506. """
  1507. if plate_id is None or not archive_file_path:
  1508. return archive_data
  1509. from backend.app.utils.threemf_tools import (
  1510. extract_filament_usage_from_3mf,
  1511. extract_print_time_from_3mf,
  1512. )
  1513. archive_path = base_dir / archive_file_path
  1514. if not archive_path.exists():
  1515. return archive_data
  1516. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1517. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1518. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1519. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1520. if plate_time:
  1521. archive_data["print_time_seconds"] = plate_time
  1522. # Gate both the grams headline AND the per-slot breakdown on the same
  1523. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1524. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1525. # to the project-level grams the archive columns already provide rather
  1526. # than ship a project-level headline next to an all-zero per-plate
  1527. # breakdown.
  1528. if plate_grams > 0:
  1529. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1530. archive_data["filament_slots"] = [
  1531. {
  1532. "slot_id": s.get("slot_id"),
  1533. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1534. "type": s.get("type", ""),
  1535. "color": s.get("color", ""),
  1536. }
  1537. for s in plate_slots
  1538. ]
  1539. return archive_data
  1540. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1541. """Best-effort filament metadata from the MQTT print-start snapshot.
  1542. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1543. file during print, see #1533) so the fallback PrintArchive still has
  1544. enough filament info to support the inventory views and AMS-expansion
  1545. planning the operator opens it for. Returns a dict with optional
  1546. ``filament_type`` and ``filament_color`` keys in the same
  1547. comma-separated format the 3MF extractor produces, so the rest of the
  1548. codebase treats the fallback archive identically to a normal one.
  1549. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1550. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1551. entries). When supplied, only the slots actually consumed by this
  1552. print contribute. Without it the function falls back to every loaded
  1553. AMS slot — less accurate but still useful.
  1554. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1555. that the unit tests pass directly, AND the on_print_start callback
  1556. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1557. bambu_mqtt service hands to main.py at runtime. The original
  1558. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1559. handled the inner shape and silently returned ``{}`` for every real
  1560. print start, leaving fallback archives' filament fields NULL — the
  1561. exact regression the fix was meant to close. Reported with a log
  1562. proving the AMS state was right there at
  1563. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1564. """
  1565. result: dict[str, str] = {}
  1566. # Look at the on_print_start wrapper first, then the inner shape.
  1567. raw_data = (data or {}).get("raw_data")
  1568. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1569. if not isinstance(ams_root, dict):
  1570. ams_root = (data or {}).get("ams") or {}
  1571. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1572. if not isinstance(ams_units, list) or not ams_units:
  1573. return result
  1574. from backend.app.services.print_scheduler import _global_tray_id
  1575. # Map global tray id → (type, color), addressed as the print's ams_mapping
  1576. # is: unit * 4 + tray, or the bare unit id for an AMS-HT (from 128).
  1577. loaded: dict[int, tuple[str, str]] = {}
  1578. for unit in ams_units:
  1579. if not isinstance(unit, dict):
  1580. continue
  1581. try:
  1582. unit_id = int(unit.get("id", 0))
  1583. except (TypeError, ValueError):
  1584. continue
  1585. for tray in unit.get("tray") or []:
  1586. if not isinstance(tray, dict):
  1587. continue
  1588. try:
  1589. tray_id = int(tray.get("id", 0))
  1590. except (TypeError, ValueError):
  1591. continue
  1592. ttype = (tray.get("tray_type") or "").strip()
  1593. # RRGGBBAA from the printer, stored as the 3MF path stores it:
  1594. # "#RRGGBB" (the Archives page's swatches and colour filter).
  1595. hex_color = (tray.get("tray_color") or "").strip().upper()[:6]
  1596. tcolor = f"#{hex_color}" if re.fullmatch(r"[0-9A-F]{6}", hex_color) else ""
  1597. if not ttype:
  1598. continue # Empty / unloaded slot.
  1599. loaded[_global_tray_id(unit_id, tray_id)] = (ttype, tcolor)
  1600. if not loaded:
  1601. return result
  1602. if ams_mapping:
  1603. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1604. filaments = [loaded[g] for g in used_ids if g in loaded]
  1605. if not filaments:
  1606. return result # Mapping points entirely at slots we have no data for.
  1607. else:
  1608. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1609. types_joined = ",".join(f[0] for f in filaments)
  1610. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1611. # Column limits per backend/app/models/archive.py: filament_type=50,
  1612. # filament_color=200.
  1613. if types_joined:
  1614. result["filament_type"] = types_joined[:50]
  1615. if colors_joined:
  1616. result["filament_color"] = colors_joined[:200]
  1617. return result
  1618. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1619. """Start a layer-timelapse session for *archive_id* when the printer has
  1620. an external camera configured. Returns True if a session was started.
  1621. Three call sites in on_print_start (expected-archive promotion, fallback
  1622. archive creation, fresh-archive creation) used to inline this same
  1623. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1624. on the first pass). Centralising the conditional + call here makes the
  1625. contract testable in isolation and keeps the three sites locked in step.
  1626. """
  1627. if not (printer.external_camera_enabled and printer.external_camera_url):
  1628. return False
  1629. from backend.app.services.layer_timelapse import start_session
  1630. start_session(
  1631. printer_id,
  1632. archive_id,
  1633. printer.external_camera_url,
  1634. printer.external_camera_type or "mjpeg",
  1635. snapshot_url=printer.external_camera_snapshot_url,
  1636. rotation=getattr(printer, "camera_rotation", 0),
  1637. )
  1638. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1639. return True
  1640. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1641. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1642. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1643. — since #2926 — the description the parser already resolved, which is preferred
  1644. when present so the queue's failure reason reads the same as the status
  1645. response. The short code still produces the bracketed label, and still
  1646. resolves the sentence for a caller whose entries predate the field. An entry
  1647. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1648. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1649. label when no description is on file. Returns None for an empty list so
  1650. callers can leave error_message unset.
  1651. """
  1652. if not hms_errors:
  1653. return None
  1654. from backend.app.services.hms_errors import get_error_description
  1655. parts: list[str] = []
  1656. for err in hms_errors:
  1657. try:
  1658. # `_hms_short_code` rather than a local derivation: this one used to
  1659. # format the error without masking it to 16 bits, so an `hms[]` entry
  1660. # whose code carries an alert-level group produced a five-digit label
  1661. # like "0500_3000A" — not a code the user can look up, and never a
  1662. # catalogue key, so the sentence was lost with it.
  1663. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1664. except (TypeError, ValueError):
  1665. continue
  1666. description = err.get("description") or get_error_description(short_code)
  1667. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1668. # groups and is not a code anyone can look up; its full code in the
  1669. # printer screen's four groups is (#2728).
  1670. full_code = str(err.get("full_code") or "")
  1671. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1672. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1673. return "; ".join(parts) if parts else None
  1674. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1675. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1676. print completes successfully. Gated to status=='completed': failed, cancelled
  1677. and aborted prints do not count as usage. Caller is responsible for committing
  1678. the session. No-op when the queue item has no linked library file (e.g. reprints
  1679. from an archive). See #1008."""
  1680. if queue_status != "completed" or item.library_file_id is None:
  1681. return
  1682. from backend.app.models.library import LibraryFile
  1683. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1684. if lib_file is None:
  1685. return
  1686. lib_file.print_count = (lib_file.print_count or 0) + 1
  1687. lib_file.last_printed_at = datetime.now(timezone.utc)
  1688. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1689. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1690. When on_print_complete fires with status 'failed' for a printer in this set we
  1691. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1692. rather than a 'print failed' notification.
  1693. """
  1694. _user_stopped_printers.add(printer_id)
  1695. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1696. _last_status_broadcast: dict[int, str] = {}
  1697. # Track printers where we've updated nozzle_count
  1698. _nozzle_count_updated: set[int] = set()
  1699. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1700. """Wait the debounce window then fire `on_printer_offline` if the printer
  1701. is still offline.
  1702. Scheduled by `on_printer_status_change` on the connected → disconnected
  1703. edge (#1752). Cancelled by the same handler if the printer reconnects
  1704. before the window elapses, so a single MQTT blip + recovery doesn't
  1705. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1706. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1707. route through the same status-change callback, so this covers both.
  1708. """
  1709. logger = logging.getLogger(__name__)
  1710. try:
  1711. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1712. still_offline = not printer_manager.is_connected(printer_id)
  1713. logger.info(
  1714. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1715. printer_id,
  1716. still_offline,
  1717. )
  1718. if not still_offline:
  1719. return
  1720. async with async_session() as db:
  1721. from backend.app.models.printer import Printer
  1722. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1723. printer = result.scalar_one_or_none()
  1724. if not printer:
  1725. logger.warning(
  1726. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1727. printer_id,
  1728. )
  1729. return
  1730. # Recorded only when the relay can publish it, so the reconnect's
  1731. # online event always has an offline before it.
  1732. if mqtt_relay.enabled and mqtt_relay.connected:
  1733. _printer_offline_published.add(printer_id)
  1734. try:
  1735. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1736. except Exception as e:
  1737. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1738. logger.info(
  1739. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1740. printer_id,
  1741. printer.name,
  1742. )
  1743. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1744. except asyncio.CancelledError:
  1745. raise
  1746. except Exception as e:
  1747. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1748. finally:
  1749. _printer_offline_notify_tasks.pop(printer_id, None)
  1750. def _hms_notify_key(error) -> str:
  1751. """What identifies a fault for notification de-duplication.
  1752. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1753. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1754. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1755. and -0006 together) shared a key and only the first was ever notified. An
  1756. entry without a full code falls back to attr and code together.
  1757. """
  1758. full_code = getattr(error, "full_code", "") or ""
  1759. if full_code:
  1760. return full_code.upper()
  1761. return f"{error.attr:08X}:{error.code}"
  1762. def _hms_fault_counts(error) -> bool:
  1763. """Whether a fault counts as a problem: the same rule the frontend's
  1764. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1765. It counts when Bambu publishes text for it or it offers action buttons, and
  1766. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1767. no actions does not count: those are things like "the top cover is open" or
  1768. "the chamber is hot, fan speed increased", which a printer can hold through
  1769. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1770. it always has; those are prompts such as "unable to start drying" (#2728).
  1771. """
  1772. if error.severity < 1:
  1773. return False
  1774. has_actions = bool(getattr(error, "actions", None))
  1775. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1776. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1777. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1778. """The new faults that count (see ``_hms_fault_counts``).
  1779. These go to the MQTT relay; the caller also needs a description before it
  1780. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1781. used to read ``severity >= 2`` when severity held the part byte; on the real
  1782. level that would drop the task-stopping errors (#2728).
  1783. """
  1784. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1785. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1786. """The faults on this printer not notified yet, and record them as notified.
  1787. Tracking is updated before anything is sent, so concurrent status callbacks
  1788. cannot notify the same fault twice. A notified fault is forgotten once it
  1789. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1790. and on is notified once (#3226), while one that clears and comes back much
  1791. later is notified again.
  1792. When ``print_state`` changes (a print resumed, started or finished), every
  1793. fault recorded so far is forgotten the first time it is gone, without the
  1794. wait: a runout fixed before resuming must be notified if it happens again a
  1795. few minutes later, while the printer sits paused. Not only the faults gone
  1796. at the change itself, because the update that flips the state can still
  1797. carry the old fault (a ``print_error`` entry stays until a payload brings
  1798. ``hms``).
  1799. """
  1800. now = time.time()
  1801. current = {_hms_notify_key(e) for e in errors}
  1802. seen = _notified_hms_errors.setdefault(printer_id, {})
  1803. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1804. if print_state is not None:
  1805. print_state = print_state.upper()
  1806. if _hms_print_state.get(printer_id, print_state) != print_state:
  1807. forget_when_gone.update(seen)
  1808. _hms_print_state[printer_id] = print_state
  1809. for key, last_seen in list(seen.items()):
  1810. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1811. del seen[key]
  1812. forget_when_gone.discard(key)
  1813. new = current - seen.keys()
  1814. for key in current:
  1815. seen[key] = now
  1816. if not seen:
  1817. _notified_hms_errors.pop(printer_id, None)
  1818. if not forget_when_gone:
  1819. _hms_forget_when_gone.pop(printer_id, None)
  1820. return _hms_errors_to_notify(errors, new)
  1821. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1822. # "Printing", -1 and 255 are "no stage" (#3211).
  1823. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1824. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1825. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1826. Records it as notified. Called only for a printing state with progress above 0.
  1827. Progress before the first layer is not progress through the print (#3211).
  1828. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1829. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1830. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1831. 75% notification together with Print Started, and since 75 was then on
  1832. record, 25 and 50 could never fire. So nothing counts while the printer
  1833. reports a layer count but has not started layer 1.
  1834. Without a layer count -- a print whose first frame carried no
  1835. ``total_layer_num``, until the pushall that asks for it is answered
  1836. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1837. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1838. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1839. reports neither keeps the old behaviour rather than never notifying.
  1840. """
  1841. if (state.layer_num or 0) < 1:
  1842. if (state.total_layers or 0) > 0:
  1843. return None
  1844. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1845. return None
  1846. progress = state.progress or 0
  1847. current_milestone = 0
  1848. if progress >= 75:
  1849. current_milestone = 75
  1850. elif progress >= 50:
  1851. current_milestone = 50
  1852. elif progress >= 25:
  1853. current_milestone = 25
  1854. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1855. _last_progress_milestone[printer_id] = current_milestone
  1856. return current_milestone
  1857. return None
  1858. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1859. """Handle printer status changes - broadcast via WebSocket."""
  1860. try:
  1861. notify_live_activities.observe(printer_id, state)
  1862. except Exception:
  1863. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1864. try:
  1865. pause_eta.observe(printer_id, state)
  1866. except Exception:
  1867. logging.getLogger(__name__).exception("Pause heads-up check failed for printer %s", printer_id)
  1868. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1869. # transitions disconnected → connected — which covers both Bambuddy
  1870. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1871. # `reconcile_stale_active_prints` exactly once for this connection so
  1872. # any archive still in `status="printing"` that can't actually be
  1873. # running anymore (printer IDLE / different subtask / empty subtask)
  1874. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1875. # finished during a disconnect window + a smart-plug power cycle
  1876. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1877. # next boot. Reconciliation runs concurrently — it must not block the
  1878. # WebSocket dedup / broadcast logic below, and the connected edge is
  1879. # marked True BEFORE the await so concurrent status updates inside
  1880. # the same connection don't re-trigger reconciliation.
  1881. #
  1882. # Wait for a real push_status before reconciling (#1679): MQTT
  1883. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1884. # the connection, BEFORE `_request_push_all` round-trips. At that
  1885. # instant the `PrinterState` is still on construction defaults — most
  1886. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1887. # If reconcile spawns here, every in-flight archive falls through to
  1888. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1889. # creates a duplicate archive on the real PRINT COMPLETE and
  1890. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1891. # keeps the #1542 mechanism intact: once the first real push_status
  1892. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1893. # fires again with the flag still False — reconcile then runs against
  1894. # actual evidence.
  1895. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1896. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1897. _printer_reconciled_since_connect[printer_id] = True
  1898. spawn_background_task(
  1899. reconcile_stale_active_prints(printer_id),
  1900. name=f"reconcile-stale-prints-{printer_id}",
  1901. )
  1902. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1903. # Re-arm so the next reconnect triggers reconciliation again.
  1904. _printer_reconciled_since_connect[printer_id] = False
  1905. # Same edge, for the calibration table the AMS card reads its K values from.
  1906. #
  1907. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1908. # tables to ask for. A `state_known` gate alone is not enough: the first
  1909. # real push_status is what makes the state known, and the nozzle fields do
  1910. # not always arrive in it. Latching there would spend this connection's one
  1911. # attempt on a printer that could not yet say what was fitted.
  1912. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1913. if (
  1914. state.connected
  1915. and state_known
  1916. and nozzle_known
  1917. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1918. ):
  1919. _printer_kprofiles_primed_since_connect[printer_id] = True
  1920. spawn_background_task(
  1921. prime_kprofile_table(printer_id),
  1922. name=f"prime-kprofiles-{printer_id}",
  1923. )
  1924. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1925. _printer_kprofiles_primed_since_connect[printer_id] = False
  1926. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1927. # else in the AMS report changing -- a power cycle does it to every slot --
  1928. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1929. # while the printer is idle; needs_check is cheap and throttled per slot.
  1930. # Guarded: nothing here may stop the status broadcast below.
  1931. try:
  1932. if not state.connected:
  1933. kprofile_drift.forget_printer(printer_id)
  1934. elif kprofile_drift.needs_check(printer_id, state):
  1935. spawn_background_task(
  1936. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1937. name=f"reapply-kprofiles-{printer_id}",
  1938. )
  1939. except Exception:
  1940. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1941. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1942. # connected → disconnected. The "back online" channel is already covered
  1943. # by the print-failure notification (firmware reports gcode_state=FAILED
  1944. # on reconnect of an interrupted print), so there is no online
  1945. # notification. The MQTT relay gets both: offline after the debounce, and
  1946. # online on the reconnect that follows a published offline.
  1947. prev_connected = _printer_last_connected.get(printer_id)
  1948. _printer_last_connected[printer_id] = state.connected
  1949. if prev_connected is True and not state.connected:
  1950. existing = _printer_offline_notify_tasks.get(printer_id)
  1951. if existing is None or existing.done():
  1952. logging.getLogger(__name__).info(
  1953. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1954. printer_id,
  1955. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1956. )
  1957. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1958. _maybe_notify_printer_offline(printer_id),
  1959. name=f"printer-offline-notify-{printer_id}",
  1960. )
  1961. elif state.connected:
  1962. # Kept until the relay can actually send online: with its broker down
  1963. # now, the next status update after the reconnect sends it.
  1964. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1965. _printer_offline_published.discard(printer_id)
  1966. printer_info = printer_manager.get_printer(printer_id)
  1967. if printer_info:
  1968. try:
  1969. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1970. except Exception as e:
  1971. logging.getLogger(__name__).warning(
  1972. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1973. )
  1974. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1975. if pending is not None and not pending.done():
  1976. logging.getLogger(__name__).info(
  1977. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1978. printer_id,
  1979. )
  1980. pending.cancel()
  1981. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1982. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1983. temps = state.temperatures or {}
  1984. nozzle_temp = round(temps.get("nozzle", 0))
  1985. bed_temp = round(temps.get("bed", 0))
  1986. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1987. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1988. # Auto-detect dual-nozzle printers from MQTT temperature data
  1989. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1990. _nozzle_count_updated.add(printer_id)
  1991. # Update nozzle_count in database
  1992. async with async_session() as db:
  1993. from backend.app.models.printer import Printer
  1994. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1995. printer = result.scalar_one_or_none()
  1996. if printer and printer.nozzle_count != 2:
  1997. printer.nozzle_count = 2
  1998. await db.commit()
  1999. logging.getLogger(__name__).info(
  2000. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  2001. )
  2002. # Include target temps for heating phase detection
  2003. bed_target = round(temps.get("bed_target", 0))
  2004. nozzle_target = round(temps.get("nozzle_target", 0))
  2005. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  2006. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  2007. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  2008. #
  2009. # dry_countdown_stalled rides along because it is the one drying signal the
  2010. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  2011. # dry_time stopped moving, so on the frame that flips it every other member
  2012. # of this key is identical and the push would be deduplicated away. Mid-print
  2013. # a temperature would eventually break the tie, but a parked command on an
  2014. # idle machine changes nothing else at all — AMS temp and humidity are not in
  2015. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  2016. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  2017. ams_dry_key = (
  2018. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  2019. if state.raw_data
  2020. else ()
  2021. )
  2022. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  2023. #
  2024. # The filament identity fields are here because Configure Slot writes
  2025. # exactly those and nothing else. Re-configuring a slot from PLA to another
  2026. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  2027. # matched, this function returned before broadcasting, and the card kept
  2028. # showing the old filament until the 30s fallback poll or a page reload —
  2029. # even though the configure route asks the printer for a fresh pushall and
  2030. # that push does carry the new values. Reset always worked, because it
  2031. # clears tray_type.
  2032. #
  2033. # These fields only change when someone configures a slot or swaps a spool,
  2034. # so unlike temperature or progress they add no broadcast traffic mid-print.
  2035. ams_tray_key = (
  2036. tuple(
  2037. (
  2038. t.get("id"),
  2039. t.get("tray_type", ""),
  2040. t.get("state"),
  2041. t.get("tray_color", ""),
  2042. t.get("tray_info_idx", ""),
  2043. t.get("tray_sub_brands", ""),
  2044. t.get("cali_idx"),
  2045. )
  2046. for a in (state.raw_data.get("ams") or [])
  2047. for t in a.get("tray", [])
  2048. )
  2049. if state.raw_data
  2050. else ()
  2051. )
  2052. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  2053. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  2054. # in the AMS change-hash (tray fields only, and widening that would fire
  2055. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  2056. # screen changed no key at all and the card's inlet badges sat stale until a
  2057. # reload. Like the filament-backup flag, these only move when someone
  2058. # reconfigures the machine, so they add no mid-print broadcast traffic.
  2059. fts_key = (
  2060. state.fila_switch.installed if state.fila_switch else False,
  2061. tuple(sorted(state.ams_switch_inlet.items())),
  2062. # Which hotend holds which slot. Unlike the two above this does move
  2063. # mid-print, on every filament change — but only between discrete slots,
  2064. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  2065. # it live: it decides which hotend the Load dialog may offer and whether
  2066. # Unload has anything to act on.
  2067. tuple(
  2068. sorted(
  2069. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  2070. # Sort on the extruder id alone: the other members are nullable
  2071. # and comparing None with an int raises.
  2072. key=lambda entry: entry[0],
  2073. )
  2074. ),
  2075. )
  2076. status_key = (
  2077. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  2078. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  2079. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  2080. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  2081. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  2082. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  2083. )
  2084. # Fields that change only when the machine does (a nozzle swap, a firmware
  2085. # update, developer mode) or once per print (its AMS mapping): no traffic,
  2086. # but on an idle printer nothing else moves the key when they change.
  2087. machine_key = (
  2088. tuple((n.nozzle_type, n.nozzle_diameter) for n in (state.nozzles or [])),
  2089. state.firmware_version,
  2090. state.developer_mode,
  2091. tuple(state.print_ams_mapping) if isinstance(state.print_ams_mapping, list) else None,
  2092. # Cooling/heating, switched on the printer's screen too: on an idle
  2093. # printer nothing else moves the key (PSF-4).
  2094. state.airduct_mode,
  2095. )
  2096. status_key = f"{status_key}:{machine_key}"
  2097. is_active_print = state.state in _ACTIVE_PRINT_STATES
  2098. if not is_active_print:
  2099. _unauthorized_print_kill_sent.discard(printer_id)
  2100. elif printer_id in _unauthorized_print_kill_sent:
  2101. # stop_print() was already sent for this print; avoid all further
  2102. # ownership and settings work until the printer leaves an active state.
  2103. pass
  2104. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  2105. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  2106. _unauthorized_print_kill_sent.discard(printer_id)
  2107. else:
  2108. kill_switch_enabled = False
  2109. authorization: bool | None = None
  2110. status_logger = logging.getLogger(__name__)
  2111. try:
  2112. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  2113. if kill_switch_enabled:
  2114. async with async_session() as db:
  2115. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  2116. except Exception as e:
  2117. # Fail safe: a database/reconciliation error must never turn into an
  2118. # irreversible stop of a print whose ownership is still unknown.
  2119. authorization = None
  2120. status_logger.warning(
  2121. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  2122. )
  2123. if not kill_switch_enabled or authorization is True:
  2124. _unauthorized_print_kill_sent.discard(printer_id)
  2125. elif authorization is None:
  2126. _unauthorized_print_kill_sent.discard(printer_id)
  2127. status_logger.debug(
  2128. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  2129. printer_id,
  2130. )
  2131. else:
  2132. try:
  2133. stopped = printer_manager.stop_print(printer_id)
  2134. if stopped:
  2135. _unauthorized_print_kill_sent.add(printer_id)
  2136. _kill_switch_stopped.add(printer_id)
  2137. printer_info = printer_manager.get_printer(printer_id)
  2138. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  2139. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  2140. notification_data = {
  2141. "status": "stopped",
  2142. "filename": state.gcode_file or state.current_print or "",
  2143. "subtask_name": state.subtask_name or "",
  2144. "progress": state.progress,
  2145. "reason": "unauthorized_print",
  2146. }
  2147. status_logger.warning(
  2148. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  2149. printer_id,
  2150. state.state,
  2151. )
  2152. try:
  2153. await ws_manager.broadcast(
  2154. {
  2155. "type": "kill_switch_triggered",
  2156. "printer_id": printer_id,
  2157. "printer_name": printer_name,
  2158. "filename": filename,
  2159. "reason": "unauthorized_print",
  2160. }
  2161. )
  2162. except Exception as e:
  2163. status_logger.warning(
  2164. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  2165. )
  2166. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  2167. if previous_task is not None and not previous_task.done():
  2168. previous_task.cancel()
  2169. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  2170. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  2171. name=f"kill-switch-notification-{printer_id}",
  2172. )
  2173. else:
  2174. status_logger.warning(
  2175. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  2176. printer_id,
  2177. state.state,
  2178. )
  2179. except Exception as e:
  2180. status_logger.warning(
  2181. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  2182. )
  2183. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  2184. try:
  2185. printer_info = printer_manager.get_printer(printer_id)
  2186. if printer_info:
  2187. await mqtt_relay.on_printer_status(
  2188. printer_id,
  2189. state,
  2190. printer_info.name,
  2191. printer_info.serial_number,
  2192. printer_manager.is_awaiting_plate_clear(printer_id),
  2193. )
  2194. except Exception:
  2195. pass # Don't fail status callback if MQTT fails
  2196. if _last_status_broadcast.get(printer_id) == status_key:
  2197. return # No change, skip WebSocket broadcast
  2198. _last_status_broadcast[printer_id] = status_key
  2199. # Check for progress milestone notifications (25%, 50%, 75%)
  2200. progress = state.progress or 0
  2201. is_printing = state.state in ("RUNNING", "PRINTING")
  2202. if is_printing and progress > 0:
  2203. current_milestone = _progress_milestone_to_notify(printer_id, state)
  2204. if current_milestone is not None:
  2205. try:
  2206. from backend.app.models.printer import Printer
  2207. # Read the printer in a short session and release the connection
  2208. # BEFORE the ~15s camera snapshot below — holding it across the grab
  2209. # pinned a pooled connection per milestone, per printer (issue #2572).
  2210. async with async_session() as db:
  2211. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2212. printer = result.scalar_one_or_none()
  2213. printer_name = printer.name if printer else f"Printer {printer_id}"
  2214. filename = state.subtask_name or state.gcode_file or "Unknown"
  2215. # remaining_time is in minutes, convert to seconds for notification
  2216. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  2217. # Capture camera snapshot for notification image attachment (no DB held).
  2218. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  2219. # Notification send needs a session (provider/template lookups).
  2220. async with async_session() as db:
  2221. await notification_service.on_print_progress(
  2222. printer_id,
  2223. printer_name,
  2224. filename,
  2225. current_milestone,
  2226. db,
  2227. remaining_time_seconds,
  2228. image_data=image_data,
  2229. )
  2230. except Exception as e:
  2231. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  2232. elif progress < 5:
  2233. # Reset milestone tracking when print restarts or new print begins
  2234. _last_progress_milestone[printer_id] = 0
  2235. _first_layer_notified[printer_id] = False
  2236. # HMS error codes that should not trigger notifications even though they
  2237. # have known descriptions (e.g. user-initiated actions, not real errors).
  2238. _HMS_NOTIFICATION_SUPPRESS = {
  2239. "0500_400E", # Printing was cancelled (user action, not an error)
  2240. }
  2241. # Check for new HMS errors and send notifications
  2242. current_hms_errors = getattr(state, "hms_errors", []) or []
  2243. if current_hms_errors:
  2244. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  2245. if new_errors:
  2246. try:
  2247. from backend.app.models.printer import Printer
  2248. # Read the printer in a short session and release the connection
  2249. # BEFORE the ~15s camera snapshot below (issue #2572).
  2250. async with async_session() as db:
  2251. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2252. printer = result.scalar_one_or_none()
  2253. printer_name = printer.name if printer else f"Printer {printer_id}"
  2254. # Format error details for notification
  2255. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  2256. module_names = {
  2257. 0x03: "Print/Task",
  2258. 0x05: "Nozzle/Extruder",
  2259. 0x07: "AMS/Filament",
  2260. 0x0C: "Motion Controller",
  2261. 0x12: "Chamber",
  2262. }
  2263. # Capture camera snapshot once for all error notifications (no DB held).
  2264. error_image_data = await _capture_snapshot_for_notification(
  2265. printer_id, printer, logging.getLogger(__name__)
  2266. )
  2267. # Notification sends need a session (provider/template lookups).
  2268. async with async_session() as db:
  2269. sent_count = 0
  2270. for error in new_errors:
  2271. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  2272. # Build short code like "0700_8010"
  2273. # Mask to 16 bits to handle printers that send larger values
  2274. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  2275. error_code_masked = error_code_int & 0xFFFF
  2276. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  2277. # Only notify for errors Bambu publishes text for — printers
  2278. # send undocumented codes that aren't real errors, and Bambu
  2279. # lists some with empty text. Resolved at parse time (#2926);
  2280. # short_code is still needed for the suppression set below.
  2281. description = error.description
  2282. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  2283. continue
  2284. error_type = f"{module_name} Error"
  2285. error_detail = description
  2286. await notification_service.on_printer_error(
  2287. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  2288. )
  2289. sent_count += 1
  2290. if sent_count:
  2291. logging.getLogger(__name__).info(
  2292. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  2293. )
  2294. # Also publish to MQTT relay (no DB): every new fault that
  2295. # counts, with or without text, the same set the UI counts.
  2296. printer_info = printer_manager.get_printer(printer_id)
  2297. if printer_info:
  2298. errors_data = [
  2299. {
  2300. "code": e.code,
  2301. "attr": e.attr,
  2302. "module": e.module,
  2303. "severity": e.severity,
  2304. }
  2305. for e in new_errors
  2306. ]
  2307. await mqtt_relay.on_printer_error(
  2308. printer_id, printer_info.name, printer_info.serial_number, errors_data
  2309. )
  2310. except Exception as e:
  2311. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  2312. else:
  2313. # No HMS errors: nothing to send, but faults gone long enough (or gone
  2314. # across a print state change) are forgotten. Some codes, e.g. chamber
  2315. # temperature regulation during PETG prints, toggle every few seconds.
  2316. _take_new_hms_faults(printer_id, [], state.state)
  2317. await ws_manager.send_printer_status(
  2318. printer_id,
  2319. printer_state_to_dict(
  2320. state,
  2321. printer_id,
  2322. printer_manager.get_model(printer_id),
  2323. printer_manager.get_drying_targets(printer_id),
  2324. ),
  2325. )
  2326. def _is_bambu_uuid(tray_uuid: str) -> bool:
  2327. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  2328. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  2329. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  2330. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  2331. K-profiles are per-nozzle and the printer's calibration table is numbered
  2332. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  2333. switch's other inlet therefore silently invalidates every configured slot in
  2334. it: the index stays put and now resolves against the other nozzle's table.
  2335. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  2336. and 0.020 on the right kept the left profile after the move, and a manual
  2337. RFID re-read only re-asserted the same wrong one.
  2338. Configuring a slot is a deliberate preparation step, so this re-selects
  2339. rather than re-configures: only the calibration binding moves, and only for
  2340. slots whose spool already has a stored profile for the new nozzle. A slot
  2341. Bambuddy knows nothing about is left exactly as the operator left it.
  2342. """
  2343. logger = logging.getLogger(__name__)
  2344. target_extruder = extruder_for_inlet(inlet)
  2345. if target_extruder is None:
  2346. return
  2347. client = printer_manager.get_client(printer_id)
  2348. state = printer_manager.get_status(printer_id)
  2349. if not client or not state or not state.raw_data:
  2350. return
  2351. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  2352. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  2353. # the nozzle width, which changes both the K profile to select and the
  2354. # preset the slot should carry.
  2355. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  2356. ams_raw = state.raw_data.get("ams")
  2357. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2358. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  2359. if not unit:
  2360. return
  2361. try:
  2362. async with async_session() as db:
  2363. for tray in unit.get("tray", []):
  2364. tray_id = int(tray.get("id", -1))
  2365. if tray_id < 0 or not tray.get("tray_type"):
  2366. continue
  2367. current_idx = tray.get("cali_idx")
  2368. profile = await find_slot_kprofile_for_extruder(
  2369. db,
  2370. printer_id,
  2371. ams_id,
  2372. tray_id,
  2373. target_extruder,
  2374. nozzle_diameter,
  2375. printer_manager.get_model(printer_id),
  2376. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2377. )
  2378. if profile is None or profile.cali_idx is None:
  2379. continue
  2380. if current_idx == profile.cali_idx:
  2381. continue # Already on the right one.
  2382. logger.info(
  2383. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2384. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2385. printer_id,
  2386. ams_id,
  2387. tray_id,
  2388. inlet,
  2389. target_extruder,
  2390. profile.name,
  2391. current_idx,
  2392. profile.cali_idx,
  2393. profile.k_value,
  2394. )
  2395. client.extrusion_cali_sel(
  2396. ams_id=ams_id,
  2397. tray_id=tray_id,
  2398. cali_idx=profile.cali_idx,
  2399. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2400. nozzle_diameter=nozzle_diameter,
  2401. )
  2402. except Exception as e:
  2403. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2404. def _slot_feeds_print(printer_id: int, ams_id: int, tray_id: int) -> bool:
  2405. """Is this slot the one feeding the printer right now?
  2406. ``tray_now`` names one slot for the whole printer, so on a dual-nozzle
  2407. machine each extruder's own fed slot is asked as well. Only meaningful
  2408. while a print runs; the caller checks that.
  2409. """
  2410. status = printer_manager.get_status(printer_id)
  2411. if status is None:
  2412. return False
  2413. if ams_id == 255:
  2414. global_id = 254 + tray_id
  2415. elif ams_id >= 128:
  2416. global_id = ams_id
  2417. else:
  2418. global_id = ams_id * 4 + tray_id
  2419. if getattr(status, "tray_now", None) == global_id:
  2420. return True
  2421. slots = getattr(status, "extruder_slots", None) or {}
  2422. return any(slot.has_filament and slot.holds(ams_id, tray_id) for slot in slots.values())
  2423. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2424. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2425. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2426. from the delayed re-check -- which is why it takes the AMS data and print
  2427. state as arguments instead of reading them from the push (#3186).
  2428. """
  2429. logger = logging.getLogger(__name__)
  2430. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2431. # Auto-unlink spool assignments with stale fingerprints. Under the
  2432. # per-printer assignment lock since #3186: the held-removal re-check runs
  2433. # this outside any MQTT push, so it can now overlap one.
  2434. try:
  2435. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2436. from sqlalchemy.orm import selectinload
  2437. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2438. from backend.app.models.spool import Spool as _Spool
  2439. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2440. from backend.app.services.ams_slot_presence import spool_present
  2441. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2442. # Built-in assignments only. Since #2812 they survive a switch to
  2443. # Spoolman mode rather than being deleted by it, and this pass ends
  2444. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2445. # time as the AMS contents changed under the other mode, undoing the
  2446. # preservation more slowly but just as completely.
  2447. assignments = []
  2448. if not await spoolman_owns_assignments(db):
  2449. result = await db.execute(
  2450. select(SA)
  2451. .where(SA.printer_id == printer_id)
  2452. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2453. )
  2454. assignments = result.scalars().all()
  2455. # ``printing_now`` (top of this function) keeps a runout from
  2456. # unlinking the spool that fed the print — the next idle-time pass
  2457. # unlinks it if the user really did take it out.
  2458. stale = []
  2459. # Removals this pass is holding rather than unlinking (#3186).
  2460. held: set[tuple] = set()
  2461. for assignment in assignments:
  2462. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2463. if assignment.ams_id == 255:
  2464. ps = printer_manager.get_status(printer_id)
  2465. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2466. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  2467. current_tray = None
  2468. for vt in vt_tray_raw:
  2469. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2470. current_tray = vt
  2471. break
  2472. if not current_tray:
  2473. # vt_tray data may not have arrived yet — keep assignment
  2474. continue
  2475. else:
  2476. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2477. if not current_tray:
  2478. if printing_now:
  2479. logger.info(
  2480. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2481. assignment.spool_id,
  2482. assignment.ams_id,
  2483. assignment.tray_id,
  2484. )
  2485. continue
  2486. # A whole AMS unit can drop out of one push and come back in
  2487. # the next; only a slot that stays gone is a removal (#3186).
  2488. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2489. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2490. held.add(hold_key)
  2491. logger.info(
  2492. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2493. "unlinking if it is still gone in %ds",
  2494. assignment.spool_id,
  2495. assignment.ams_id,
  2496. assignment.tray_id,
  2497. int(slot_unlink_grace.GRACE_SECONDS),
  2498. )
  2499. continue
  2500. logger.info(
  2501. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2502. assignment.spool_id,
  2503. assignment.ams_id,
  2504. assignment.tray_id,
  2505. )
  2506. stale.append(assignment) # Slot empty
  2507. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2508. # A Bambu Lab spool is in this slot — check if it's the same spool
  2509. # that's currently assigned. If yes, keep the assignment (avoids
  2510. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2511. # the printer's filament preset on every startup).
  2512. tray_uuid = current_tray.get("tray_uuid", "")
  2513. tag_uid = current_tray.get("tag_uid", "")
  2514. spool = assignment.spool
  2515. spool_matches = False
  2516. if spool:
  2517. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2518. spool.tag_uid
  2519. and tag_uid
  2520. and tag_uid != "0000000000000000"
  2521. and spool.tag_uid.upper() == tag_uid.upper()
  2522. ):
  2523. spool_matches = True
  2524. if spool_matches:
  2525. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2526. cur_color = current_tray.get("tray_color", "")
  2527. cur_type = current_tray.get("tray_type", "")
  2528. fp_color = assignment.fingerprint_color or ""
  2529. fp_type = assignment.fingerprint_type or ""
  2530. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2531. assignment.fingerprint_color = cur_color
  2532. assignment.fingerprint_type = cur_type
  2533. logger.debug(
  2534. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2535. assignment.spool_id,
  2536. assignment.ams_id,
  2537. assignment.tray_id,
  2538. )
  2539. continue
  2540. # Different BL spool or unrecognized — unlink so auto-assign can match
  2541. logger.info(
  2542. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2543. assignment.spool_id,
  2544. assignment.ams_id,
  2545. assignment.tray_id,
  2546. tray_uuid,
  2547. )
  2548. stale.append(assignment)
  2549. else:
  2550. cur_color = current_tray.get("tray_color", "")
  2551. cur_type = current_tray.get("tray_type", "")
  2552. cur_state = current_tray.get("state")
  2553. fp_color = assignment.fingerprint_color or ""
  2554. fp_type = assignment.fingerprint_type or ""
  2555. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2556. # the slot was empty when the user pre-assigned via SpoolBuddy
  2557. # (the firmware drops ams_filament_setting on empty slots, so
  2558. # MQTT was deferred). The moment any filament gets inserted
  2559. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2560. # reconfigured spool — fire the deferred configuration.
  2561. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2562. # extruder" code) OR, on firmwares that don't use the state
  2563. # enum meaningfully, a non-empty tray_type when state is
  2564. # NOT one of the firmware's explicit empty signals (9, 10).
  2565. # state-only was wrong for firmwares that never set 11 — A1
  2566. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2567. # always report state=3 — so the replay never fired for them
  2568. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2569. # explicit "empty" signals authoritative over any stale
  2570. # tray_type that might survive the relay's auto-clearing.
  2571. #
  2572. # tray_exist_bits comes first because that guard cannot tell
  2573. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2574. # writes state=9 when the bit is 0 and leaves it there when the
  2575. # bit returns. A non-RFID spool inserted into a pre-assigned
  2576. # slot brings no tray_type with it, so the stale 9 made this
  2577. # expression false forever and the deferred config never fired
  2578. # — the deadlock #1322 removed from the assign path, still in
  2579. # place here (#3084, #3100).
  2580. loaded = spool_present(current_tray) is True or (
  2581. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2582. )
  2583. # Not into the slot feeding a running print: the printer refuses
  2584. # the setting for it (``ams_filament_setting refused``), and a
  2585. # spool swapped in after a runout sat through one refused send
  2586. # per AMS change. Held, it fires on the first change once the
  2587. # print is over (#3434).
  2588. if (
  2589. not fp_type.strip()
  2590. and loaded
  2591. and assignment.spool
  2592. and printing_now
  2593. and _slot_feeds_print(printer_id, assignment.ams_id, assignment.tray_id)
  2594. ):
  2595. logger.debug(
  2596. "Pre-config held for spool %d AMS%d-T%d: the slot is feeding the print",
  2597. assignment.spool_id,
  2598. assignment.ams_id,
  2599. assignment.tray_id,
  2600. )
  2601. continue
  2602. if not fp_type.strip() and loaded and assignment.spool:
  2603. # The fingerprint ends this replay. Not recorded when nothing
  2604. # could be sent (no MQTT client while the printer reconnects),
  2605. # so the next AMS change tries again. An attempt that raised is
  2606. # recorded as before: it may have sent part of the commands and
  2607. # would raise again on every change, remain% steps included.
  2608. configured: bool | None = False
  2609. try:
  2610. from backend.app.api.routes.inventory import (
  2611. apply_spool_to_slot_via_mqtt,
  2612. )
  2613. configured = await apply_spool_to_slot_via_mqtt(
  2614. db=db,
  2615. current_user=None,
  2616. spool=assignment.spool,
  2617. printer_id=printer_id,
  2618. ams_id=assignment.ams_id,
  2619. tray_id=assignment.tray_id,
  2620. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2621. current_tray_type=cur_type,
  2622. current_tray_sub_brands=current_tray.get("tray_sub_brands", ""),
  2623. )
  2624. except Exception:
  2625. logger.exception(
  2626. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2627. assignment.spool_id,
  2628. printer_id,
  2629. assignment.ams_id,
  2630. assignment.tray_id,
  2631. )
  2632. configured = None
  2633. if configured is False:
  2634. logger.warning(
  2635. "Pre-config not sent for spool %d on printer %d AMS%d-T%d (no MQTT client); "
  2636. "retrying on the next AMS change",
  2637. assignment.spool_id,
  2638. printer_id,
  2639. assignment.ams_id,
  2640. assignment.tray_id,
  2641. )
  2642. else:
  2643. if configured:
  2644. logger.info(
  2645. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2646. assignment.spool_id,
  2647. printer_id,
  2648. assignment.ams_id,
  2649. assignment.tray_id,
  2650. )
  2651. assignment.fingerprint_color = cur_color
  2652. assignment.fingerprint_type = cur_type
  2653. continue
  2654. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2655. # Blank tray data mid-print is a runout, not a swap: the
  2656. # firmware clears colour and type when it unloads a spool
  2657. # it just emptied. Unlinking here would erase the record
  2658. # of which spool fed the print so far.
  2659. if printing_now and not cur_color.strip() and not cur_type.strip():
  2660. logger.info(
  2661. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2662. "(runout?)",
  2663. assignment.spool_id,
  2664. assignment.ams_id,
  2665. assignment.tray_id,
  2666. )
  2667. continue
  2668. # Same reasoning off the print, on firmware's own say-so:
  2669. # a blank tray report from a slot whose tray_exist_bits
  2670. # bit is set describes a spool the AMS cannot identify —
  2671. # a non-RFID one, or one whose slot was reset — not a
  2672. # spool that was taken out. Deleting the assignment there
  2673. # threw away the identity the user had supplied, which is
  2674. # the only place it existed (#3100). A slot the bit calls
  2675. # empty, or one that carries no bit at all, still unlinks.
  2676. #
  2677. # Unless the slot was reported empty first: a removal
  2678. # already held means a spool came out and another went
  2679. # in, so the blank report keeps the hold running below
  2680. # rather than cancelling it (#3186).
  2681. if (
  2682. spool_present(current_tray) is True
  2683. and not cur_color.strip()
  2684. and not cur_type.strip()
  2685. and not slot_unlink_grace.is_held(
  2686. printer_id,
  2687. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2688. )
  2689. ):
  2690. logger.info(
  2691. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2692. "tray reports no filament data yet",
  2693. assignment.spool_id,
  2694. assignment.ams_id,
  2695. assignment.tray_id,
  2696. )
  2697. continue
  2698. # A blank report the presence bit does not vouch for is
  2699. # still only one push. An idle X1C cleared a whole AMS
  2700. # unit's bits, colour and type for a moment and lost
  2701. # four saved assignments that way (#3186); unlink only
  2702. # if the slot is still blank after the grace period.
  2703. if not cur_color.strip() and not cur_type.strip():
  2704. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2705. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2706. held.add(hold_key)
  2707. logger.info(
  2708. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2709. "unlinking if it is still blank in %ds",
  2710. assignment.spool_id,
  2711. assignment.ams_id,
  2712. assignment.tray_id,
  2713. int(slot_unlink_grace.GRACE_SECONDS),
  2714. )
  2715. continue
  2716. # Fingerprint mismatch — but check if tray now matches the
  2717. # assigned spool (e.g. auto-configure changed the tray).
  2718. # Both sides are reduced to the type the slot can carry
  2719. # before comparing: the assign path writes that rather
  2720. # than the spool's raw material (#2902), so a spool whose
  2721. # material is a product line — "PLA+", "HTPLA" — reports
  2722. # back as "PLA" and would otherwise fail this check and
  2723. # be auto-unlinked from the slot it was just assigned to.
  2724. # Reducing the printer's side too keeps slots configured
  2725. # by an older Bambuddy, still reporting "PLA+", matching.
  2726. spool = assignment.spool
  2727. if spool:
  2728. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2729. # Two ways the assign path can have arrived at the
  2730. # slot's type, so both count as "we wrote this".
  2731. # The material column is one; the spool's preset is
  2732. # the other, and it outranks the material when the
  2733. # spool has one -- a spool whose material says PLA
  2734. # and whose preset is "Bambu PLA Aero" puts
  2735. # PLA-AERO in the slot (#2902). Read from the stored
  2736. # preset name rather than resolving the preset,
  2737. # because this runs on every AMS push and a cloud
  2738. # lookup here would be both slow and unavailable on
  2739. # the unauthenticated replay path.
  2740. spool_types = {printer_filament_type(spool.material).upper()}
  2741. if spool.slicer_filament_name:
  2742. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2743. # An imported local preset stores its type outright,
  2744. # which is what the assign path used -- and the name
  2745. # above may be unset. One keyed read, and only on a
  2746. # mismatch, which is rare.
  2747. #
  2748. # slicer_filament is free text up to fifty characters,
  2749. # so the digits have to be checked against the range
  2750. # of the integer primary key they are about to be
  2751. # compared with. Postgres raises on an out-of-range
  2752. # integer rather than simply not matching, and that
  2753. # would poison this session and abandon the rest of
  2754. # the cleanup pass.
  2755. lp_ref = (spool.slicer_filament or "").strip()
  2756. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2757. from backend.app.models.local_preset import LocalPreset as _LP
  2758. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2759. if lp_type:
  2760. spool_types.add(printer_filament_type(lp_type).upper())
  2761. if (
  2762. _colors_similar(cur_color, spool_color)
  2763. and printer_filament_type(cur_type).upper() in spool_types
  2764. ):
  2765. logger.info(
  2766. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2767. assignment.spool_id,
  2768. assignment.ams_id,
  2769. assignment.tray_id,
  2770. )
  2771. assignment.fingerprint_color = cur_color
  2772. assignment.fingerprint_type = cur_type
  2773. continue
  2774. logger.info(
  2775. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2776. assignment.spool_id,
  2777. assignment.ams_id,
  2778. assignment.tray_id,
  2779. cur_color,
  2780. cur_type,
  2781. fp_color,
  2782. fp_type,
  2783. spool.rgba if spool else "?",
  2784. spool.material if spool else "?",
  2785. )
  2786. stale.append(assignment) # Spool changed
  2787. slot_unlink_grace.settle(printer_id, "inventory", held)
  2788. # Snapshot slots before delete — ORM attribute access after the
  2789. # commit would refresh against a deleted row.
  2790. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2791. for a in stale:
  2792. await db.delete(a)
  2793. if stale:
  2794. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2795. # Commit any changes (stale deletions and/or fingerprint updates)
  2796. await db.commit()
  2797. # Tell open browsers the assignment is gone (#2575). Only the manual
  2798. # REST assign/unassign endpoints broadcast this event; without it the
  2799. # frontend's spool-assignments cache keeps rendering the unlinked
  2800. # spool on the slot until an unrelated refetch — which reads exactly
  2801. # like "the fix didn't work" (reporter verified: a browser refresh
  2802. # after the swap showed the correct state all along).
  2803. for ams_id, tray_id in unlinked_slots:
  2804. await ws_manager.broadcast(
  2805. {
  2806. "type": "spool_assignment_changed",
  2807. "printer_id": printer_id,
  2808. "ams_id": ams_id,
  2809. "tray_id": tray_id,
  2810. }
  2811. )
  2812. except Exception as e:
  2813. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2814. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2815. """Delete Spoolman slot rows whose held removal has run its grace period.
  2816. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2817. talks to Spoolman for every tray; this only needs the local rows, so it
  2818. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2819. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2820. not in a slot the presence bit calls occupied -- and nothing else.
  2821. """
  2822. logger = logging.getLogger(__name__)
  2823. try:
  2824. async with async_session() as db:
  2825. from backend.app.api.routes.settings import get_setting
  2826. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2827. from backend.app.services.ams_slot_presence import spool_present
  2828. enabled = await get_setting(db, "spoolman_enabled")
  2829. if not enabled or enabled.lower() != "true":
  2830. return
  2831. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2832. if sync_mode and sync_mode != "auto":
  2833. return
  2834. trays: dict[tuple[int, int], dict] = {}
  2835. for ams_unit in ams_data or []:
  2836. if not isinstance(ams_unit, dict):
  2837. continue
  2838. for tray in ams_unit.get("tray", []):
  2839. if isinstance(tray, dict):
  2840. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2841. rows = (
  2842. (
  2843. await db.execute(
  2844. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2845. )
  2846. )
  2847. .scalars()
  2848. .all()
  2849. )
  2850. held: set[tuple] = set()
  2851. expired: list[tuple[int, int]] = []
  2852. for row in rows:
  2853. tray = trays.get((row.ams_id, row.tray_id))
  2854. if tray is None or printing_now:
  2855. continue
  2856. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2857. continue
  2858. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2859. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2860. continue
  2861. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2862. expired.append((row.ams_id, row.tray_id))
  2863. else:
  2864. held.add(hold_key)
  2865. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2866. if not expired:
  2867. return
  2868. # A statement rather than ORM deletes, like the sync pass: the two
  2869. # can overlap, and a row the other already removed must not fail
  2870. # this commit.
  2871. for ams_id, tray_id in expired:
  2872. await db.execute(
  2873. delete(SpoolmanSlotAssignment).where(
  2874. SpoolmanSlotAssignment.printer_id == printer_id,
  2875. SpoolmanSlotAssignment.ams_id == ams_id,
  2876. SpoolmanSlotAssignment.tray_id == tray_id,
  2877. )
  2878. )
  2879. await db.commit()
  2880. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2881. for ams_id, tray_id in expired:
  2882. await ws_manager.broadcast(
  2883. {
  2884. "type": "spool_assignment_changed",
  2885. "printer_id": printer_id,
  2886. "ams_id": ams_id,
  2887. "tray_id": tray_id,
  2888. }
  2889. )
  2890. except Exception as e:
  2891. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2892. async def _recheck_held_unlinks(printer_id: int) -> None:
  2893. """Re-run just the slot cleanup against the printer's current AMS state.
  2894. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2895. passes otherwise run only when the AMS hash changes, and a slot that went
  2896. empty and stayed empty may never change it again.
  2897. """
  2898. status = printer_manager.get_status(printer_id)
  2899. # A disconnected printer's state is its last report, not a new one: acting
  2900. # on it would "confirm" a removal nobody has seen for the whole grace
  2901. # period. Leave the holds; the first push after reconnecting decides.
  2902. if status is None or not status.connected:
  2903. return
  2904. ams_raw = status.raw_data.get("ams")
  2905. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2906. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2907. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2908. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2909. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2910. async def on_ams_change(printer_id: int, ams_data: list):
  2911. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2912. logger = logging.getLogger(__name__)
  2913. # Snapshot BEFORE any await: if a print is active, or a finished one is
  2914. # still being charged, skip weight sync later. on_print_complete may pop
  2915. # _active_sessions during our awaits (#880).
  2916. from backend.app.services.usage_tracker import printer_is_charging
  2917. _print_active = printer_is_charging(printer_id)
  2918. # A slot that reports empty while a print is running is a filament runout,
  2919. # not a spool swap: the spool is still physically in the AMS, just
  2920. # consumed. Dropping either inventory backend's slot link there loses the
  2921. # only record of which spool fed the print, so the completion path can't
  2922. # charge the runout segment to anything. Both cleanup passes below consult
  2923. # this; computed once, up front, so neither depends on the other having run.
  2924. _unlink_state = printer_manager.get_status(printer_id)
  2925. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2926. # The session alone is not enough: a restart that finds a stale persisted
  2927. # session registers none for the print that is running.
  2928. _print_active = _print_active or printing_now
  2929. # MQTT relay - publish AMS change
  2930. try:
  2931. printer_info = printer_manager.get_printer(printer_id)
  2932. if printer_info:
  2933. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2934. except Exception:
  2935. pass # Don't fail AMS callback if MQTT fails
  2936. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2937. # This ensures frontend gets immediate updates when AMS slots are configured
  2938. try:
  2939. state = printer_manager.get_status(printer_id)
  2940. if state:
  2941. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2942. await ws_manager.send_printer_status(
  2943. printer_id,
  2944. printer_state_to_dict(
  2945. state,
  2946. printer_id,
  2947. printer_manager.get_model(printer_id),
  2948. printer_manager.get_drying_targets(printer_id),
  2949. ),
  2950. )
  2951. except Exception as e:
  2952. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2953. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2954. # Spools whose tag this pass assigned to a slot; their other slots are
  2955. # released below, once this printer's lock is let go (#3427).
  2956. rfid_assigned: list[tuple[int, tuple[int, int, int]]] = []
  2957. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2958. # Serialised per-printer via services/ams_assignment_lock: MQTT bursts can deliver
  2959. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2960. # "no existing assignment" for the same (printer, ams, tray) and race to
  2961. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2962. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2963. # bug stayed latent there. See services/ams_assignment_lock for details.
  2964. try:
  2965. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2966. from sqlalchemy.orm import selectinload
  2967. from backend.app.api.routes.settings import get_setting
  2968. from backend.app.models.spool import Spool
  2969. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2970. from backend.app.services.spool_tag_matcher import (
  2971. auto_assign_spool,
  2972. create_spool_from_tray,
  2973. find_matching_untagged_spool,
  2974. get_spool_by_tag,
  2975. is_bambu_tag,
  2976. is_valid_tag,
  2977. link_tag_to_inventory_spool,
  2978. tag_belongs_to_archived_spool,
  2979. )
  2980. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2981. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2982. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2983. if not _spoolman_on or _spoolman_on.lower() != "true":
  2984. for ams_unit in ams_data:
  2985. if not isinstance(ams_unit, dict):
  2986. continue
  2987. ams_id = int(ams_unit.get("id", 0))
  2988. for tray in ams_unit.get("tray", []):
  2989. if not isinstance(tray, dict):
  2990. continue
  2991. tray_id = int(tray.get("id", 0))
  2992. tag_uid = tray.get("tag_uid", "")
  2993. tray_uuid = tray.get("tray_uuid", "")
  2994. tray_info_idx = tray.get("tray_info_idx", "")
  2995. if not tray.get("tray_type"):
  2996. # Slot reported empty — drop any cached unknown-tag
  2997. # broadcast so reinserting the same spool re-prompts.
  2998. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2999. continue # Empty slot
  3000. # Check if assignment already exists for this slot
  3001. existing = await db.execute(
  3002. select(SA)
  3003. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  3004. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  3005. )
  3006. existing_assignment = existing.scalar_one_or_none()
  3007. if existing_assignment:
  3008. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  3009. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  3010. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  3011. # Skip during active prints: the usage tracker handles deduction
  3012. # precisely via 3MF data on print completion. Without this guard the
  3013. # AMS remain% SET and the usage tracker ADD both fire from the same
  3014. # MQTT message, doubling the deduction (#880).
  3015. if _print_active:
  3016. continue
  3017. remain_raw = tray.get("remain")
  3018. if (
  3019. remain_raw is not None
  3020. and existing_assignment.spool
  3021. and not existing_assignment.spool.weight_locked
  3022. ):
  3023. try:
  3024. remain_val = int(remain_raw)
  3025. except (TypeError, ValueError):
  3026. remain_val = -1
  3027. if 1 <= remain_val <= 100:
  3028. lw = existing_assignment.spool.label_weight or 1000
  3029. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  3030. current_used = existing_assignment.spool.weight_used or 0
  3031. if new_used > current_used + 1:
  3032. # Rechecked in the statement: the spool was loaded
  3033. # before this, and a weight set by hand (or weighed)
  3034. # and locked since then must stay (WL-6).
  3035. result = cast(
  3036. CursorResult,
  3037. await db.execute(
  3038. update(Spool)
  3039. .where(
  3040. Spool.id == existing_assignment.spool_id,
  3041. Spool.weight_locked.is_not(True),
  3042. func.coalesce(Spool.weight_used, 0) < new_used - 1,
  3043. )
  3044. .values(weight_used=new_used)
  3045. ),
  3046. )
  3047. await db.commit()
  3048. if result.rowcount:
  3049. logger.info(
  3050. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  3051. existing_assignment.spool_id,
  3052. current_used,
  3053. new_used,
  3054. remain_val,
  3055. )
  3056. await ws_manager.broadcast({"type": "inventory_changed"})
  3057. # A K-profile the slot lost (the default K after a reset or
  3058. # power cycle) is put back by kprofile_drift on the next idle
  3059. # push; a different real profile was picked on purpose and
  3060. # stays (#3219, item 44).
  3061. continue
  3062. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  3063. # BL spool with RFID tag: auto-match → inventory match → auto-create
  3064. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  3065. # Only a spool already known by this tag is proven to be
  3066. # here; a material/colour match or a new spool is not
  3067. # grounds to take it out of other slots (#3427).
  3068. known_by_tag = spool is not None
  3069. if not spool and await tag_belongs_to_archived_spool(db, tag_uid, tray_uuid):
  3070. # An archived spool still in the AMS: the slot
  3071. # stays free rather than adopting its tag.
  3072. continue
  3073. if not spool:
  3074. # Try matching an untagged inventory spool (same material/color)
  3075. spool = await find_matching_untagged_spool(db, tray)
  3076. if spool:
  3077. await link_tag_to_inventory_spool(db, spool, tray)
  3078. elif _auto_add_unknown:
  3079. spool = await create_spool_from_tray(db, tray)
  3080. else:
  3081. # Auto-add disabled: surface the slot so the
  3082. # user can add it manually via the UI.
  3083. await _broadcast_unknown_tag(
  3084. printer_id=printer_id,
  3085. ams_id=ams_id,
  3086. tray_id=tray_id,
  3087. tag_uid=tag_uid,
  3088. tray_uuid=tray_uuid,
  3089. tray_type=tray.get("tray_type"),
  3090. tray_color=tray.get("tray_color"),
  3091. tray_sub_brands=tray.get("tray_sub_brands"),
  3092. tray_count=len(ams_unit.get("tray", [])),
  3093. )
  3094. continue
  3095. # Slot matched (existing tag, untagged inventory
  3096. # match, or freshly auto-created spool) — drop any
  3097. # stale dedup so a future tag swap re-prompts.
  3098. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  3099. await auto_assign_spool(
  3100. printer_id,
  3101. ams_id,
  3102. tray_id,
  3103. spool,
  3104. printer_manager,
  3105. db,
  3106. tray_info_idx=tray_info_idx,
  3107. )
  3108. await db.commit()
  3109. if known_by_tag:
  3110. rfid_assigned.append((spool.id, (printer_id, ams_id, tray_id)))
  3111. await ws_manager.broadcast(
  3112. {
  3113. "type": "spool_auto_assigned",
  3114. "printer_id": printer_id,
  3115. "ams_id": ams_id,
  3116. "tray_id": tray_id,
  3117. "spool_id": spool.id,
  3118. }
  3119. )
  3120. logger.info(
  3121. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  3122. spool.id,
  3123. printer_id,
  3124. ams_id,
  3125. tray_id,
  3126. )
  3127. elif is_valid_tag(tag_uid, tray_uuid) and not await tag_belongs_to_archived_spool(
  3128. db, tag_uid, tray_uuid
  3129. ):
  3130. # Non-BL spool with some tag — let user choose (not
  3131. # an archived one's, whose slot stays free)
  3132. await _broadcast_unknown_tag(
  3133. printer_id=printer_id,
  3134. ams_id=ams_id,
  3135. tray_id=tray_id,
  3136. tag_uid=tag_uid,
  3137. tray_uuid=tray_uuid,
  3138. tray_type=tray.get("tray_type"),
  3139. tray_color=tray.get("tray_color"),
  3140. tray_sub_brands=tray.get("tray_sub_brands"),
  3141. tray_count=len(ams_unit.get("tray", [])),
  3142. )
  3143. # No-tag slots (generic non-RFID filament) are left alone:
  3144. # nothing to identify, prompting "+ Add" would just create
  3145. # ghost spools with empty tags on every confirm.
  3146. except Exception as e:
  3147. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  3148. if rfid_assigned:
  3149. from backend.app.services.spool_relocation import INTERNAL, release_other_slots
  3150. for spool_id, slot in rfid_assigned:
  3151. try:
  3152. await release_other_slots(INTERNAL, spool_id, slot)
  3153. except Exception as e:
  3154. logger.warning("Releasing spool %s from its other slots failed: %s", spool_id, e, exc_info=True)
  3155. try:
  3156. async with async_session() as db:
  3157. from backend.app.api.routes.settings import get_setting
  3158. from backend.app.models.printer import Printer
  3159. # Check if Spoolman is enabled
  3160. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  3161. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  3162. return
  3163. # Check sync mode
  3164. sync_mode = await get_setting(db, "spoolman_sync_mode")
  3165. if sync_mode and sync_mode != "auto":
  3166. return # Only sync on auto mode
  3167. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  3168. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  3169. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  3170. # always owned by per-print tracking, never by AMS auto-sync. The
  3171. # setting is still read by the settings UI for backwards compat but
  3172. # has no effect on the sync path here.
  3173. # Get Spoolman URL
  3174. spoolman_url = await get_setting(db, "spoolman_url")
  3175. if not spoolman_url:
  3176. return
  3177. # Get or create Spoolman client
  3178. client = await get_spoolman_client()
  3179. if not client:
  3180. try:
  3181. client = await init_spoolman_client(spoolman_url)
  3182. except ValueError as exc:
  3183. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  3184. return
  3185. # Check if Spoolman is reachable
  3186. if not await client.health_check():
  3187. logger.warning("Spoolman not reachable at %s", spoolman_url)
  3188. return
  3189. # Get printer name for location
  3190. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3191. printer = result.scalar_one_or_none()
  3192. printer_name = printer.name if printer else f"Printer {printer_id}"
  3193. # OPTIMIZATION: Fetch all spools once before processing trays
  3194. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  3195. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  3196. try:
  3197. cached_spools = await client.get_spools()
  3198. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  3199. except Exception as e:
  3200. logger.error(
  3201. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  3202. printer_id,
  3203. e,
  3204. )
  3205. return
  3206. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  3207. from sqlalchemy.orm import selectinload
  3208. from backend.app.models.spool_assignment import SpoolAssignment
  3209. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  3210. from backend.app.services.ams_slot_presence import spool_present
  3211. from backend.app.services.inventory_mode import spoolman_owns_assignments
  3212. # Built-in remaining weight, used by sync_ams_tray only when the
  3213. # firmware reports an unusable remain%/tray_weight for a slot.
  3214. #
  3215. # Left empty since #2812. This block runs in Spoolman mode only,
  3216. # and until then the built-in table was emptied on the switch, so
  3217. # there was never anything here to read and the fallback was inert.
  3218. # Preserving those rows makes it live again, and it is keyed by slot
  3219. # rather than by spool: after a mode switch the tray may well hold
  3220. # different filament, and ``create_spool`` writes ``remaining_weight``
  3221. # unconditionally, so a stale figure would be seeded into a brand new
  3222. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  3223. # intent survives for whoever revisits the cross-mode fallback.
  3224. inventory_weights: dict[tuple[int, int], float] = {}
  3225. if not await spoolman_owns_assignments(db):
  3226. try:
  3227. assign_result = await db.execute(
  3228. select(SpoolAssignment)
  3229. .options(selectinload(SpoolAssignment.spool))
  3230. .where(SpoolAssignment.printer_id == printer_id)
  3231. )
  3232. for assignment in assign_result.scalars().all():
  3233. spool = assignment.spool
  3234. if spool and spool.label_weight > 0:
  3235. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  3236. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  3237. except Exception as e:
  3238. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  3239. # Load existing Spoolman slot assignments for the no-RFID fallback path
  3240. spoolman_slot_map: dict[tuple[int, int], int] = {}
  3241. slot_map_read = False
  3242. try:
  3243. slot_result = await db.execute(
  3244. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  3245. )
  3246. for slot in slot_result.scalars().all():
  3247. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  3248. slot_map_read = True
  3249. except Exception as e:
  3250. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  3251. # Sync each AMS tray and collect slot changes for DB persistence
  3252. synced = 0
  3253. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  3254. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  3255. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  3256. for ams_unit in ams_data:
  3257. if not isinstance(ams_unit, dict):
  3258. continue
  3259. ams_id = int(ams_unit.get("id", 0))
  3260. trays = ams_unit.get("tray", [])
  3261. for tray_data in trays:
  3262. if not isinstance(tray_data, dict):
  3263. continue
  3264. tray_id_raw = int(tray_data.get("id", 0))
  3265. tray = client.parse_ams_tray(ams_id, tray_data)
  3266. if not tray:
  3267. # Empty tray slot — record for local assignment cleanup
  3268. # and drop any cached unknown-tag broadcast so a
  3269. # reinserted spool re-prompts.
  3270. #
  3271. # Not during a running print: a slot that empties there
  3272. # is a filament runout, and the spool is still in the
  3273. # AMS. `spoolman_slot_assignments` is how a tag-less
  3274. # spool assigned through the Bambuddy UI is resolved at
  3275. # completion (#1459), so deleting the row mid-print
  3276. # loses the runout segment's usage — the same failure
  3277. # the internal inventory's auto-unlink had.
  3278. #
  3279. # Nor when firmware's presence bit says the slot is
  3280. # occupied. parse_ams_tray calls a tray with no type or
  3281. # no colour empty, and a spool the AMS cannot read has
  3282. # neither until something configures it — so a tag-less
  3283. # spool assigned through the UI had its row deleted by
  3284. # the first idle push after it was inserted. Same
  3285. # deletion as the internal inventory's in #3100, same
  3286. # answer, so the two modes stay in step.
  3287. #
  3288. # And only once the slot has stayed empty for the grace
  3289. # period -- the internal inventory's #3186 answer, for
  3290. # the same one-push blank.
  3291. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  3292. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  3293. if not printing_now and (
  3294. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  3295. ):
  3296. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  3297. empty_slots.append((ams_id, tray_id_raw))
  3298. else:
  3299. spoolman_held.add(hold_key)
  3300. logger.info(
  3301. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  3302. "unlinking if it is still empty in %ds",
  3303. ams_id,
  3304. tray_id_raw,
  3305. linked_spool,
  3306. int(slot_unlink_grace.GRACE_SECONDS),
  3307. )
  3308. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  3309. continue
  3310. spool_tag = (
  3311. tray.tray_uuid
  3312. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  3313. else tray.tag_uid
  3314. )
  3315. # Provide the hint only when no RFID is available
  3316. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  3317. try:
  3318. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  3319. result = await client.sync_ams_tray(
  3320. tray,
  3321. printer_name,
  3322. db,
  3323. # Per-print tracking is the only weight writer (#1119).
  3324. # AMS auto-sync still maintains spool metadata / slot
  3325. # assignments but no longer touches remaining_weight.
  3326. disable_weight_sync=True,
  3327. cached_spools=cached_spools,
  3328. inventory_remaining=inv_remaining,
  3329. spoolman_spool_id_hint=hint,
  3330. auto_add_unknown_rfid=auto_add_unknown_rfid,
  3331. )
  3332. if result is None and spool_tag and not auto_add_unknown_rfid:
  3333. # Spoolman skipped auto-create per user setting — surface
  3334. # the slot so the UI can offer "+ Add to inventory".
  3335. await _broadcast_unknown_tag(
  3336. printer_id=printer_id,
  3337. ams_id=ams_id,
  3338. tray_id=tray.tray_id,
  3339. tag_uid=tray.tag_uid or "",
  3340. tray_uuid=tray.tray_uuid or "",
  3341. tray_type=tray.tray_type,
  3342. tray_color=tray.tray_color,
  3343. tray_sub_brands=tray.tray_sub_brands,
  3344. tray_count=len(trays),
  3345. )
  3346. elif result:
  3347. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  3348. if result:
  3349. synced += 1
  3350. if result.get("id"):
  3351. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  3352. # If a new spool was created, add it to the cache
  3353. # so subsequent trays can find it if they reference the same tag
  3354. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  3355. if not spool_exists:
  3356. cached_spools.append(result)
  3357. logger.debug(
  3358. "[Printer %s] Added newly created spool %s to cache",
  3359. printer_id,
  3360. result["id"],
  3361. )
  3362. # Reconcile slot_preset_mappings (the same row internal
  3363. # mode keeps in sync via inventory + spool_tag_matcher).
  3364. # Without this the slot card surfaces the previous spool's
  3365. # preset name — same bug shape, different inventory mode.
  3366. from backend.app.services.slot_preset_writer import (
  3367. upsert_slot_preset_for_spoolman_spool,
  3368. )
  3369. await upsert_slot_preset_for_spoolman_spool(
  3370. db=db,
  3371. spoolman_spool=result,
  3372. tray_info_idx=tray.tray_info_idx or "",
  3373. tray_sub_brands=tray.tray_sub_brands or "",
  3374. tray_type=tray.tray_type or "",
  3375. printer_id=printer_id,
  3376. ams_id=ams_id,
  3377. tray_id=tray.tray_id,
  3378. )
  3379. except Exception as e:
  3380. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  3381. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  3382. if synced > 0:
  3383. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  3384. # Persist slot assignment changes to the local table: only slots
  3385. # whose spool this pass changed, and only while they still hold what
  3386. # it read before awaiting Spoolman, so a spool assigned by hand in
  3387. # between stays (SSA-3). The changed slots are announced: the slot
  3388. # card reads slot_preset_mappings (rewritten above) ahead of the live
  3389. # tray, so with no event it kept the previous spool's preset name.
  3390. if slot_changes or empty_slots:
  3391. from backend.app.services.spoolman_slot_sync import write_slot_results
  3392. try:
  3393. await write_slot_results(
  3394. db,
  3395. {(printer_id, a_id, t_id): spool_id for (a_id, t_id), spool_id in spoolman_slot_map.items()}
  3396. if slot_map_read
  3397. else None,
  3398. [(printer_id, a_id, t_id, spool_id) for a_id, t_id, spool_id in slot_changes],
  3399. [(printer_id, a_id, t_id) for a_id, t_id in empty_slots],
  3400. )
  3401. except Exception as e:
  3402. await db.rollback()
  3403. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3404. except Exception as e:
  3405. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3406. # Largest finish photo attached to a notification; a bigger one is still linked.
  3407. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3408. async def _finish_photo_for_notification(
  3409. db, archive, archive_id: int, filename: str
  3410. ) -> tuple[str | None, bytes | None]:
  3411. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3412. With authentication off the link is the archive's own photo route, as it
  3413. always was: it opens without a login and doesn't expire. With
  3414. authentication on that route needs a media token, which nothing tapping a
  3415. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3416. link only ever answered 401. The photo is then saved as a notification
  3417. photo as well (utils/notification_photos.py) and the link points there: an
  3418. unguessable name that opens this one photo and nothing else, for 3 days.
  3419. The link is relative when no External URL is set. Bytes over
  3420. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3421. ``(None, None)`` when the photo can't be found.
  3422. """
  3423. from backend.app.api.routes.settings import get_setting
  3424. from backend.app.core.auth import is_auth_enabled
  3425. from backend.app.utils.archive_paths import find_archive_photo
  3426. from backend.app.utils.notification_photos import save_notification_photo
  3427. log = logging.getLogger(__name__)
  3428. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3429. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3430. photo_bytes: bytes | None = None
  3431. try:
  3432. photo_path = find_archive_photo(archive, filename)
  3433. if photo_path is not None:
  3434. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3435. except Exception as e:
  3436. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3437. try:
  3438. auth_on = await is_auth_enabled(db)
  3439. except Exception:
  3440. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3441. if auth_on:
  3442. url = None
  3443. if photo_bytes:
  3444. try:
  3445. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3446. url = f"{base}/api/v1/notifications/photos/{name}"
  3447. except Exception as e:
  3448. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3449. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3450. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3451. return url, None
  3452. if photo_bytes:
  3453. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3454. return url, photo_bytes
  3455. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3456. """Capture a camera snapshot for notification image attachment.
  3457. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3458. Uses: external camera > buffered frame > fresh capture.
  3459. Turns the chamber light on for the picture when the printer asks for it
  3460. (#1655). ``light=False`` is for callers that capture all through a print,
  3461. where the light would flash with every frame.
  3462. """
  3463. if not printer:
  3464. return None
  3465. async with camera_light(printer if light else None):
  3466. return await _capture_snapshot_frame(printer_id, printer, logger)
  3467. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3468. """The capture behind ``_capture_snapshot_for_notification``."""
  3469. try:
  3470. from backend.app.api.routes.settings import get_setting
  3471. async with async_session() as db:
  3472. capture_enabled = await get_setting(db, "capture_finish_photo")
  3473. if capture_enabled is not None and capture_enabled.lower() != "true":
  3474. return None
  3475. # Try external camera first
  3476. if printer.external_camera_enabled and printer.external_camera_url:
  3477. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3478. from backend.app.api.routes.camera import live_frame_for_capture
  3479. from backend.app.services.external_camera import capture_frame
  3480. # An external camera allows one reader, so capturing while a viewer
  3481. # is attached fails (#2707). A None here falls through to the paths
  3482. # below exactly as a failed capture did.
  3483. defer, buffered = live_frame_for_capture(printer_id)
  3484. if defer:
  3485. frame_data = buffered
  3486. else:
  3487. frame_data = await capture_frame(
  3488. printer.external_camera_url,
  3489. printer.external_camera_type or "mjpeg",
  3490. snapshot_url=printer.external_camera_snapshot_url,
  3491. )
  3492. if frame_data and len(frame_data) <= 2_500_000:
  3493. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3494. return _apply_camera_rotation(frame_data, printer, logger)
  3495. # Try buffered frame from active stream
  3496. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3497. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3498. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3499. buffered_frame = get_buffered_frame(printer_id)
  3500. if (active_for_printer or active_chamber) and buffered_frame:
  3501. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3502. if len(buffered_frame) <= 2_500_000:
  3503. return _apply_camera_rotation(buffered_frame, printer, logger)
  3504. # Fresh capture from printer camera
  3505. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3506. from backend.app.services.camera import capture_camera_frame_bytes
  3507. frame_data = await capture_camera_frame_bytes(
  3508. printer.ip_address, printer.access_code, printer.model, timeout=15
  3509. )
  3510. if frame_data and len(frame_data) <= 2_500_000:
  3511. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3512. return _apply_camera_rotation(frame_data, printer, logger)
  3513. except Exception as e:
  3514. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3515. return None
  3516. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3517. """#1867: bank a recent in-print camera frame for the finish photo.
  3518. Called on every layer change and (#2547) on every print-progress advance.
  3519. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3520. path has a pre-End-G-code image for prints that end with a plate swap.
  3521. Both drivers are print telemetry that stops the instant printing ends: no
  3522. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3523. plate swap) executes. So the last banked frame is always the finished print,
  3524. never the swapped plate — that property is what the #1867 path relies on and
  3525. it must survive any change to the throttle below.
  3526. Layer changes alone were not enough: they stop when the *final* layer
  3527. begins, which on a three-minute last layer left the bank stale by the whole
  3528. length of that layer (#2547). Progress keeps ticking through it.
  3529. Best-effort: any failure just leaves the previous banked frame.
  3530. """
  3531. logger = logging.getLogger(__name__)
  3532. client = printer_manager.get_client(printer_id)
  3533. state = client.state if client else None
  3534. if not state or state.state != "RUNNING":
  3535. return
  3536. # Only during actual extrusion — firmware ticks layer_num during the
  3537. # pre-print calibration sequence, whose sub-stages are non-zero.
  3538. if state.mc_print_sub_stage not in (None, 0):
  3539. return
  3540. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3541. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3542. # now that progress advances also drive banking, that exemption would fire a
  3543. # camera grab on every percent tick of the last layer. Bambu printers accept
  3544. # one RTSP client at a time, so each grab contends with the live view.
  3545. now = time.monotonic()
  3546. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3547. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3548. return
  3549. total = state.total_layers or 0
  3550. try:
  3551. async with async_session() as db:
  3552. from backend.app.models.printer import Printer
  3553. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3554. printer = result.scalar_one_or_none()
  3555. if not printer:
  3556. return
  3557. # Reuses the notification snapshot path, which honours the
  3558. # `capture_finish_photo` setting (returns None when disabled) so we
  3559. # don't bank frames the user never asked for. Without the chamber light
  3560. # (#1655): this runs every 25 seconds for the whole print.
  3561. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3562. if frame:
  3563. _inprint_frame_bank[printer_id] = frame
  3564. _inprint_frame_bank_ts[printer_id] = now
  3565. logger.debug(
  3566. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3567. printer_id,
  3568. layer_num,
  3569. total,
  3570. len(frame),
  3571. )
  3572. except Exception as e:
  3573. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3574. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3575. """Apply camera rotation to snapshot image if configured."""
  3576. from backend.app.services.camera import apply_camera_rotation
  3577. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3578. async def _send_print_start_notification(
  3579. printer_id: int,
  3580. data: dict,
  3581. archive_data: dict | None = None,
  3582. logger=None,
  3583. ):
  3584. """Helper to send print start notification with optional archive data."""
  3585. if logger is None:
  3586. logger = logging.getLogger(__name__)
  3587. try:
  3588. async with async_session() as db:
  3589. from backend.app.models.printer import Printer
  3590. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3591. printer = result.scalar_one_or_none()
  3592. printer_name = printer.name if printer else f"Printer {printer_id}"
  3593. # Capture camera snapshot for notification image attachment
  3594. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3595. if image_data:
  3596. if archive_data is None:
  3597. archive_data = {}
  3598. archive_data["image_data"] = image_data
  3599. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3600. # Send user-specific email notification for print start
  3601. if archive_data and archive_data.get("created_by_id"):
  3602. await notification_service.send_user_print_email(
  3603. event_type="user_print_start",
  3604. created_by_id=archive_data["created_by_id"],
  3605. printer_name=printer_name,
  3606. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3607. db=db,
  3608. )
  3609. except Exception as e:
  3610. logger.warning("Notification on_print_start failed: %s", e)
  3611. async def _dispatch_user_print_email(
  3612. status: str,
  3613. created_by_id: int | None,
  3614. printer_name: str,
  3615. filename: str,
  3616. db,
  3617. image_data: bytes | None = None,
  3618. finish_photo_url: str | None = None,
  3619. ) -> None:
  3620. """Send a user-specific print-completion email based on print status.
  3621. Maps the normalised print status to the correct event type and delegates
  3622. to :meth:`NotificationService.send_user_print_email`. A single helper
  3623. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3624. "stopped"`` dispatch block at every call site.
  3625. Does nothing if *created_by_id* is ``None``.
  3626. """
  3627. if created_by_id is None:
  3628. return
  3629. if status == "completed":
  3630. event_type = "user_print_complete"
  3631. elif status == "failed":
  3632. event_type = "user_print_failed"
  3633. elif status in ("stopped", "aborted", "cancelled"):
  3634. event_type = "user_print_stopped"
  3635. else:
  3636. return
  3637. await notification_service.send_user_print_email(
  3638. event_type=event_type,
  3639. created_by_id=created_by_id,
  3640. printer_name=printer_name,
  3641. filename=filename,
  3642. db=db,
  3643. image_data=image_data,
  3644. finish_photo_url=finish_photo_url,
  3645. )
  3646. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3647. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3648. try:
  3649. from backend.app.services.archive import extract_printable_objects_from_archive
  3650. client = printer_manager.get_client(printer_id)
  3651. if not client:
  3652. return
  3653. # Extract with positions for UI overlay, scoped to the plate that
  3654. # is printing — resolve_plate_id is the same resolver /cover uses,
  3655. # so the object list can't disagree with the thumbnail it is drawn
  3656. # over (#2522).
  3657. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3658. app_settings.base_dir / archive.file_path,
  3659. plate_number=resolve_plate_id(client.state),
  3660. )
  3661. if printable_objects:
  3662. client.state.printable_objects = printable_objects
  3663. client.state.printable_objects_bbox_all = bbox_all
  3664. client.state.skipped_objects = []
  3665. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3666. except Exception as e:
  3667. logger.debug("Failed to extract printable objects from archive: %s", e)
  3668. def _load_pauses_from_3mf(threemf_path, printer_id: int, *, warned_layers=(), passed_through_layer: int = 0) -> None:
  3669. """Read the running print's slicer pauses from its 3MF, in the background (#2984).
  3670. In a thread: a plate's G-code runs to tens of MB, and the print-start
  3671. handler must not wait for it. Kept only while the printer is still on
  3672. the print they were read for: a new print replaces the list.
  3673. ``warned_layers``: pauses this print was already warned about, kept on its
  3674. archive, so a restart does not send the heads-up again.
  3675. ``passed_through_layer``: for a print resumed after a restart, the layer it
  3676. is on. Its pauses up to there are behind it, though the printer's layer
  3677. reads 0 until it reports the next one.
  3678. """
  3679. client = printer_manager.get_client(printer_id)
  3680. if not client:
  3681. return
  3682. state = client.state
  3683. read_for = state.pause_points
  3684. try:
  3685. plate_id = resolve_plate_id(state)
  3686. except Exception:
  3687. # Never at the cost of the print-start handler this runs inside.
  3688. logging.getLogger(__name__).warning("[Printer %s] Could not tell the plate to read pauses for", printer_id)
  3689. return
  3690. async def _load() -> None:
  3691. from backend.app.utils.threemf_tools import extract_pause_points_from_3mf
  3692. points = await asyncio.to_thread(extract_pause_points_from_3mf, Path(threemf_path), plate_id)
  3693. if state.pause_points is not read_for:
  3694. return
  3695. state.pause_points = [p for p in points if p.layer > passed_through_layer]
  3696. state.pause_warned_layers = set(state.pause_warned_layers) | set(warned_layers)
  3697. if points:
  3698. logging.getLogger(__name__).info(
  3699. "Loaded %s slicer pause(s) for printer %s at layer(s) %s",
  3700. len(points),
  3701. printer_id,
  3702. [p.layer for p in points],
  3703. )
  3704. spawn_background_task(_load(), name=f"load-pauses-{printer_id}")
  3705. def _load_pauses_from_resumed_archive(archive, printer_id: int) -> None:
  3706. """Pauses for a print start taken as the resumption of a running print.
  3707. A restart while the print was paused makes its resume look like a new
  3708. print (#2984): the pauses warned about and passed are kept from before.
  3709. """
  3710. client = printer_manager.get_client(printer_id)
  3711. state = client.state if client else None
  3712. _load_pauses_from_3mf(
  3713. app_settings.base_dir / archive.file_path,
  3714. printer_id,
  3715. warned_layers=pause_eta.warned_layers_of(archive, state) if state is not None else (),
  3716. passed_through_layer=getattr(client, "layer_before_new_print", 0) if client else 0,
  3717. )
  3718. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3719. """Put the skip-objects list back after a restart mid-print.
  3720. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3721. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3722. which the #1304 guard suppresses on the first RUNNING push after startup.
  3723. Everything else this hook restores (the archive, the usage-tracking session,
  3724. the timelapse baseline) was already handled; the object list was not, so a
  3725. restart mid-print took skip-objects away for the rest of that print.
  3726. Nothing recovered it either: the printer card gates its Skip button on the
  3727. object count, and the one endpoint that can rebuild the list is reachable
  3728. only from the modal that button opens.
  3729. The archive is the running print's as ``running_print_archive`` finds it:
  3730. by subtask_id, or for a print that reports none by the archive bound to it
  3731. (#3327), never by name: a leftover ``status="printing"`` row from a
  3732. completion we never saw must not hand this print someone else's objects.
  3733. After a restart that binding exists only for Bambuddy's own prints, so a
  3734. print that reports no subtask_id loads nothing rather than a guess; the
  3735. reload path on ``GET /print/objects`` covers that case on demand.
  3736. """
  3737. client = printer_manager.get_client(printer_id)
  3738. if client is None or (client.state.printable_objects and client.state.pause_points):
  3739. return
  3740. archive = await running_print_archive(db, printer_id, state, printing_only=True, by_name=False)
  3741. if archive is not None and archive.file_path:
  3742. if not client.state.printable_objects:
  3743. _load_objects_from_archive(archive, printer_id, logger)
  3744. # The slicer's pauses are in-memory only as well (#2984).
  3745. if not client.state.pause_points:
  3746. _load_pauses_from_3mf(
  3747. app_settings.base_dir / archive.file_path,
  3748. printer_id,
  3749. warned_layers=pause_eta.warned_layers_of(archive, state),
  3750. )
  3751. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3752. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3753. # past it; the second covers a handshake that failed again on the way back and
  3754. # armed a fresh one. Module-level so tests can shrink them.
  3755. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3756. # Retry ladder for the other temporary give-up: the file service answered and
  3757. # the transfer still did not finish, which at print start is usually the printer
  3758. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3759. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3760. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3761. # two cover a printer that stays busy well into the print.
  3762. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3763. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3764. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3765. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3766. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3767. # by view, so two views race), the cool-off retry task, and print completion.
  3768. # Without this they each read file_path == "" and each run a full copy, so the row
  3769. # ends up pointing at one timestamped directory while the others sit orphaned.
  3770. #
  3771. # Keyed by printer rather than archive because a printer runs one print at a time,
  3772. # which makes the two equally strong here — and it bounds the dict by printer
  3773. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3774. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3775. # resuming, so "no waiters" is not a question this API can answer.
  3776. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3777. # How many of a printer's newest archives a touchscreen reprint is compared
  3778. # against (#3307). A repeat is usually of a recent job; the bound keeps a
  3779. # print start from reading a long history's extra_data.
  3780. _REPEAT_LOOKBACK = 200
  3781. async def _archived_3mf_for_repeat(
  3782. db, printer_id: int, subtask_name: str | None, gcode_file: str | None, total_layers: int | None
  3783. ):
  3784. """The newest archive of the job this printer is running again, with its 3MF.
  3785. A "Print again" on the printer's screen never names the file on the card:
  3786. it reports its own history copy under a generic name
  3787. (``file:///userdata/project_file.gcode.3mf``), the 3MF's internal title as
  3788. ``subtask_name`` and the plate as ``gcode_file`` -- and the title is often
  3789. not the card file's name, so every lookup built from it misses (#3307).
  3790. An earlier run that was archived recorded that same title and plate in its
  3791. ``_print_data``, and holds the 3MF.
  3792. Same printer, same title, same plate, a 3MF still on disk. A layer count
  3793. known on both sides must agree: the same title and plate re-sliced is
  3794. another job. None when nothing matches.
  3795. """
  3796. from backend.app.models.archive import PrintArchive
  3797. if not subtask_name or not gcode_file:
  3798. return None
  3799. rows = (
  3800. (
  3801. await db.execute(
  3802. select(PrintArchive)
  3803. .where(
  3804. PrintArchive.printer_id == printer_id,
  3805. PrintArchive.deleted_at.is_(None),
  3806. PrintArchive.file_path.isnot(None),
  3807. PrintArchive.file_path != "",
  3808. )
  3809. .order_by(PrintArchive.created_at.desc(), PrintArchive.id.desc())
  3810. .limit(_REPEAT_LOOKBACK)
  3811. )
  3812. )
  3813. .scalars()
  3814. .all()
  3815. )
  3816. for archive in rows:
  3817. extra = archive.extra_data if isinstance(archive.extra_data, dict) else {}
  3818. run = extra.get("_print_data")
  3819. if not isinstance(run, dict):
  3820. continue
  3821. if run.get("subtask_name") != subtask_name or run.get("filename") != gcode_file:
  3822. continue
  3823. if total_layers and archive.total_layers and archive.total_layers != total_layers:
  3824. continue
  3825. if not (app_settings.base_dir / archive.file_path).is_file():
  3826. continue
  3827. return archive
  3828. return None
  3829. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True) -> bool:
  3830. """Fill in a no-3MF archive from a 3MF that turned up later.
  3831. Returns True when the row was upgraded. Safe to call speculatively: it
  3832. verifies the archive still exists, is still a fallback, and that the file
  3833. is a readable 3MF before touching anything.
  3834. Serialised per printer — see ``_fallback_recovery_locks``.
  3835. """
  3836. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3837. async with lock:
  3838. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id, price=price)
  3839. async def _recover_fallback_archive_locked(
  3840. archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True
  3841. ) -> bool:
  3842. """The body of :func:`_recover_fallback_archive`, under its per-printer lock.
  3843. ``price`` is False when the print's end is being handled: the archive
  3844. still reads "printing" then, and its end prices it.
  3845. """
  3846. import zipfile
  3847. from backend.app.models.archive import PrintArchive
  3848. from backend.app.services.archive import ArchiveService
  3849. logger = logging.getLogger(__name__)
  3850. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3851. return False
  3852. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3853. # A truncated or half-written download is worse than no download: it
  3854. # would replace an honest empty archive with wrong metadata.
  3855. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3856. return False
  3857. async with async_session() as db:
  3858. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3859. if archive is None or archive.deleted_at is not None:
  3860. return False
  3861. if archive.file_path:
  3862. # Already recovered, or never was a fallback. Either way there is a
  3863. # real 3MF attached and overwriting it is not this function's job.
  3864. return False
  3865. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3866. service = ArchiveService(db)
  3867. recovered = await service.archive_print(
  3868. printer_id=printer_id,
  3869. source_file=source_3mf,
  3870. print_data={**print_data, "status": archive.status or "printing"},
  3871. subtask_id=archive.subtask_id,
  3872. update_archive_id=archive.id,
  3873. )
  3874. if recovered is None:
  3875. return False
  3876. logger.info(
  3877. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3878. archive_id,
  3879. source_3mf,
  3880. recovered.file_size,
  3881. )
  3882. # Spoolman's tracking stored no 3MF usage at print start and would
  3883. # charge the AMS remain% change; the built-in tracker reads the archive
  3884. # at completion and needs nothing. Also at the print's end (``price``
  3885. # False): that recovery runs inside the close-out, before the charge.
  3886. try:
  3887. from backend.app.services.spoolman_tracking import attach_recovered_3mf
  3888. from backend.app.services.usage_tracker import is_completing
  3889. await attach_recovered_3mf(
  3890. printer_id,
  3891. recovered.id,
  3892. recovered.file_path,
  3893. db,
  3894. printer_manager,
  3895. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3896. may_start=not price or (recovered.status == "printing" and not is_completing(printer_id)),
  3897. )
  3898. except Exception:
  3899. logger.warning(
  3900. "[RECOVER] Archive %s: could not add the 3MF to Spoolman's usage tracking", archive_id, exc_info=True
  3901. )
  3902. if price and recovered.status == "printing" and recovered.file_path:
  3903. # Print start had no 3MF to read the slicer's pauses from (#2984).
  3904. _load_pauses_from_3mf(app_settings.base_dir / recovered.file_path, printer_id)
  3905. if price and recovered.status == "printing":
  3906. # Print start priced it from the default rate, having no 3MF to
  3907. # estimate from; now it has one. An ended print is left alone: its
  3908. # end prices it. A print Bambuddy didn't dispatch has no start
  3909. # plate; the one the archive just read from the 3MF stands in.
  3910. _schedule_archive_cost_estimate(
  3911. printer_id,
  3912. recovered.id,
  3913. printer_manager,
  3914. ams_mapping=_get_start_ams_mapping(print_data, printer_id, recovered.id),
  3915. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3916. session_factory=async_session,
  3917. )
  3918. # `archive_updated`, not `archive_created` — the row was already on the
  3919. # Archives page as an empty card and is now filled in, not new.
  3920. await ws_manager.send_archive_updated(
  3921. {
  3922. "id": recovered.id,
  3923. "printer_id": recovered.printer_id,
  3924. "filename": recovered.filename,
  3925. "print_name": recovered.print_name,
  3926. "status": recovered.status,
  3927. }
  3928. )
  3929. return True
  3930. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path, *, price: bool = True) -> bool:
  3931. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3932. Called from the paths that pull a 3MF for a print that is already under way
  3933. — chiefly the cover endpoint, which downloads the very file the archive flow
  3934. could not get and, before #2957, used it for a thumbnail and nothing else.
  3935. The bytes are already local, so this costs a parse and a row update.
  3936. No-op when the running print has a real archive, which is the common case.
  3937. """
  3938. from backend.app.models.archive import PrintArchive
  3939. logger = logging.getLogger(__name__)
  3940. # `_active_prints` is keyed on the raw names seen at print start — the
  3941. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3942. # Callers here arrive with whichever variant their own path produced, so
  3943. # match on the same normalization the download cache uses rather than on an
  3944. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3945. # endpoint find an archive registered under "Desktop_Goose".
  3946. wanted = normalize_3mf_name(name)
  3947. archive_id = None
  3948. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3949. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3950. archive_id = value
  3951. break
  3952. if archive_id is None:
  3953. return False
  3954. async with async_session() as db:
  3955. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3956. # Cheap pre-check so the common case (a normal archive) does no work.
  3957. if archive is None or archive.file_path or archive.deleted_at is not None:
  3958. return False
  3959. try:
  3960. return await _recover_fallback_archive(archive_id, path, printer_id, price=price)
  3961. except Exception as e:
  3962. # Recovery is opportunistic. A failure here must never take down the
  3963. # caller, which is usually just trying to render a thumbnail.
  3964. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3965. return False
  3966. def _schedule_fallback_3mf_retry(
  3967. printer_id: int,
  3968. archive_id: int,
  3969. filenames: list[str],
  3970. delays: tuple[float, ...] | None = None,
  3971. reason: str = REASON_FTPS_COOLOFF,
  3972. ) -> None:
  3973. """Re-attempt the 3MF download after a temporary give-up.
  3974. ``reason`` says which give-up this is, and picks the default ladder: an
  3975. FTPS cool-off has to be waited out, while a transfer that timed out under
  3976. contention is worth asking about again straight away (#3063). It is only
  3977. read for the ladder and the log line -- the retry itself is identical, since
  3978. in both cases the file is on the printer and the last attempt at it failed
  3979. for a reason that does not last.
  3980. """
  3981. logger = logging.getLogger(__name__)
  3982. if delays is None:
  3983. delays = (
  3984. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3985. if reason == REASON_FTP_TRANSFER_FAILED
  3986. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3987. )
  3988. async def _retry() -> None:
  3989. from backend.app.models.archive import PrintArchive
  3990. from backend.app.models.printer import Printer
  3991. for delay in delays:
  3992. await asyncio.sleep(delay)
  3993. async with async_session() as db:
  3994. archive = (
  3995. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3996. ).scalar_one_or_none()
  3997. if archive is None or archive.deleted_at is not None or archive.file_path:
  3998. return
  3999. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  4000. if printer is None:
  4001. return
  4002. # Read the fields while the session is open rather than touching
  4003. # a detached instance minutes later, mid-download.
  4004. printer_ip = printer.ip_address
  4005. printer_code = printer.access_code
  4006. printer_model = printer.model
  4007. # Someone else may have fetched it in the meantime — the cover
  4008. # endpoint routinely does, and its copy is the same bytes.
  4009. for name in filenames:
  4010. cached = get_cached_3mf(printer_id, name)
  4011. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  4012. return
  4013. if ftps_handshake_blocked(printer_ip):
  4014. logger.info(
  4015. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  4016. printer_id,
  4017. archive_id,
  4018. )
  4019. continue
  4020. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  4021. for candidate in filenames:
  4022. # Bare name only. These come from the print-start flow, which
  4023. # already strips the path, but the local temp write must not
  4024. # depend on that holding for every future caller — a name that
  4025. # is absolute or contains ".." would otherwise escape the data
  4026. # volume via the `/` operator.
  4027. name = Path(candidate).name
  4028. if not name or name in (".", ".."):
  4029. continue
  4030. if not name.endswith(".3mf"):
  4031. name = f"{name}.3mf"
  4032. temp_path = app_settings.archive_dir / "temp" / name
  4033. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4034. try:
  4035. hit = await download_file_try_paths_async(
  4036. printer_ip,
  4037. printer_code,
  4038. ftp_probe_paths(name),
  4039. temp_path,
  4040. socket_timeout=ftp_timeout,
  4041. printer_model=printer_model,
  4042. max_total_timeout=RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  4043. )
  4044. except Exception as e:
  4045. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  4046. continue
  4047. if not hit:
  4048. continue
  4049. cache_3mf_download(printer_id, name, temp_path)
  4050. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  4051. return
  4052. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  4053. async def _guarded() -> None:
  4054. try:
  4055. await _retry()
  4056. except asyncio.CancelledError:
  4057. raise
  4058. except Exception as e:
  4059. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  4060. finally:
  4061. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  4062. _fallback_3mf_retry_tasks.pop(printer_id, None)
  4063. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  4064. if existing and not existing.done():
  4065. existing.cancel()
  4066. task = asyncio.create_task(_guarded())
  4067. _fallback_3mf_retry_tasks[printer_id] = task
  4068. logger.info(
  4069. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  4070. archive_id,
  4071. reason,
  4072. printer_id,
  4073. ", ".join(f"{d:g}s" for d in delays),
  4074. )
  4075. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  4076. """Whether an archive created here should ask for the print's outcome (#1898).
  4077. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  4078. branches below: a queued job already has its archive and takes the
  4079. expected-print branch, where the queue item's own ``confirm_outcome``
  4080. decides. The queue is still consulted, because a restart mid-print empties
  4081. ``_expected_prints`` — without the check the setting could override a queue
  4082. item that deliberately has the flag off. Any failure answers "don't ask":
  4083. an unwanted prompt is worse than a missing one, and this must never be the
  4084. reason a print goes unarchived.
  4085. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  4086. leaves one behind when a completion cannot be matched to it
  4087. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  4088. only takes it back once the printer has sat connected and terminal for
  4089. minutes. Until then every screen-started print on that printer would
  4090. silently lose its prompt, so the row is held against ``observed_name`` by
  4091. the same comparison a completion uses: a positive disagreement means the row
  4092. is about some other run and this print is external after all.
  4093. """
  4094. logger = logging.getLogger(__name__)
  4095. try:
  4096. # A savepoint rather than a rollback of the caller's transaction on
  4097. # failure: a failed statement leaves the transaction unusable, but a
  4098. # full rollback also expires every object the caller has loaded (the
  4099. # printer, the archive it just created), and on an async session the
  4100. # next attribute read then raises instead of reloading. Everything here
  4101. # is a read, so undoing the savepoint loses nothing.
  4102. async with db.begin_nested():
  4103. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  4104. except Exception as e:
  4105. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  4106. return False
  4107. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  4108. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  4109. from backend.app.api.routes.settings import get_setting, setting_is_true
  4110. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  4111. return False
  4112. from backend.app.models.print_queue import PrintQueueItem
  4113. dispatched_here = await db.scalar(
  4114. select(PrintQueueItem)
  4115. .where(
  4116. PrintQueueItem.printer_id == printer_id,
  4117. PrintQueueItem.status == "printing",
  4118. )
  4119. .limit(1)
  4120. )
  4121. if dispatched_here is None:
  4122. return True
  4123. expected = await _queue_item_dispatched_name(db, dispatched_here)
  4124. observed = (observed_name or "").strip()
  4125. if not expected or not observed or _subtask_names_match(expected, observed):
  4126. logger.info(
  4127. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  4128. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  4129. printer_id,
  4130. dispatched_here.id,
  4131. )
  4132. return False
  4133. logger.info(
  4134. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  4135. "%r; treating this as an externally started print.",
  4136. dispatched_here.id,
  4137. printer_id,
  4138. expected,
  4139. observed,
  4140. )
  4141. return True
  4142. async def _dispatch_outcome_confirmation_safely(
  4143. db,
  4144. printer_id: int,
  4145. printer_name: str,
  4146. data: dict,
  4147. archive_id: int,
  4148. archive_data: dict | None = None,
  4149. run_id: int | None = None,
  4150. ) -> None:
  4151. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  4152. The completion task sends the per-user print email on the same session
  4153. right after the prompt. A failed statement in the prompt leaves that
  4154. session needing a rollback, and without one the email step fails with
  4155. PendingRollbackError; the prompt is the optional part, so it must not be
  4156. the reason the email never goes out.
  4157. """
  4158. try:
  4159. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data, run_id=run_id)
  4160. except Exception as e:
  4161. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  4162. try:
  4163. await db.rollback()
  4164. except Exception:
  4165. pass
  4166. async def _outcome_answerers(db, owner_id: int | None) -> set[int] | None:
  4167. """Who may answer a print's outcome prompt in the app: its owner and anyone
  4168. who may change everyone's archives. None (everyone on the printer) with auth
  4169. off, or for a print nobody owns."""
  4170. from sqlalchemy.orm import selectinload
  4171. from backend.app.core.auth import is_auth_enabled
  4172. from backend.app.core.permissions import Permission
  4173. from backend.app.models.user import User
  4174. if owner_id is None or not await is_auth_enabled(db):
  4175. return None
  4176. users = (await db.execute(select(User).options(selectinload(User.groups)).where(User.is_active))).scalars().all()
  4177. return {owner_id} | {u.id for u in users if u.has_permission(Permission.ARCHIVES_UPDATE_ALL.value)}
  4178. async def dispatch_outcome_confirmation(
  4179. db,
  4180. printer_id: int,
  4181. printer_name: str,
  4182. data: dict,
  4183. archive_id: int,
  4184. archive_data: dict | None = None,
  4185. *,
  4186. run_id: int | None = None,
  4187. ) -> bool:
  4188. """Emit the post-print outcome prompt for a completed print (#1898).
  4189. Gated on the run that ended (``run_id``): ``confirm_requested`` is the
  4190. opt-in (from the queue item, or from ``confirm_outcome_external_prints``
  4191. for a print Bambuddy did not start, copied onto the run at its start) and
  4192. ``user_verdict`` being unset is what makes the question still open. Mints
  4193. the run's capability token the one-tap verdict links carry: plates of one
  4194. archive each have their own question. Without a run, the archive's, as
  4195. before runs.
  4196. Lives here rather than inline in ``on_print_complete``'s notification task
  4197. because that task swallows every exception: extracted, the gate and the two
  4198. emissions can be driven by a test, which is the only thing standing between
  4199. a regression here and a farm that quietly stops asking.
  4200. Returns whether a prompt was sent.
  4201. """
  4202. logger = logging.getLogger(__name__)
  4203. from backend.app.models.archive import PrintArchive
  4204. from backend.app.models.print_log import PrintLogEntry
  4205. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  4206. if confirm_archive is None:
  4207. return False
  4208. run = await db.get(PrintLogEntry, run_id) if run_id is not None else None
  4209. if run is not None and run.archive_id != archive_id:
  4210. run = None
  4211. # The run carries the opt-in from its start; one logged before it did
  4212. # (None) asks as its archive does.
  4213. asks = confirm_archive if run is None or run.confirm_requested is None else run
  4214. holder = run if run is not None else confirm_archive
  4215. if not (asks.confirm_requested and holder.user_verdict is None):
  4216. return False
  4217. import secrets as _secrets
  4218. # A spent token stays on the row so the one-tap route can recognise it, so
  4219. # "has a token" no longer means "answerable". A prompt going out now needs a
  4220. # live one: mint a new token whenever the stored one is already spent, or
  4221. # every button in the new message would land on the already-answered page.
  4222. if not holder.confirm_token or holder.confirm_token_used_at is not None:
  4223. holder.confirm_token = _secrets.token_urlsafe(32)
  4224. holder.confirm_token_used_at = None
  4225. await db.commit()
  4226. from backend.app.api.routes.settings import get_external_base_url, get_setting
  4227. base = await get_external_base_url(db)
  4228. if not await get_setting(db, "external_url"):
  4229. # Both the Telegram inline keyboard and the ntfy action buttons need an
  4230. # absolute URL, so an unconfigured install used to get a message body
  4231. # with two unusable relative paths and no buttons at all. The shared
  4232. # fallback at least produces tappable links; say which setting makes
  4233. # them resolve from a phone.
  4234. logger.warning(
  4235. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  4236. "Set Settings → External URL so they resolve away from this host.",
  4237. base,
  4238. )
  4239. token = holder.confirm_token
  4240. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  4241. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  4242. confirm_url = f"{base}/archives?confirm={archive_id}" + (f"&run={run.id}" if run is not None else "")
  4243. await ws_manager.send_print_confirm_request(
  4244. printer_id,
  4245. {
  4246. "archive_id": archive_id,
  4247. "run_id": run.id if run is not None else None,
  4248. "print_name": confirm_archive.print_name or confirm_archive.filename,
  4249. },
  4250. user_ids=await _outcome_answerers(db, confirm_archive.created_by_id),
  4251. )
  4252. await notification_service.on_print_confirm_request(
  4253. printer_id,
  4254. printer_name,
  4255. data,
  4256. db,
  4257. archive_data=archive_data,
  4258. good_url=good_url,
  4259. reject_url=reject_url,
  4260. confirm_url=confirm_url,
  4261. archive_id=archive_id,
  4262. run_id=run.id if run is not None else None,
  4263. )
  4264. return True
  4265. async def _printer_gone(db, printer_id: int) -> bool:
  4266. """Whether the printer was deleted. A column read: the session's loaded
  4267. Printer would otherwise answer for the database."""
  4268. from backend.app.models.printer import Printer
  4269. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  4270. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  4271. """Remove the archive just written if its printer was deleted meanwhile.
  4272. The delete route sweeps the printer's archives before it commits, so a row
  4273. committed after that sweep (the check before writing passed while the
  4274. delete was still uncommitted) is left for a printer that will never report
  4275. the print's end. A row the sweep reached is the route's: deleted with the
  4276. printer's archives, or detached (printer_id NULL) when the user kept them,
  4277. and then left as it is. Either way nothing is registered for it. Run after
  4278. the archive's commit, before anything is registered for it.
  4279. """
  4280. from backend.app.models.archive import PrintArchive
  4281. if not await _printer_gone(db, printer_id):
  4282. return False
  4283. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  4284. if owner == printer_id:
  4285. logging.getLogger(__name__).info(
  4286. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  4287. )
  4288. await ArchiveService(db).delete_archive(archive_id)
  4289. await forget_printer(printer_id)
  4290. return True
  4291. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  4292. """After an IntegrityError on a print start's archive write: whether it was
  4293. the printer being deleted, forgotten then (the caller returns).
  4294. PostgreSQL: the delete route locks the printer from its archive sweep to its
  4295. commit, so an archive written or adopted for it meanwhile (one that sets
  4296. printer_id) waits and the printer's foreign key then refuses it. That is
  4297. the printer being deleted, not an error; anything else is re-raised by the
  4298. caller.
  4299. """
  4300. await db.rollback()
  4301. if not await _printer_gone(db, printer_id):
  4302. return False
  4303. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  4304. await forget_printer(printer_id)
  4305. return True
  4306. async def _forget_if_printer_gone(printer_id: int) -> None:
  4307. """At the end of a print start: the slow steps after the last check (smart
  4308. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  4309. printer's delete and its forget_printer, and then wrote state back.
  4310. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  4311. SQLite; PostgreSQL refuses it.)
  4312. Its own session: those steps can leave the handler's needing a rollback (a
  4313. write to the archive the delete removed). Never raises: it runs inside the
  4314. fallback branch's try, whose except reports the archive as failed.
  4315. """
  4316. try:
  4317. async with async_session() as db:
  4318. gone = await _printer_gone(db, printer_id)
  4319. if gone:
  4320. await forget_printer(printer_id)
  4321. except Exception:
  4322. logging.getLogger(__name__).warning(
  4323. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  4324. )
  4325. async def _announce_plate_check_failed(printer_id: int, printer_name: str, reason: str) -> None:
  4326. """Tell the UI a plate check could not run. It does not block the print,
  4327. but an unchecked plate is not an empty one."""
  4328. try:
  4329. await ws_manager.broadcast(
  4330. {"type": "plate_check_failed", "printer_id": printer_id, "printer_name": printer_name, "reason": reason}
  4331. )
  4332. except Exception as e:
  4333. logging.getLogger(__name__).warning("[PLATE CHECK] Could not announce the failed check: %s", e)
  4334. def _expected_print_keys(printer_id: int, filename: str | None, subtask_name: str | None) -> list[tuple[int, str]]:
  4335. """The ``_expected_prints`` keys a print start may be registered under."""
  4336. keys: list[tuple[int, str]] = []
  4337. if subtask_name:
  4338. keys.append((printer_id, subtask_name))
  4339. keys.append((printer_id, f"{subtask_name}.3mf"))
  4340. keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  4341. if filename:
  4342. fname = filename.split("/")[-1] if "/" in filename else filename
  4343. keys.append((printer_id, fname))
  4344. # Strip extensions to match
  4345. base = fname.replace(".gcode", "").replace(".3mf", "")
  4346. keys.append((printer_id, base))
  4347. keys.append((printer_id, f"{base}.3mf"))
  4348. return keys
  4349. async def _dispatched_by_bambuddy(db, printer_id: int, filename: str | None, subtask_name: str | None) -> bool:
  4350. """Whether this print start is one Bambuddy sent to the printer."""
  4351. if any(key in _expected_prints for key in _expected_print_keys(printer_id, filename, subtask_name)):
  4352. return True
  4353. from backend.app.models.archive import PrintArchive
  4354. from backend.app.models.print_queue import PrintQueueItem
  4355. # The queue row the scheduler sets to printing before it sends -- but only
  4356. # when it was sent as this print: a row left printing by a run whose end
  4357. # was missed names another file.
  4358. dispatched_names = (
  4359. await db.execute(
  4360. select(PrintArchive.filename)
  4361. .join(PrintQueueItem, PrintQueueItem.archive_id == PrintArchive.id)
  4362. .where(PrintQueueItem.printer_id == printer_id, PrintQueueItem.status == "printing")
  4363. )
  4364. ).scalars()
  4365. observed = [name for name in (subtask_name, (filename or "").rsplit("/", 1)[-1]) if name]
  4366. return any(
  4367. _subtask_names_match(_subtask_name_from_filename(dispatched), _subtask_name_from_filename(seen))
  4368. for dispatched in dispatched_names
  4369. if dispatched
  4370. for seen in observed
  4371. )
  4372. async def on_print_start(printer_id: int, data: dict):
  4373. """Handle print start - archive the 3MF file immediately."""
  4374. logger = logging.getLogger(__name__)
  4375. # The print's start, before the 3MF download that the archive waits for
  4376. # (#3327): a minute of it would otherwise be missing from the print time.
  4377. detected_at = datetime.now(timezone.utc)
  4378. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  4379. try:
  4380. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  4381. except Exception:
  4382. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  4383. # Clear any stale user-stopped flag from previous print cycles
  4384. _user_stopped_printers.discard(printer_id)
  4385. _kill_switch_stopped.discard(printer_id)
  4386. # A new print starts its milestones from zero (#3211). The status path only
  4387. # resets on progress below 5 while not printing, which a printer that goes
  4388. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  4389. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  4390. # or on resume from pause, so it cannot repeat a milestone mid-print.
  4391. _last_progress_milestone[printer_id] = 0
  4392. _kill_switch_notification_tasks.pop(printer_id, None)
  4393. # #1721: drop any leftover pre-captured finish frame from a prior print
  4394. # so a never-consumed cache entry can't bleed into the new print's photo.
  4395. _stage22_finish_frames.pop(printer_id, None)
  4396. # #1867: same for the in-print frame bank — a queued print must not reuse
  4397. # the previous job's banked frame.
  4398. _inprint_frame_bank.pop(printer_id, None)
  4399. _inprint_frame_bank_ts.pop(printer_id, None)
  4400. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  4401. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  4402. # print's flag instead of inheriting it.
  4403. print_dispatch_context.adopt(printer_id)
  4404. # Cancel any active bed cooldown waiter for this printer
  4405. if _bed_cool_waiters.pop(printer_id, None):
  4406. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  4407. # Clear cached cover images so the new print's thumbnail is fetched fresh
  4408. from backend.app.api.routes.printers import clear_cover_cache
  4409. clear_cover_cache(printer_id)
  4410. await ws_manager.send_print_start(printer_id, data)
  4411. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  4412. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  4413. # MQTT relay - publish print start
  4414. try:
  4415. printer_info = printer_manager.get_printer(printer_id)
  4416. if printer_info:
  4417. await mqtt_relay.on_print_start(
  4418. printer_id,
  4419. printer_info.name,
  4420. printer_info.serial_number,
  4421. data.get("filename", ""),
  4422. data.get("subtask_name", ""),
  4423. )
  4424. except Exception:
  4425. pass # Don't fail print start callback if MQTT fails
  4426. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  4427. # and mapping, and the seeded tray-change log.
  4428. #
  4429. # Unconditional, for both inventory backends. This only *captures* — the
  4430. # writing is still split, with the internal tracker skipped at completion
  4431. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  4432. # carries its plate-scoped 3MF figures and stored mapping, but not the
  4433. # tray-change log, and that log is the only record of which spool fed
  4434. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  4435. # it on one side only would leave Spoolman users with the mid-print
  4436. # restart bug this fixes for everyone else.
  4437. try:
  4438. async with async_session() as db:
  4439. from backend.app.api.routes.settings import get_setting
  4440. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  4441. _spoolman_on = await get_setting(db, "spoolman_enabled")
  4442. await usage_on_print_start(
  4443. printer_id,
  4444. data,
  4445. printer_manager,
  4446. db=db,
  4447. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  4448. )
  4449. except Exception as e:
  4450. logger.warning("Usage tracker on_print_start failed: %s", e)
  4451. # Track if notification was sent (to avoid sending twice)
  4452. notification_sent = False
  4453. # Smart plug automation: turn on plug when print starts
  4454. try:
  4455. async with async_session() as db:
  4456. await smart_plug_manager.on_print_start(printer_id, db)
  4457. except Exception as e:
  4458. logger.warning("Smart plug on_print_start failed: %s", e)
  4459. async with async_session() as db:
  4460. from backend.app.models.printer import Printer
  4461. from backend.app.services.bambu_ftp import list_files_async
  4462. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4463. printer = result.scalar_one_or_none()
  4464. # Plate detection check - pause if objects detected on build plate
  4465. logger.info(
  4466. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  4467. )
  4468. if printer and printer.plate_detection_enabled:
  4469. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  4470. # Release the pooled DB connection before the plate-detection camera
  4471. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  4472. # printer SELECT has run so far — nothing to persist — so this commit
  4473. # is a data-noop that ends the read transaction and returns the
  4474. # connection to the pool during the I/O (issue #2572). expire_on_commit
  4475. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  4476. # archive lookups below re-acquire a fresh connection on next execute.
  4477. await db.commit()
  4478. try:
  4479. from backend.app.services.plate_detection import check_plate_empty
  4480. # Build ROI tuple from printer settings if available
  4481. roi = None
  4482. if all(
  4483. [
  4484. printer.plate_detection_roi_x is not None,
  4485. printer.plate_detection_roi_y is not None,
  4486. printer.plate_detection_roi_w is not None,
  4487. printer.plate_detection_roi_h is not None,
  4488. ]
  4489. ):
  4490. roi = (
  4491. printer.plate_detection_roi_x,
  4492. printer.plate_detection_roi_y,
  4493. printer.plate_detection_roi_w,
  4494. printer.plate_detection_roi_h,
  4495. )
  4496. # The light is held, not switched, so a live view opened
  4497. # meanwhile keeps it when the check lets go (SP-C11). Every
  4498. # printer, whatever the camera light mode: detection needs it.
  4499. plate_photo_data = None
  4500. objects_detected = False
  4501. check_failure: str | None = None
  4502. async with camera_light(printer, any_mode=True, settle=2.5):
  4503. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  4504. plate_result = await check_plate_empty(
  4505. printer_id=printer_id,
  4506. ip_address=printer.ip_address,
  4507. access_code=printer.access_code,
  4508. model=printer.model,
  4509. include_debug_image=False,
  4510. external_camera_url=printer.external_camera_url,
  4511. external_camera_type=printer.external_camera_type,
  4512. use_external=printer.external_camera_enabled,
  4513. roi=roi,
  4514. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  4515. )
  4516. # No reference to compare against is a check that did not
  4517. # run either: say so rather than call the plate empty.
  4518. check_failure = getattr(plate_result, "failure_reason", None) or (
  4519. "not_calibrated" if plate_result.needs_calibration else None
  4520. )
  4521. objects_detected = not check_failure and not plate_result.is_empty
  4522. if objects_detected:
  4523. # Objects detected - pause the print!
  4524. logger.warning(
  4525. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  4526. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  4527. )
  4528. pause_client = printer_manager.get_client(printer_id)
  4529. if pause_client:
  4530. pause_client.pause_print()
  4531. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  4532. # Snapshot while the light's still on — restoring it first
  4533. # would leave the notification with a dark photo.
  4534. try:
  4535. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  4536. except Exception as snap_err:
  4537. logger.warning(
  4538. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  4539. )
  4540. if objects_detected:
  4541. # Send notification about plate not empty
  4542. await ws_manager.broadcast(
  4543. {
  4544. "type": "plate_not_empty",
  4545. "printer_id": printer_id,
  4546. "printer_name": printer.name,
  4547. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  4548. }
  4549. )
  4550. # Also send push notification
  4551. try:
  4552. await notification_service.on_plate_not_empty(
  4553. printer_id=printer_id,
  4554. printer_name=printer.name,
  4555. db=db,
  4556. difference_percent=plate_result.difference_percent,
  4557. image_data=plate_photo_data,
  4558. )
  4559. except Exception as notif_err:
  4560. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  4561. elif check_failure:
  4562. logger.warning(
  4563. "[PLATE CHECK] Plate check could not run for printer %s (%s): %s; proceeding with print",
  4564. printer_id,
  4565. check_failure,
  4566. plate_result.message,
  4567. )
  4568. await _announce_plate_check_failed(printer_id, printer.name, check_failure)
  4569. else:
  4570. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  4571. except Exception as plate_err:
  4572. # Don't block print on plate detection errors
  4573. logger.warning(
  4574. "[PLATE CHECK] Plate check could not run for printer %s: %s; proceeding with print",
  4575. printer_id,
  4576. plate_err,
  4577. )
  4578. await _announce_plate_check_failed(printer_id, printer.name, "error")
  4579. if not printer:
  4580. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  4581. if not notification_sent:
  4582. await _send_print_start_notification(printer_id, data, logger=logger)
  4583. return
  4584. # Skip the printer's own jobs — a calibration run is not a user's print.
  4585. # See is_internal_printer_job for what counts and why both fields are
  4586. # tested; the pressure-advance line reports as a subtask name with no
  4587. # /usr/ path, which the old prefix-only test here missed entirely.
  4588. #
  4589. # No notification either. The event describes the printer calibrating
  4590. # itself, so "Print started" is as wrong as the archive was, and the
  4591. # matching completion is suppressed in on_print_complete for the same
  4592. # reason. Checked before the auto-archive switches, whose "off" path
  4593. # still notifies.
  4594. # A /usr/ path is the printer's own file. A name alone is not proof: a
  4595. # print Bambuddy dispatched is never one, whatever it is called.
  4596. # Dispatched = an expected print, or, after a restart that lost those,
  4597. # a queue job printing on the printer.
  4598. if is_internal_printer_job(data.get("filename", ""), data.get("subtask_name", "")) and (
  4599. (data.get("filename") or "").startswith("/usr/")
  4600. or not await _dispatched_by_bambuddy(db, printer_id, data.get("filename", ""), data.get("subtask_name", ""))
  4601. ):
  4602. logger.info(
  4603. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4604. data.get("filename", ""),
  4605. data.get("subtask_name", ""),
  4606. )
  4607. return
  4608. # The global switch is the master: off, no printer archives prints
  4609. # started outside Bambuddy; on, each printer's own switch decides.
  4610. from backend.app.api.routes.settings import get_setting
  4611. _global_auto_archive = await get_setting(db, "auto_archive")
  4612. archives_prints = printer.auto_archive and (
  4613. _global_auto_archive is None or _global_auto_archive.lower() == "true"
  4614. )
  4615. if not archives_prints:
  4616. # auto-archive disabled — check if there's an expected print (dispatched
  4617. # by BamBuddy via queue/reprint) that already has an archive to promote.
  4618. # If so, fall through to the expected-print handling below so the archive
  4619. # is tracked in _active_prints and usage tracking works at completion.
  4620. _fn = data.get("filename", "")
  4621. _sn = data.get("subtask_name", "")
  4622. _check_keys: list[tuple[int, str]] = []
  4623. if _sn:
  4624. _check_keys += [
  4625. (printer_id, _sn),
  4626. (printer_id, f"{_sn}.3mf"),
  4627. (printer_id, f"{_sn}.gcode.3mf"),
  4628. ]
  4629. if _fn:
  4630. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4631. _check_keys.append((printer_id, _base_fn))
  4632. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4633. _check_keys += [
  4634. (printer_id, _no_archive_base),
  4635. (printer_id, f"{_no_archive_base}.3mf"),
  4636. ]
  4637. _has_expected = any(k in _expected_prints for k in _check_keys)
  4638. if not _has_expected:
  4639. # No expected print — truly external print (started from slicer/touchscreen)
  4640. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  4641. if not notification_sent:
  4642. _no_archive_creator: int | None = None
  4643. for _key in _check_keys:
  4644. _expected_prints.pop(_key, None)
  4645. _expected_print_registered_at.pop(_key, None)
  4646. popped_creator = _expected_print_creators.pop(_key, None)
  4647. if _no_archive_creator is None:
  4648. _no_archive_creator = popped_creator
  4649. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4650. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4651. return
  4652. else:
  4653. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4654. # Get the filename and subtask_name
  4655. filename = data.get("filename", "")
  4656. subtask_name = data.get("subtask_name", "")
  4657. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4658. # present, it lets us match an archive across a backend restart (#972):
  4659. # same id → same print → resume the existing row instead of cancelling
  4660. # it and recreating from scratch (which loses started_at). Treat "0"
  4661. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4662. raw_mqtt = data.get("raw_data") or {}
  4663. subtask_id = raw_mqtt.get("subtask_id")
  4664. if subtask_id is not None:
  4665. subtask_id = str(subtask_id).strip()
  4666. if subtask_id in ("", "0"):
  4667. subtask_id = None
  4668. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4669. if not filename and not subtask_name:
  4670. # Send notification without archive data (no filename)
  4671. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4672. if not notification_sent:
  4673. await _send_print_start_notification(printer_id, data, logger=logger)
  4674. return
  4675. # Check if this is an expected print from reprint/scheduled
  4676. expected_keys = _expected_print_keys(printer_id, filename, subtask_name)
  4677. expected_archive_id = None
  4678. # Who queued it, taken with the entries it was registered beside: left
  4679. # behind once those are gone (the archive deleted mid-dispatch, or the
  4680. # start notification already sent), the expiry never saw it, and an
  4681. # unrelated later print of that name was attributed to that user (EP-2).
  4682. fallback_creator = None
  4683. for key in expected_keys:
  4684. expected_archive_id = _expected_prints.pop(key, None)
  4685. _expected_print_registered_at.pop(key, None)
  4686. if expected_archive_id:
  4687. # Clean up other possible keys for this print
  4688. for other_key in expected_keys:
  4689. _expected_prints.pop(other_key, None)
  4690. _expected_print_registered_at.pop(other_key, None)
  4691. creator = _expected_print_creators.pop(other_key, None)
  4692. if fallback_creator is None:
  4693. fallback_creator = creator
  4694. break
  4695. if expected_archive_id:
  4696. # This is a reprint/scheduled print - use existing archive, don't create new one
  4697. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4698. # Bambuddy dispatched it: the kill switch's fast path keeps it as
  4699. # Bambuddy's once the expected entry is consumed here.
  4700. _owned_print_archive_ids.add(expected_archive_id)
  4701. from backend.app.models.archive import PrintArchive
  4702. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4703. archive = result.scalar_one_or_none()
  4704. # Deleted after this handler loaded it (the plate check waits
  4705. # seconds) but before the route forgot the expected print: the
  4706. # archive the route kept or deleted is left as the route left it.
  4707. if archive and await _printer_gone(db, printer_id):
  4708. logger.info(
  4709. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4710. )
  4711. await forget_printer(printer_id)
  4712. return
  4713. if archive:
  4714. # As it was before this adoption: put back if the printer turns
  4715. # out to have been deleted while it was adopted (below).
  4716. before_adoption = {
  4717. attr.columns[0].name: getattr(archive, attr.key)
  4718. for attr in sa_inspect(PrintArchive).column_attrs
  4719. if attr.key != "id"
  4720. }
  4721. # Update archive status to printing
  4722. archive.status = "printing"
  4723. archive.started_at = datetime.now(timezone.utc)
  4724. # The previous run's outcome is not this one's: a reprint that
  4725. # completes must not keep showing why the last one failed.
  4726. archive.failure_reason = None
  4727. archive.completed_at = None
  4728. # The previous run's answer is still on this row and the
  4729. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4730. # so without a reset the second run inherits the first run's
  4731. # verdict: no prompt at all, and a green "good" badge on a run
  4732. # nobody ever judged.
  4733. if archive.confirm_requested:
  4734. archive.user_verdict = None
  4735. archive.user_verdict_source = None
  4736. archive.user_verdict_at = None
  4737. archive.confirm_token = None
  4738. archive.confirm_token_used_at = None
  4739. # Reprint of an archive reuses the source row. Without resetting
  4740. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4741. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4742. # extracts the *original* print's last frame, which then ships in
  4743. # the completion notification (#1707). Clear the path so the
  4744. # scanner runs fresh; also unlink the old video file so reprints
  4745. # don't accumulate orphans in the archive directory. Photos list
  4746. # is left alone — accumulating one finish photo per run is fine.
  4747. # The print-start baseline (#2704) is stale for the same reason:
  4748. # it describes the printer before the previous run. The capture
  4749. # below overwrites it, but clear it here too so an early failure
  4750. # can't leave the scan diffing against the wrong snapshot.
  4751. #
  4752. # Unlinked only when it is the same plate printing again. Every
  4753. # plate of a Send All shares this archive, and the video on it
  4754. # can be the only copy of another plate's run -- the printer's
  4755. # was deleted once it attached (#3275). That one is left in the
  4756. # archive directory, which goes with the archive. A video whose
  4757. # plate is not on record (attached by hand, or before the
  4758. # column existed) is kept too where the 3MF has other plates,
  4759. # or cannot be read: nothing tells it apart from another plate's,
  4760. # and keeping costs one file where deleting can cost the only
  4761. # copy. On an archive with exactly one plate it is that plate's.
  4762. archive.timelapse_baseline = None
  4763. stale_timelapse_relpath = archive.timelapse_path
  4764. stale_timelapse_plate_id = archive.timelapse_plate_id
  4765. starting_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4766. if stale_timelapse_relpath:
  4767. archive.timelapse_path = None
  4768. archive.timelapse_plate_id = None
  4769. stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
  4770. if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
  4771. from backend.app.services.archive import plate_indexes_in_3mf
  4772. plates = await asyncio.to_thread(
  4773. plate_indexes_in_3mf,
  4774. app_settings.base_dir / archive.file_path, # SEC-PATH-OK: stored relative archive path
  4775. )
  4776. stale_is_this_plates = len(plates) == 1
  4777. if stale_timelapse_relpath and not stale_is_this_plates:
  4778. logger.info(
  4779. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4780. stale_timelapse_relpath,
  4781. stale_timelapse_plate_id,
  4782. expected_archive_id,
  4783. starting_plate_id,
  4784. )
  4785. # The video is deleted once the adoption stands (below).
  4786. delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
  4787. # Persist a restart-stable id so a later restart resumes this
  4788. # archive by subtask_id instead of name-matching + duplicating
  4789. # it (#1485). The printer often hasn't echoed subtask_id back
  4790. # this soon after dispatch, so fall back to the id Bambuddy
  4791. # minted when it sent the print command. Scoped to this
  4792. # expected-print branch on purpose: an expected match means
  4793. # Bambuddy dispatched this exact print in this process, so the
  4794. # client's last-dispatch id genuinely belongs to it — using it
  4795. # for an externally-started print could mis-tag the archive.
  4796. effective_subtask_id = subtask_id
  4797. if not effective_subtask_id:
  4798. _client = printer_manager.get_client(printer_id)
  4799. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4800. if _dispatched:
  4801. effective_subtask_id = str(_dispatched).strip() or None
  4802. # Update on first-set OR on reprint (the queue dispatcher mints
  4803. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4804. # the rewrite for reprints leaves the archive holding the FIRST
  4805. # run's id; if MQTT then reconnects mid-print, the reconciler
  4806. # (#1542) compares the stale stored id against the printer's
  4807. # live id, sees a mismatch, and synthesises a bogus PRINT
  4808. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4809. # in #1807. Inequality check preserves the noop-on-stable-push
  4810. # behaviour the earlier `not archive.subtask_id` guard provided.
  4811. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4812. archive.subtask_id = effective_subtask_id
  4813. # #1403 follow-up: VP-queue archives are created with
  4814. # printer_id=None at queue-add time (we don't know which
  4815. # printer will run the job yet). When the print actually
  4816. # starts on a specific printer the expected-archive lookup
  4817. # used to skip this assignment, leaving printer_id=None
  4818. # forever — which then disables the "Scan for timelapse"
  4819. # button in ArchivesPage (gated on !archive.printer_id).
  4820. if archive.printer_id != printer_id:
  4821. archive.printer_id = printer_id
  4822. adopting_id = archive.id # a rollback expires the object
  4823. try:
  4824. await db.commit()
  4825. except (IntegrityError, StaleDataError):
  4826. # The archive stays unchanged, or is gone: "delete archives"
  4827. # removed the row under the adoption, which then matched no
  4828. # row (StaleDataError) rather than being refused.
  4829. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4830. return
  4831. raise
  4832. # The printer can be deleted between the check above and this
  4833. # commit (the route's transaction lasts seconds), and the commit
  4834. # then adopted the archive anyway: status, verdict and timelapse
  4835. # changed, and the deleted printer's id written on a row the
  4836. # route had detached or never touched. Undo the adoption.
  4837. if await _printer_gone(db, printer_id):
  4838. logger.info(
  4839. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4840. printer_id,
  4841. archive.id,
  4842. )
  4843. # Everything as before this adoption. The printer it had
  4844. # then stays, unless it was the deleted one: the route
  4845. # detached that row (kept) or deleted it (no row matches).
  4846. previous_printer = before_adoption["printer_id"]
  4847. await db.execute(
  4848. update(PrintArchive)
  4849. .where(PrintArchive.id == archive.id)
  4850. .values(
  4851. {
  4852. **before_adoption,
  4853. "printer_id": None if previous_printer == printer_id else previous_printer,
  4854. }
  4855. )
  4856. )
  4857. await db.commit()
  4858. await forget_printer(printer_id)
  4859. return
  4860. await _drop_replaced_plate_videos(
  4861. db,
  4862. archive.id,
  4863. starting_plate_id,
  4864. stale_timelapse_relpath if delete_stale_video else None,
  4865. logger,
  4866. )
  4867. # Track as active print
  4868. _bind_active_print(printer_id, archive.id, archive.filename, filename, subtask_name)
  4869. await _open_run_for(archive.id, printer_id, subtask_id)
  4870. # Start timelapse session if external camera is enabled (#1353).
  4871. # Queue / VP-dispatched prints land here in the expected-archive
  4872. # branch and used to skip start_session entirely — frames were
  4873. # never captured and the post-print stitch silently returned None.
  4874. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4875. # Inject ams_mapping into usage tracker session — the session was created
  4876. # before expected-print promotion, so it may have ams_mapping=None when
  4877. # the MQTT request topic subscription failed (common on P1S/A1).
  4878. _stored_map = _print_ams_mappings.get((printer_id, expected_archive_id))
  4879. _stored_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4880. if _stored_map or _stored_plate_id is not None:
  4881. try:
  4882. from backend.app.services.usage_tracker import _active_sessions
  4883. _ut_session = _active_sessions.get(printer_id)
  4884. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4885. _ut_session.ams_mapping = _stored_map
  4886. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4887. # plate_id injection covers direct-Print of plate N of a multi-plate
  4888. # 3MF — queue prints already capture it via the on_print_start queue
  4889. # lookup, but direct-Print never goes through the queue (#1697).
  4890. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4891. _ut_session.plate_id = _stored_plate_id
  4892. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4893. except Exception:
  4894. pass
  4895. # Set up energy tracking (#941: persist start on archive row)
  4896. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4897. await ws_manager.send_archive_updated(
  4898. {
  4899. "id": archive.id,
  4900. "status": "printing",
  4901. }
  4902. )
  4903. # Send notification with archive data (reprint/scheduled)
  4904. if not notification_sent:
  4905. # Use archive's created_by_id; fall back to the creator registered via
  4906. # register_expected_print (handles library-file-based queue items where
  4907. # the freshly-created archive has no created_by_id yet), taken above.
  4908. archive_data = {
  4909. "print_time_seconds": _run_print_time_seconds(archive, printer_id),
  4910. "created_by_id": archive.created_by_id or fallback_creator,
  4911. }
  4912. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4913. # Extract printable objects from the archived 3MF file
  4914. _load_objects_from_archive(archive, printer_id, logger)
  4915. if archive.file_path:
  4916. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  4917. # Store Spoolman tracking data for per-filament usage reporting
  4918. try:
  4919. await _store_spoolman_print_data(
  4920. printer_id,
  4921. archive.id,
  4922. archive.file_path,
  4923. db,
  4924. printer_manager,
  4925. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4926. plate_id=_get_start_plate_id(printer_id, archive.id),
  4927. )
  4928. except Exception as e:
  4929. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4930. # Price the print from its spools now rather than only at completion (#3261)
  4931. _schedule_archive_cost_estimate(
  4932. printer_id,
  4933. archive.id,
  4934. printer_manager,
  4935. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4936. plate_id=_get_start_plate_id(printer_id, archive.id),
  4937. session_factory=async_session,
  4938. )
  4939. # Capture timelapse file baseline for snapshot-diff on completion
  4940. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4941. # hit this branch — without the baseline the completion-time scan
  4942. # falls into its "take baseline now" fallback, which snapshots
  4943. # AFTER the new MP4 already exists and never matches a diff
  4944. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4945. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4946. await _forget_if_printer_gone(printer_id)
  4947. return # Skip creating a new archive
  4948. # The archive was deleted after the job was queued.
  4949. if not archives_prints:
  4950. # Only the expected print brought a printer that does not
  4951. # archive this far; with it gone, nothing is archived.
  4952. return
  4953. # Otherwise archive the print anew rather than drop it, so it still
  4954. # gets its notification, usage tracking and history.
  4955. logger.warning(
  4956. "Expected archive %s for printer %s no longer exists; archiving the print anew",
  4957. expected_archive_id,
  4958. printer_id,
  4959. )
  4960. # Check if there's already a "printing" archive for this printer/file
  4961. # This prevents duplicates when backend restarts during an active print
  4962. from backend.app.models.archive import PrintArchive
  4963. existing_archive: PrintArchive | None = None
  4964. resumed_by_run = False
  4965. # Best match: this job's run, open on the printer since the print
  4966. # started. The archive row is shared by every plate of it, and its
  4967. # printer, job id and status are the latest start's, which may be
  4968. # another printer's.
  4969. if subtask_id:
  4970. from backend.app.services.print_log import open_run_on_printer
  4971. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  4972. if run is not None and run.archive_id is not None:
  4973. existing_archive = await db.scalar(
  4974. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  4975. )
  4976. resumed_by_run = existing_archive is not None
  4977. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4978. # across a backend restart for the same print, so this is the most
  4979. # reliable way to reattach. Only a row still printing: a cancelled one
  4980. # has been through completion (usage, history, notifications) already,
  4981. # and reopening it would count the print twice.
  4982. if subtask_id and existing_archive is None:
  4983. by_id = await db.execute(
  4984. select(PrintArchive)
  4985. .where(PrintArchive.printer_id == printer_id)
  4986. .where(PrintArchive.subtask_id == subtask_id)
  4987. .where(PrintArchive.status == "printing")
  4988. .order_by(PrintArchive.created_at.desc())
  4989. .limit(1)
  4990. )
  4991. existing_archive = by_id.scalar_one_or_none()
  4992. # Fallback match: name-based lookup. Kept as-is for prints whose
  4993. # subtask_id is missing ("0" / local / non-cloud prints).
  4994. if existing_archive is None:
  4995. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4996. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4997. # A print started from the printer's screen names its file in full,
  4998. # so the forms above double its extension. The file itself is the
  4999. # one exact match, and nothing looser is added (#3009).
  5000. if _subtask_is_the_file(subtask_name, filename):
  5001. archive_filenames.append(subtask_name)
  5002. existing = await db.execute(
  5003. select(PrintArchive)
  5004. .where(PrintArchive.printer_id == printer_id)
  5005. .where(PrintArchive.status == "printing")
  5006. .where(
  5007. or_(
  5008. PrintArchive.print_name == check_name,
  5009. PrintArchive.filename.in_(archive_filenames),
  5010. )
  5011. )
  5012. .order_by(PrintArchive.created_at.desc())
  5013. .limit(1)
  5014. )
  5015. existing_archive = existing.scalar_one_or_none()
  5016. if existing_archive:
  5017. # subtask_id match → always resume, regardless of age. Same print,
  5018. # just a backend restart.
  5019. subtask_match = resumed_by_run or bool(subtask_id and existing_archive.subtask_id == subtask_id)
  5020. if subtask_match:
  5021. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  5022. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  5023. await _open_run_for(existing_archive.id, printer_id, subtask_id)
  5024. _mark_owned_if_dispatched(existing_archive)
  5025. if await _run_needs_energy_start(existing_archive, printer_id, db):
  5026. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  5027. if not notification_sent:
  5028. archive_data = {
  5029. "print_time_seconds": _run_print_time_seconds(existing_archive, printer_id),
  5030. "created_by_id": existing_archive.created_by_id,
  5031. }
  5032. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5033. _load_objects_from_archive(existing_archive, printer_id, logger)
  5034. if existing_archive.file_path:
  5035. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  5036. return
  5037. # Name-match only (no subtask_id to anchor on): decide resume vs.
  5038. # stale from the printer's *current* progress, not wall-clock age.
  5039. # A genuinely long print used to trip a blind 4h cutoff and have its
  5040. # live archive cancelled + duplicated on every backend restart
  5041. # (#1485). If the printer reports real progress, this name-matched
  5042. # 'printing' archive IS that ongoing print — resume it whatever its
  5043. # age. Only treat it as a stale leftover when the printer clearly
  5044. # shows a different, freshly-started print: near-0% progress on an
  5045. # archive far too old to still be at 0%. Unknown progress (printer
  5046. # not connected) never cancels — resuming is the safe default.
  5047. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  5048. live_status = printer_manager.get_status(printer_id)
  5049. live_progress = getattr(live_status, "progress", None) if live_status else None
  5050. looks_stale = (
  5051. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  5052. )
  5053. # Two subtask ids are two prints, however young the archive: one
  5054. # whose completion was missed must not swallow the next print of
  5055. # the same file. Except Bambuddy's own reprint, which reuses the
  5056. # row and mints a fresh id (#1807): the id it last sent says so,
  5057. # and after a restart, which forgets it, this printer's queue job
  5058. # running the archive.
  5059. if (
  5060. not looks_stale
  5061. and subtask_id
  5062. and existing_archive.subtask_id
  5063. and existing_archive.subtask_id != subtask_id
  5064. ):
  5065. _client = printer_manager.get_client(printer_id)
  5066. _dispatched = str(getattr(_client, "last_dispatch_subtask_id", None) or "").strip()
  5067. if _dispatched:
  5068. looks_stale = _dispatched != subtask_id
  5069. else:
  5070. from backend.app.models.print_queue import PrintQueueItem as _PQI
  5071. queue_run = await db.scalar(
  5072. select(_PQI.id)
  5073. .where(_PQI.archive_id == existing_archive.id)
  5074. .where(_PQI.printer_id == printer_id)
  5075. .where(_PQI.status == "printing")
  5076. .limit(1)
  5077. )
  5078. looks_stale = queue_run is None
  5079. if looks_stale:
  5080. logger.warning(
  5081. "Found stale 'printing' archive %s (age: %s, printer progress %s%%, subtask %s, printer reports %s)"
  5082. " — marking cancelled and creating new archive",
  5083. existing_archive.id,
  5084. archive_age,
  5085. live_progress,
  5086. existing_archive.subtask_id,
  5087. subtask_id,
  5088. )
  5089. existing_archive.status = "cancelled"
  5090. # Canonical key, not a sentence (issue #2974). "No status update
  5091. # received" is what both stale paths actually observed; which of
  5092. # the two it was is already carried by ``status`` -- cancelled
  5093. # here, the reconciled outcome at the reconnect site -- so one
  5094. # key loses no information and gives the Statistics breakdown a
  5095. # single bucket instead of two untranslatable prose strings.
  5096. existing_archive.failure_reason = "noStatusUpdate"
  5097. # And its run, as before runs were opened at the start: a new
  5098. # print starts on the printer, so whatever is open there ended
  5099. # unseen. Left open, the next reconnect would close it again.
  5100. from backend.app.services.print_log import discard_open_runs
  5101. discarded = await discard_open_runs(db, printer_id)
  5102. await db.commit()
  5103. await _announce_discarded_runs(discarded, printer_id)
  5104. # Its print keys go with it; the new archive registers its own.
  5105. for _key in [k for k, v in _active_prints.items() if v == existing_archive.id and k[0] == printer_id]:
  5106. del _active_prints[_key]
  5107. # Fall through to create new archive (don't return)
  5108. else:
  5109. logger.info(
  5110. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  5111. )
  5112. # Track this as the active print
  5113. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  5114. _mark_owned_if_dispatched(existing_archive)
  5115. # Attach subtask_id retroactively so future restarts can resume.
  5116. # Compare for inequality (not "is empty") to also pick up reprint
  5117. # dispatches that mint a fresh id — see #1807 for the bogus
  5118. # "Print Stopped" the strict-empty guard caused on reconnect.
  5119. if subtask_id and existing_archive.subtask_id != subtask_id:
  5120. existing_archive.subtask_id = subtask_id
  5121. await db.commit()
  5122. await _open_run_for(existing_archive.id, printer_id, subtask_id)
  5123. # Also set up energy tracking if not already tracked (#941: persisted column)
  5124. if await _run_needs_energy_start(existing_archive, printer_id, db):
  5125. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  5126. # Send notification with archive data (existing archive)
  5127. if not notification_sent:
  5128. archive_data = {
  5129. "print_time_seconds": _run_print_time_seconds(existing_archive, printer_id),
  5130. "created_by_id": existing_archive.created_by_id,
  5131. }
  5132. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5133. # Extract printable objects from the archived 3MF file
  5134. _load_objects_from_archive(existing_archive, printer_id, logger)
  5135. if existing_archive.file_path:
  5136. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  5137. return
  5138. # Build list of possible 3MF filenames to try
  5139. possible_names = []
  5140. # Bambu printers typically store files as "Name.gcode.3mf"
  5141. # The subtask_name is usually the best source for the filename
  5142. if subtask_name:
  5143. if _subtask_is_the_file(subtask_name, filename):
  5144. # A print started from the printer's own screen reports the
  5145. # file's full name, extension included. That is the file, so
  5146. # no extension is appended to it (#3009).
  5147. possible_names.append(subtask_name)
  5148. else:
  5149. # Try common Bambu naming patterns
  5150. possible_names.append(f"{subtask_name}.gcode.3mf")
  5151. possible_names.append(f"{subtask_name}.3mf")
  5152. # Try original filename with .3mf extension
  5153. if filename:
  5154. # Extract just the filename part, not the full path
  5155. fname = filename.split("/")[-1] if "/" in filename else filename
  5156. if fname.endswith(".3mf"):
  5157. possible_names.append(fname)
  5158. elif fname.endswith(".gcode"):
  5159. base = fname.rsplit(".", 1)[0]
  5160. possible_names.append(f"{base}.gcode.3mf")
  5161. possible_names.append(f"{base}.3mf")
  5162. else:
  5163. possible_names.append(f"{fname}.gcode.3mf")
  5164. possible_names.append(f"{fname}.3mf")
  5165. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  5166. space_variants = []
  5167. for name in possible_names:
  5168. if " " in name:
  5169. space_variants.append(name.replace(" ", "_"))
  5170. possible_names.extend(space_variants)
  5171. # Remove duplicates while preserving order
  5172. seen = set()
  5173. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  5174. logger.info("Trying filenames: %s", possible_names)
  5175. # Release the pooled DB connection before the 3MF FTP download. Reaching
  5176. # here means none of the expected-/existing-archive write branches ran
  5177. # (they all return earlier) — only SELECTs have executed on this path, so
  5178. # this commit persists nothing; it ends the read transaction so the
  5179. # connection returns to the pool during the download. That download tries
  5180. # up to five remote paths per candidate filename with retry/backoff and
  5181. # can run for minutes under FTP contention; holding the session across it
  5182. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  5183. # work runs during the download — the new-archive writes below re-acquire
  5184. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  5185. await db.commit()
  5186. # Try to find and download the 3MF file
  5187. temp_path = None
  5188. downloaded_filename = None
  5189. # Cache check: cover endpoint may have already pulled this 3MF during
  5190. # the print (frontend opens the card and shows the thumbnail) — reuse
  5191. # that file instead of re-downloading 36MB over the same FTP link that
  5192. # just served it (#972). The cache keys on a normalized filename so
  5193. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  5194. for try_filename in possible_names:
  5195. if not try_filename.endswith(".3mf"):
  5196. continue
  5197. cached = get_cached_3mf(printer_id, try_filename)
  5198. if cached:
  5199. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  5200. temp_path = cached
  5201. downloaded_filename = try_filename
  5202. break
  5203. # Does this printer keep the sliced file somewhere FTPS can reach? On
  5204. # H2-series and P2S the answer is routinely no — the file stays on
  5205. # internal eMMC and port 990 only ever serves external storage — and
  5206. # then the whole sweep below (six filenames x five directories x four
  5207. # retries, then the directory walk) is ~110 connections that cannot
  5208. # succeed. Skip it and say why (#2780).
  5209. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  5210. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  5211. # running rather than because the file is somewhere unreachable. The
  5212. # distinction is the whole of #2957: one is permanent, the other clears
  5213. # in minutes with the file still sitting on the printer.
  5214. blocked_by_ftps_cooloff = False
  5215. # Set when a probe reached the printer and still came back without the
  5216. # file -- a timeout mid-transfer, a refused connection, anything that is
  5217. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  5218. # caught by name below, so a file that genuinely is not on the card
  5219. # leaves this False and schedules nothing. Anything else means the
  5220. # transfer, not the file, is what failed, and that does not last (#3063).
  5221. ftp_transfer_failed = False
  5222. # The narrower case of the above: the directory walk *listed* a file
  5223. # for this print and could not fetch it, so the file is on the card
  5224. # under a name that matches. The only failure that rules out an
  5225. # earlier run's 3MF standing in for it (#3307).
  5226. walk_transfer_failed = False
  5227. # Paths the sweep reached and could not transfer -- a timeout, not a
  5228. # 550. The directory walk lists the same folders and would download
  5229. # the same file again: on a slow A1 that was a second 300 s on the
  5230. # printer's one FTPS slot, at print start, for a file the recovery
  5231. # retry fetches with a deadline twice as long (#3308).
  5232. sweep_failed_paths: set[str] = set()
  5233. # The print's name, for a fallback archive whose `subtask_name` the
  5234. # plate guard below had to disown. Display only, and deliberately kept
  5235. # apart from `subtask_name`: that variable is what every file lookup
  5236. # here is built from, and once a name has been shown to fetch another
  5237. # plate's 3MF it must not key `_active_prints` either, or the cover
  5238. # endpoint hands the same contradicted file to
  5239. # `_recover_fallback_archive` and fills the row in with it (#3126).
  5240. display_name_after_plate_reject: str | None = None
  5241. # Get FTP retry settings
  5242. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  5243. # ...but "the printer put it on eMMC" is where it went, not whether we
  5244. # can read it. An H2D with a card in mirrors the job to /cache and
  5245. # serves it happily, and skipping on the URL alone cost that reporter
  5246. # every archive for two days (#2856). So ask the printer instead of
  5247. # guessing: the dispatch named the exact file, which is one connection
  5248. # walking five paths rather than the sweep's ~110. Only when the probe
  5249. # comes back empty does the verdict's reason stand.
  5250. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  5251. if ftps_handshake_blocked(printer.ip_address):
  5252. # Deliberately NOT recorded as a cool-off give-up. This branch
  5253. # only runs on an unreachable verdict, and that verdict is the
  5254. # honest, permanent reason the archive is empty — the probe was
  5255. # a long shot on top of it. Blaming the cool-off here would
  5256. # schedule a retry for a file sitting on internal eMMC, which is
  5257. # the sweep #2780 removed (#2957).
  5258. logger.debug(
  5259. "Not probing for %s on printer %s: its file service is not answering over TLS",
  5260. storage.probe_filename,
  5261. printer_id,
  5262. )
  5263. else:
  5264. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  5265. probe_path.parent.mkdir(parents=True, exist_ok=True)
  5266. try:
  5267. probe_hit = await download_file_try_paths_async(
  5268. printer.ip_address,
  5269. printer.access_code,
  5270. ftp_probe_paths(storage.probe_filename),
  5271. probe_path,
  5272. socket_timeout=ftp_timeout,
  5273. printer_model=printer.model,
  5274. )
  5275. except Exception as e:
  5276. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  5277. probe_hit = False
  5278. if probe_hit:
  5279. downloaded_filename = storage.probe_filename
  5280. temp_path = probe_path
  5281. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  5282. # Naming the path, not just the file: a printer that keeps
  5283. # uploads around for weeks can serve a same-named copy of an
  5284. # earlier slice, and without the directory in the log that
  5285. # mismatch is invisible rather than merely rare (#1820).
  5286. logger.info(
  5287. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  5288. downloaded_filename,
  5289. probe_hit,
  5290. printer_id,
  5291. storage.reason,
  5292. )
  5293. if not storage.reachable and not downloaded_filename:
  5294. # Same opening words whether or not a probe ran, because that is
  5295. # the phrase support asks people to grep for — only the tail says
  5296. # which of the two happened.
  5297. logger.info(
  5298. "Skipping the 3MF lookup for printer %s: %s — %s",
  5299. printer_id,
  5300. storage.reason,
  5301. "no copy of it on external storage either"
  5302. if storage.probe_filename
  5303. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  5304. )
  5305. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  5306. if not try_filename.endswith(".3mf"):
  5307. continue
  5308. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  5309. # printers, so try it first — deferring it to last cost #972's reporter
  5310. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  5311. # landing on the path that actually had the file.
  5312. remote_paths = [
  5313. f"/{try_filename}",
  5314. f"/cache/{try_filename}",
  5315. f"/model/{try_filename}",
  5316. f"/data/{try_filename}",
  5317. f"/data/Metadata/{try_filename}",
  5318. ]
  5319. temp_path = app_settings.archive_dir / "temp" / try_filename
  5320. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5321. for remote_path in remote_paths:
  5322. if ftps_handshake_blocked(printer.ip_address):
  5323. # The printer's FTPS service is not completing a TLS
  5324. # handshake, so it has no path we could reach — walking the
  5325. # remaining candidates only re-runs the same failure
  5326. # (#2780). Fall through to the no-3MF archive now.
  5327. #
  5328. # Remember *why*, though. This is the one give-up that is
  5329. # temporary: the cool-off clears in minutes and the file was
  5330. # on the printer the whole time. The fallback archive is
  5331. # stamped with it so a retry can be scheduled, and so the
  5332. # Archives banner stops blaming storage (#2957).
  5333. blocked_by_ftps_cooloff = True
  5334. logger.warning(
  5335. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  5336. printer_id,
  5337. )
  5338. break
  5339. logger.debug("Trying FTP download: %s", remote_path)
  5340. try:
  5341. if ftp_retry_enabled:
  5342. downloaded = await with_ftp_retry(
  5343. download_file_async,
  5344. printer.ip_address,
  5345. printer.access_code,
  5346. remote_path,
  5347. temp_path,
  5348. timeout=ftp_timeout,
  5349. socket_timeout=ftp_timeout,
  5350. printer_model=printer.model,
  5351. max_retries=ftp_retry_count,
  5352. retry_delay=ftp_retry_delay,
  5353. operation_name=f"Download 3MF from {remote_path}",
  5354. cooloff_ip=printer.ip_address,
  5355. non_retry_exceptions=(FileNotOnPrinterError,),
  5356. )
  5357. else:
  5358. downloaded = await download_file_async(
  5359. printer.ip_address,
  5360. printer.access_code,
  5361. remote_path,
  5362. temp_path,
  5363. timeout=ftp_timeout,
  5364. socket_timeout=ftp_timeout,
  5365. printer_model=printer.model,
  5366. )
  5367. if downloaded:
  5368. downloaded_filename = try_filename
  5369. logger.info("Downloaded: %s", remote_path)
  5370. # Populate shared cache so the cover endpoint (if it
  5371. # runs next) doesn't refetch the same 36MB over FTP.
  5372. cache_3mf_download(printer_id, try_filename, temp_path)
  5373. break
  5374. # with_ftp_retry returns None once it has spent its budget,
  5375. # and download_file_async returns False on a timeout, so an
  5376. # exhausted transfer arrives here rather than as an
  5377. # exception (#3063).
  5378. ftp_transfer_failed = True
  5379. sweep_failed_paths.add(remote_path)
  5380. except FileNotOnPrinterError:
  5381. # 550 — file isn't at this path. Advance to next candidate
  5382. # without burning the retry budget.
  5383. logger.debug("3MF not at %s (550), trying next path", remote_path)
  5384. except Exception as e:
  5385. ftp_transfer_failed = True
  5386. sweep_failed_paths.add(remote_path)
  5387. logger.debug("FTP download failed for %s: %s", remote_path, e)
  5388. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  5389. break
  5390. # If still not found, try listing directories to find matching file
  5391. # Different printer models use different directory structures. Skipped
  5392. # when the printer's FTPS handshake is failing — the directory walk is
  5393. # five more connections that cannot get further than the download did.
  5394. if (
  5395. not downloaded_filename
  5396. and storage.reachable
  5397. and (filename or subtask_name)
  5398. and not ftps_handshake_blocked(printer.ip_address)
  5399. ):
  5400. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  5401. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  5402. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  5403. # Every folder is listed before one file is picked, so a file named
  5404. # for the print in a later folder wins over one that merely
  5405. # contains the name in an earlier folder.
  5406. listed_paths: list[str] = []
  5407. for search_dir in search_dirs:
  5408. try:
  5409. dir_files = await list_files_async(
  5410. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  5411. )
  5412. except Exception as e:
  5413. logger.debug("Failed to list %s: %s", search_dir, e)
  5414. continue
  5415. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  5416. if threemf_files:
  5417. logger.info(
  5418. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  5419. )
  5420. listed_paths += [
  5421. posixpath.join(search_dir, f.get("name", "")) for f in dir_files if not f.get("is_directory")
  5422. ]
  5423. for remote_full_path in _3mf_files_for_print(listed_paths, search_term):
  5424. if remote_full_path in sweep_failed_paths:
  5425. # Listed for this print, and its transfer already failed:
  5426. # the same as a failed walk download, without spending a
  5427. # second deadline on it. Skipping it cannot hand the walk a
  5428. # look-alike: while a file of the print's own name is
  5429. # listed, files that merely contain the name are not.
  5430. logger.info(
  5431. "Not downloading %s again: its transfer already failed; the recovery retry will fetch it",
  5432. remote_full_path,
  5433. )
  5434. walk_transfer_failed = True
  5435. continue
  5436. fname = posixpath.basename(remote_full_path)
  5437. logger.info("Found matching file: %s", remote_full_path)
  5438. temp_path = app_settings.archive_dir / "temp" / fname
  5439. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5440. try:
  5441. if ftp_retry_enabled:
  5442. downloaded = await with_ftp_retry(
  5443. download_file_async,
  5444. printer.ip_address,
  5445. printer.access_code,
  5446. remote_full_path,
  5447. temp_path,
  5448. timeout=ftp_timeout,
  5449. socket_timeout=ftp_timeout,
  5450. printer_model=printer.model,
  5451. max_retries=ftp_retry_count,
  5452. retry_delay=ftp_retry_delay,
  5453. operation_name=f"Download 3MF from {remote_full_path}",
  5454. cooloff_ip=printer.ip_address,
  5455. )
  5456. else:
  5457. downloaded = await download_file_async(
  5458. printer.ip_address,
  5459. printer.access_code,
  5460. remote_full_path,
  5461. temp_path,
  5462. timeout=ftp_timeout,
  5463. socket_timeout=ftp_timeout,
  5464. printer_model=printer.model,
  5465. )
  5466. except Exception as e:
  5467. logger.debug("Failed to download %s: %s", remote_full_path, e)
  5468. continue
  5469. if downloaded:
  5470. downloaded_filename = fname
  5471. logger.info("Found and downloaded: %s", remote_full_path)
  5472. cache_3mf_download(printer_id, fname, temp_path)
  5473. break
  5474. # The listing named the file, so it is on the card;
  5475. # only the transfer failed (#3063).
  5476. ftp_transfer_failed = True
  5477. walk_transfer_failed = True
  5478. # A "Print again" on the printer's screen names no file Bambuddy can
  5479. # find: only its history copy under a generic name, and the 3MF's
  5480. # internal title (#3307). When an earlier run of the same job was
  5481. # archived, its 3MF is the one being printed again. Not when the
  5482. # directory walk listed a file for this print and only its transfer
  5483. # failed: that file is on the card, and the retry fetches it. A
  5484. # cool-off or a failed sweep path is no such evidence -- the retry
  5485. # tries the same names, which this print's file never had.
  5486. reused_3mf_from: int | None = None
  5487. if not downloaded_filename and not walk_transfer_failed:
  5488. reported_layers = raw_mqtt.get("total_layer_num")
  5489. earlier = await _archived_3mf_for_repeat(
  5490. db,
  5491. printer_id,
  5492. subtask_name,
  5493. filename,
  5494. reported_layers if isinstance(reported_layers, int) and reported_layers > 0 else None,
  5495. )
  5496. if earlier is not None:
  5497. reuse_name = Path(earlier.filename or "").name or f"archive_{earlier.id}.3mf"
  5498. # Per printer: two printers reprinting the same job at once
  5499. # must not write one temp file (archive_print names the
  5500. # archive after original_filename, not this path).
  5501. reuse_path = app_settings.archive_dir / "temp" / f"reprint_{printer_id}_{reuse_name}"
  5502. try:
  5503. reuse_path.parent.mkdir(parents=True, exist_ok=True)
  5504. await asyncio.to_thread(shutil.copyfile, app_settings.base_dir / earlier.file_path, reuse_path)
  5505. except OSError as e:
  5506. # A copy that fails leaves the print the fallback archive
  5507. # it would have had, not no archive at all.
  5508. logger.warning("Could not copy the 3MF of archive %s for printer %s: %s", earlier.id, printer_id, e)
  5509. else:
  5510. temp_path = reuse_path
  5511. downloaded_filename = reuse_name
  5512. reused_3mf_from = earlier.id
  5513. cache_3mf_download(printer_id, reuse_name, temp_path)
  5514. logger.info(
  5515. "No 3MF on printer %s for %s (%s); using the 3MF of archive %s, an earlier run of the same job",
  5516. printer_id,
  5517. subtask_name,
  5518. filename,
  5519. earlier.id,
  5520. )
  5521. # Validate the downloaded 3MF actually matches the plate that's running
  5522. # (#1204): subtask_name lags across consecutive plates of the same model,
  5523. # so the first FTP candidate (built from subtask_name) can land on the
  5524. # previous plate's still-resident upload. Cross-check the slice_info
  5525. # plate index against the plate parsed from gcode_file (always fresh —
  5526. # it's the field whose change triggered this callback).
  5527. if downloaded_filename and temp_path:
  5528. expected_plate = parse_plate_id(filename)
  5529. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  5530. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  5531. logger.warning(
  5532. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  5533. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  5534. downloaded_filename,
  5535. actual_plate,
  5536. expected_plate,
  5537. subtask_name,
  5538. )
  5539. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  5540. retry_succeeded = False
  5541. if corrected_subtask and corrected_subtask != subtask_name:
  5542. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  5543. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  5544. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  5545. for remote_path in (
  5546. f"/{try_filename}",
  5547. f"/cache/{try_filename}",
  5548. f"/model/{try_filename}",
  5549. f"/data/{try_filename}",
  5550. f"/data/Metadata/{try_filename}",
  5551. ):
  5552. try:
  5553. if ftp_retry_enabled:
  5554. downloaded = await with_ftp_retry(
  5555. download_file_async,
  5556. printer.ip_address,
  5557. printer.access_code,
  5558. remote_path,
  5559. retry_temp_path,
  5560. timeout=ftp_timeout,
  5561. socket_timeout=ftp_timeout,
  5562. printer_model=printer.model,
  5563. max_retries=ftp_retry_count,
  5564. retry_delay=ftp_retry_delay,
  5565. operation_name=f"Re-download 3MF from {remote_path}",
  5566. cooloff_ip=printer.ip_address,
  5567. non_retry_exceptions=(FileNotOnPrinterError,),
  5568. )
  5569. else:
  5570. downloaded = await download_file_async(
  5571. printer.ip_address,
  5572. printer.access_code,
  5573. remote_path,
  5574. retry_temp_path,
  5575. timeout=ftp_timeout,
  5576. socket_timeout=ftp_timeout,
  5577. printer_model=printer.model,
  5578. )
  5579. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  5580. logger.info(
  5581. "[CALLBACK] Re-download succeeded with corrected name %s "
  5582. "(plate %s) — replacing wrong file",
  5583. try_filename,
  5584. expected_plate,
  5585. )
  5586. try:
  5587. temp_path.unlink(missing_ok=True)
  5588. except OSError:
  5589. pass
  5590. temp_path = retry_temp_path
  5591. downloaded_filename = try_filename
  5592. subtask_name = corrected_subtask
  5593. cache_3mf_download(printer_id, try_filename, temp_path)
  5594. retry_succeeded = True
  5595. break
  5596. elif downloaded:
  5597. # Wrong plate again — discard and keep trying
  5598. try:
  5599. retry_temp_path.unlink(missing_ok=True)
  5600. except OSError:
  5601. pass
  5602. except FileNotOnPrinterError:
  5603. continue
  5604. except Exception as e:
  5605. logger.debug("Re-download failed for %s: %s", remote_path, e)
  5606. if retry_succeeded:
  5607. break
  5608. # If the retry didn't find a matching file, drop the wrong 3MF
  5609. # so the no-3MF fallback below creates an archive whose name
  5610. # at least reflects the right plate.
  5611. if not retry_succeeded:
  5612. logger.warning(
  5613. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  5614. expected_plate,
  5615. )
  5616. try:
  5617. temp_path.unlink(missing_ok=True)
  5618. except OSError:
  5619. pass
  5620. temp_path = None
  5621. downloaded_filename = None
  5622. # Whatever the sweep's transport did earlier, it is not why
  5623. # this archive ends up empty: a 3MF downloaded fine, it was
  5624. # just the wrong plate. Retrying would re-fetch that same
  5625. # contradicted file under the same stale names and hand it
  5626. # to _recover_fallback_archive, which checks that a
  5627. # candidate is a readable 3MF but not which plate it is --
  5628. # so the row would be filled in with another plate's
  5629. # filament and cost, the exact swap #2957 removed (#3063).
  5630. ftp_transfer_failed = False
  5631. # Disown the name for *lookups*: it has just been shown to
  5632. # fetch another plate's 3MF, and it keys `_active_prints`
  5633. # below, where the cover endpoint's own download of that
  5634. # same name would find this archive and fill it in with the
  5635. # file we are discarding here.
  5636. #
  5637. # Keep it for the *title*, which is a separate question.
  5638. # ``swap_plate_suffix`` returns None both for a name that
  5639. # carries no "- Plate N" / "_plate_N" suffix and for no
  5640. # name at all, and those are not the same situation: a name
  5641. # without a suffix holds no stale plate number to be wrong
  5642. # about. Blanking both uses at once dropped the project
  5643. # name too, and the row fell through to the gcode_file path
  5644. # titled "plate_1" though the real name was in hand.
  5645. # #1204's own premise is consecutive plates *of the same
  5646. # model*, so the project part is right either way (#3126).
  5647. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  5648. subtask_name = corrected_subtask or ""
  5649. # Deleted while the 3MF was being fetched (that can take minutes): no
  5650. # archive, timelapse or tracking for a printer that will never report
  5651. # the print's end. forget_printer again: the download registered its
  5652. # 3MF cache entry after the delete cleared the id. (A delete committing
  5653. # while the archive is written is caught after its commit.)
  5654. if await _printer_gone(db, printer_id):
  5655. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  5656. await forget_printer(printer_id)
  5657. return
  5658. if not downloaded_filename or not temp_path:
  5659. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  5660. # Create a fallback archive without 3MF data so the print is still tracked
  5661. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  5662. try:
  5663. from backend.app.models.archive import PrintArchive
  5664. # Why the card is empty. The two temporary causes outrank the
  5665. # storage verdict because they say the sweep never got a fair
  5666. # answer: a cool-off skipped it at the transport, and a failed
  5667. # transfer reached the printer but never finished. Either way
  5668. # the file is still on the card, so reporting where the printer
  5669. # files its jobs would describe a setting that is not the
  5670. # problem (#2957, #3063).
  5671. if blocked_by_ftps_cooloff:
  5672. no_3mf_reason = REASON_FTPS_COOLOFF
  5673. elif storage.reachable and ftp_transfer_failed:
  5674. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  5675. else:
  5676. no_3mf_reason = storage.reason
  5677. # Derive print name from subtask_name or filename. The
  5678. # plate guard's disowned name comes second: it is a real name
  5679. # for a real print, and only the gcode_file path is left
  5680. # otherwise -- which titles the row "plate_1" (#3126).
  5681. print_name = subtask_name or display_name_after_plate_reject or filename
  5682. if print_name:
  5683. # Clean up the name (remove extensions, path parts)
  5684. print_name = print_name.split("/")[-1]
  5685. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  5686. else:
  5687. print_name = "Unknown Print"
  5688. # Recover estimated print time from MQTT (best-effort for notifications)
  5689. fallback_print_time = None
  5690. mqtt_remaining = data.get("remaining_time")
  5691. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5692. fallback_print_time = int(mqtt_remaining)
  5693. if fallback_print_time is None:
  5694. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  5695. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  5696. fallback_print_time = int(mc_remaining * 60)
  5697. # Best-effort filament metadata from MQTT — see
  5698. # _extract_filament_data_from_mqtt. Without this the fallback
  5699. # archive's filament fields stayed NULL even though the AMS
  5700. # state at print start was sitting right there in `data`.
  5701. # The slicer's ams_mapping (when present) narrows the result
  5702. # to slots actually used by the print (#1533).
  5703. mqtt_filament_meta = _extract_filament_data_from_mqtt(
  5704. data, _get_start_ams_mapping(data, printer_id, None)
  5705. )
  5706. # Create minimal archive entry
  5707. fallback_archive = PrintArchive(
  5708. printer_id=printer_id,
  5709. filename=filename or f"{print_name}.3mf",
  5710. file_path="", # Empty - no 3MF file available
  5711. file_size=0,
  5712. print_name=print_name,
  5713. print_time_seconds=fallback_print_time,
  5714. status="printing",
  5715. started_at=detected_at,
  5716. subtask_id=subtask_id,
  5717. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  5718. filament_type=mqtt_filament_meta.get("filament_type"),
  5719. filament_color=mqtt_filament_meta.get("filament_color"),
  5720. extra_data={
  5721. "no_3mf_available": True,
  5722. # Why the card is empty, when we know -- see above. The
  5723. # banner reads this to stop telling H2/P2 owners to
  5724. # switch on a setting that is already on and would not
  5725. # have helped (#2780).
  5726. "no_3mf_reason": no_3mf_reason,
  5727. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  5728. "_print_data": data,
  5729. },
  5730. )
  5731. db.add(fallback_archive)
  5732. try:
  5733. await db.commit()
  5734. except IntegrityError:
  5735. # Not "Failed to create fallback archive" below, and no
  5736. # start notification for a printer that is gone.
  5737. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  5738. return
  5739. raise
  5740. await db.refresh(fallback_archive)
  5741. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5742. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5743. return
  5744. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5745. # Track as active print
  5746. _bind_active_print(printer_id, fallback_archive.id, fallback_archive.filename, filename, subtask_name)
  5747. await _open_run_for(fallback_archive.id, printer_id, subtask_id)
  5748. # Record starting energy if smart plug available (#941: persisted column)
  5749. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5750. # Send WebSocket notification
  5751. await ws_manager.send_archive_created(
  5752. {
  5753. "id": fallback_archive.id,
  5754. "printer_id": fallback_archive.printer_id,
  5755. "filename": fallback_archive.filename,
  5756. "print_name": fallback_archive.print_name,
  5757. "status": fallback_archive.status,
  5758. }
  5759. )
  5760. # MQTT relay - publish archive created
  5761. try:
  5762. await mqtt_relay.on_archive_created(
  5763. archive_id=fallback_archive.id,
  5764. print_name=fallback_archive.print_name,
  5765. printer_name=printer.name,
  5766. status=fallback_archive.status,
  5767. )
  5768. except Exception:
  5769. pass # Don't fail if MQTT fails
  5770. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5771. try:
  5772. await _store_spoolman_print_data(
  5773. printer_id,
  5774. fallback_archive.id,
  5775. fallback_archive.file_path,
  5776. db,
  5777. printer_manager,
  5778. ams_mapping=_get_start_ams_mapping(data, printer_id, fallback_archive.id),
  5779. plate_id=_get_start_plate_id(printer_id, fallback_archive.id),
  5780. )
  5781. except Exception as e:
  5782. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5783. # Both temporary give-ups are worth coming back for, and for
  5784. # the same reason: the file is on the printer and the last look
  5785. # failed at the transport rather than finding nothing. One waits
  5786. # out the handshake block (#2957), the other waits for the
  5787. # printer to stop being busy (#3063). Deliberately not scheduled
  5788. # for a storage verdict: a file on internal eMMC will not appear
  5789. # at any FTPS path however long we wait, and retrying it is
  5790. # exactly the sweep #2780 removed.
  5791. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5792. # `possible_names`, not the raw MQTT strings: it is the exact
  5793. # list this flow just tried, already stripped of any path
  5794. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5795. # some firmware) and deduped.
  5796. _schedule_fallback_3mf_retry(
  5797. printer_id=printer_id,
  5798. archive_id=fallback_archive.id,
  5799. filenames=list(possible_names),
  5800. reason=no_3mf_reason,
  5801. )
  5802. # Send notification without archive data (file not found)
  5803. if not notification_sent:
  5804. await _send_print_start_notification(printer_id, data, logger=logger)
  5805. # The same baseline the other two on_print_start branches take
  5806. # (#2704), and last for the same reason they are: it lists the
  5807. # printer's timelapse directory, so a slow card must not delay
  5808. # the _active_prints registration, the energy reading, the
  5809. # archive-created event or the start notification above it.
  5810. #
  5811. # This branch never took one, so every no-3MF archive reached
  5812. # completion with no baseline in memory and none on the row, and
  5813. # the completion scan fell into its "snapshot now" fallback --
  5814. # which runs after the printer has written the video, so the new
  5815. # file landed inside the baseline and no diff ever matched
  5816. # (#2957 follow-up).
  5817. #
  5818. # Skipped when the FTPS cool-off is what produced this fallback:
  5819. # the listing needs the same connection that just failed, so it
  5820. # could only record that the card was unreadable. The scan
  5821. # handles that case by refusing to choose between candidates.
  5822. if not blocked_by_ftps_cooloff:
  5823. await _capture_timelapse_baseline_at_start(
  5824. printer, printer_id, logger, archive_id=fallback_archive.id
  5825. )
  5826. await _forget_if_printer_gone(printer_id)
  5827. return
  5828. except Exception as e:
  5829. logger.error("Failed to create fallback archive: %s", e)
  5830. # Send notification without archive data (file not found)
  5831. if not notification_sent:
  5832. await _send_print_start_notification(printer_id, data, logger=logger)
  5833. return
  5834. try:
  5835. # Archive the file with status "printing"
  5836. service = ArchiveService(db)
  5837. try:
  5838. archive = await service.archive_print(
  5839. printer_id=printer_id,
  5840. source_file=temp_path,
  5841. print_data={
  5842. **data,
  5843. "status": "printing",
  5844. # Where the 3MF came from when the printer had none to
  5845. # give (#3307), for whoever reads this archive later.
  5846. **({"_3mf_from_archive": reused_3mf_from} if reused_3mf_from is not None else {}),
  5847. },
  5848. subtask_id=subtask_id,
  5849. started_at=detected_at,
  5850. # The reused copy's temp name carries the printer id; a
  5851. # download's is the file's own name, as before.
  5852. original_filename=downloaded_filename if reused_3mf_from is not None else None,
  5853. )
  5854. except IntegrityError:
  5855. # archive_print removed the folder it had copied the 3MF into.
  5856. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5857. return
  5858. raise
  5859. if archive:
  5860. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5861. # Set on the row rather than passed to archive_print, which also
  5862. # serves the queue dispatcher — there the queue item decides.
  5863. # Guarded because this branch has no ``except``: an unhandled
  5864. # write error would take the _active_prints registration, the
  5865. # start notification, the energy reading and the timelapse
  5866. # baseline below it with it, and a missing prompt is by far the
  5867. # cheaper failure.
  5868. archive_id = archive.id
  5869. try:
  5870. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5871. archive.confirm_requested = True
  5872. await db.commit()
  5873. except Exception as e:
  5874. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5875. # The rollback expires every loaded object, and on an async
  5876. # session reading one afterwards raises instead of
  5877. # reloading, so the two this branch goes on to use are
  5878. # fetched again. The archive itself was committed by
  5879. # archive_print; only the flag is lost.
  5880. try:
  5881. await db.rollback()
  5882. archive = await db.get(PrintArchive, archive_id)
  5883. printer = await db.get(Printer, printer_id)
  5884. except Exception as reload_error:
  5885. logger.warning(
  5886. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5887. )
  5888. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5889. return
  5890. # Track this active print (use both original filename and downloaded filename)
  5891. _bind_active_print(printer_id, archive_id, downloaded_filename, filename, subtask_name)
  5892. await _open_run_for(archive_id, printer_id, subtask_id)
  5893. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5894. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5895. # Record starting energy from smart plug if available (#941: persisted column)
  5896. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5897. await ws_manager.send_archive_created(
  5898. {
  5899. "id": archive.id,
  5900. "printer_id": archive.printer_id,
  5901. "filename": archive.filename,
  5902. "print_name": archive.print_name,
  5903. "status": archive.status,
  5904. }
  5905. )
  5906. # MQTT relay - publish archive created
  5907. try:
  5908. await mqtt_relay.on_archive_created(
  5909. archive_id=archive.id,
  5910. print_name=archive.print_name,
  5911. printer_name=printer.name,
  5912. status=archive.status,
  5913. )
  5914. except Exception:
  5915. pass # Don't fail if MQTT fails
  5916. # Send notification with archive data (new archive created)
  5917. if not notification_sent:
  5918. archive_data = {
  5919. "print_time_seconds": _run_print_time_seconds(archive, printer_id),
  5920. "created_by_id": archive.created_by_id,
  5921. }
  5922. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5923. # Extract printable objects for skip object functionality
  5924. try:
  5925. from backend.app.services.archive import extract_printable_objects_from_3mf
  5926. client = printer_manager.get_client(printer_id)
  5927. if client:
  5928. with open(temp_path, "rb") as f:
  5929. threemf_data = f.read()
  5930. # Extract with positions for UI overlay, scoped to the
  5931. # plate that is printing — an all-plates 3MF carries
  5932. # every plate's objects (#2522).
  5933. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5934. threemf_data,
  5935. plate_number=resolve_plate_id(client.state),
  5936. include_positions=True,
  5937. )
  5938. if printable_objects:
  5939. # Store objects in printer state
  5940. client.state.printable_objects = printable_objects
  5941. client.state.printable_objects_bbox_all = bbox_all
  5942. client.state.skipped_objects = [] # Reset skipped objects for new print
  5943. logger.info(
  5944. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5945. )
  5946. except Exception as e:
  5947. logger.debug("Failed to extract printable objects: %s", e)
  5948. # From the archived copy: the downloaded one may be removed
  5949. # below while the pauses are still being read.
  5950. if archive is not None and archive.file_path:
  5951. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  5952. # Store Spoolman tracking data for per-filament usage reporting
  5953. try:
  5954. await _store_spoolman_print_data(
  5955. printer_id,
  5956. archive.id,
  5957. archive.file_path,
  5958. db,
  5959. printer_manager,
  5960. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  5961. plate_id=_get_start_plate_id(printer_id, archive_id),
  5962. )
  5963. except Exception as e:
  5964. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  5965. # Price the print from its spools now rather than only at completion (#3261)
  5966. _schedule_archive_cost_estimate(
  5967. printer_id,
  5968. archive.id,
  5969. printer_manager,
  5970. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  5971. plate_id=_get_start_plate_id(printer_id, archive_id),
  5972. session_factory=async_session,
  5973. )
  5974. # Capture timelapse file baseline for snapshot-diff on completion
  5975. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  5976. await _forget_if_printer_gone(printer_id)
  5977. finally:
  5978. # Keep temp_path around until print completes so the cover endpoint
  5979. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5980. # the file. If the cache entry was evicted early (file vanished),
  5981. # clean up any stragglers here to avoid leaking disk on retries.
  5982. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5983. if temp_path and temp_path.exists() and cached_now != temp_path:
  5984. temp_path.unlink()
  5985. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5986. _TIMELAPSE_DIRECTORIES = ("/timelapse", "/timelapse/video", "/record", "/recording")
  5987. # A baseline that could not be read at print start is read again on this
  5988. # schedule while the print runs (#3412). The printer writes the video only once
  5989. # the print has ended, so a reading taken mid-print is as good as one taken at
  5990. # the start. The interval is shorter than the FTPS handshake cool-off (300 s),
  5991. # which is what usually makes the card unreadable, so the first reading after
  5992. # it ends is not long behind; while the cool-off runs a round costs nothing, as
  5993. # no connection is opened. The cap bounds a print that never reports an end.
  5994. _TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS = 120.0
  5995. _TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS = 720
  5996. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  5997. # tests can shrink them without waiting out real delays.
  5998. #
  5999. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  6000. # looking. Across 247 support bundles the attempt that found the video was #1
  6001. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  6002. # decaying one, which is the signature of a budget that expires while files are
  6003. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  6004. # prints make big videos and the printer writes them after the print ends, so
  6005. # the poll now runs for minutes and costs one FTP LIST per round.
  6006. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  6007. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  6008. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  6009. def _timelapse_scan_max_attempts() -> int:
  6010. """Round cap for the poll, derived from the wall-clock budget.
  6011. The deadline alone is not a sufficient bound: it assumes each round really
  6012. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  6013. and an FTP list that fails immediately would otherwise spin against the
  6014. printer at full speed for the whole window. Whichever bound is reached
  6015. first ends the poll.
  6016. """
  6017. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  6018. # A zero interval makes the wall-clock budget meaningless; fall back to
  6019. # the round count the production interval would have given.
  6020. return 32
  6021. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  6022. async def _read_timelapse_baseline(printer) -> tuple[set[str], bool]:
  6023. """The video names on *printer*'s card, and whether the card was read.
  6024. ``_list_timelapse_videos`` answers ``[]`` when its connect fails rather
  6025. than raising, so a card behind the FTPS handshake cool-off, or one whose
  6026. listing timed out, is indistinguishable from one holding no videos.
  6027. Everywhere that only wants to know "is there a video yet" the difference
  6028. does not matter -- both mean "not yet, retry".
  6029. It matters where an empty listing is recorded as a *baseline*. Recording
  6030. "the card held nothing" for a card that was never read means every video on
  6031. it counts as new, and the completion scan then attaches a stale video to
  6032. this print and deletes it from the printer (#2957 follow-up, #3412). So an
  6033. empty listing is asked again here in a way that tells the two apart: the
  6034. card counts as read only when every directory walked answered, with a
  6035. listing or with "no such directory". One that failed may be the one
  6036. holding the videos.
  6037. """
  6038. from backend.app.services.bambu_ftp import ftps_handshake_blocked, list_files_result_async
  6039. files, _ = await _list_timelapse_videos(printer)
  6040. if files:
  6041. return {f.get("name", "") for f in files}, True
  6042. ip_address = getattr(printer, "ip_address", None)
  6043. printer_id = getattr(printer, "id", None)
  6044. if not ip_address:
  6045. return set(), True
  6046. # No card in the slot: nothing to read, and nothing a video could land on.
  6047. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  6048. return set(), True
  6049. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  6050. if ftps_handshake_blocked(ip_address):
  6051. # Below any path: every remaining one would fail the same way.
  6052. return set(), False
  6053. listing = await list_files_result_async(
  6054. ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  6055. )
  6056. if not (listing.available or listing.missing):
  6057. return set(), False
  6058. videos = [
  6059. f
  6060. for f in listing.files
  6061. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  6062. ]
  6063. if videos:
  6064. return {f.get("name", "") for f in videos}, True
  6065. return set(), True
  6066. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  6067. """List video files from printer's timelapse directory.
  6068. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  6069. Returns (video_files, found_path) where video_files is a list of file dicts
  6070. and found_path is the directory where they were found, or ([], None).
  6071. An empty return does not distinguish "no videos" from "could not read the
  6072. card" — see :func:`_read_timelapse_baseline`, which the two baseline
  6073. callers use instead.
  6074. """
  6075. from backend.app.services.bambu_ftp import list_files_async
  6076. logger = logging.getLogger(__name__)
  6077. # No card in the slot means no /timelapse to walk — four connections that
  6078. # can only fail, on a path whose failures are swallowed and so would go on
  6079. # costing time silently forever (#2780).
  6080. #
  6081. # ``getattr`` rather than ``printer.id``: every dereference below happens
  6082. # inside the loop's own try/except, so a caller that passed something
  6083. # unexpected used to get an empty listing rather than an exception. Keep
  6084. # that, instead of making this gate the first thing that can raise here.
  6085. printer_id = getattr(printer, "id", None)
  6086. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  6087. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  6088. return [], None
  6089. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  6090. try:
  6091. found_files = await list_files_async(
  6092. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  6093. )
  6094. if found_files:
  6095. video_files = [
  6096. f
  6097. for f in found_files
  6098. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  6099. ]
  6100. if video_files:
  6101. return video_files, timelapse_path
  6102. except Exception as e:
  6103. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  6104. continue
  6105. return [], None
  6106. async def _capture_timelapse_baseline_at_start(
  6107. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  6108. ) -> None:
  6109. """Snapshot the printer's timelapse directory at print start so the
  6110. completion-time scan can pick the new file by set-difference.
  6111. Must be called from every on_print_start path that proceeds to a real
  6112. print — both the new-archive branch and the expected-archive branch (which
  6113. queue / VP-dispatched prints take). Without a baseline,
  6114. _scan_for_timelapse_with_retries falls into its "take baseline now"
  6115. fallback that runs AFTER the new MP4 has already landed on the SD card,
  6116. so the new file ends up in the "baseline" set and no diff ever matches.
  6117. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  6118. unreliable — the snapshot-diff approach sidesteps that entirely.
  6119. When ``archive_id`` is known the baseline is also written to the archive
  6120. row, so it survives a restart and the manual "Scan for Timelapse" button
  6121. can run the same diff instead of falling back to clock-based matching
  6122. (#2704). Only baselines taken at print start are persisted — one taken at
  6123. completion already contains the new video and would poison a later scan.
  6124. """
  6125. names: set[str] | None = None
  6126. unread = False
  6127. _timelapse_baselines_unread.discard(printer_id)
  6128. try:
  6129. names, read = await _read_timelapse_baseline(printer)
  6130. unread = not read
  6131. _timelapse_baselines[printer_id] = names
  6132. if unread:
  6133. # Recorded anyway, deliberately, and marked. An empty baseline taken
  6134. # off a card we could not read is not evidence, but it is still the
  6135. # right *default*: Bambuddy deletes each video from the printer once
  6136. # it is attached, so the usual card holds exactly one video at
  6137. # completion and an empty baseline resolves it. Persisting NULL
  6138. # instead would send completion to take its own snapshot, by which
  6139. # point this print's video is on the card and would be swallowed by
  6140. # it. The mark keeps the scan from choosing between several videos
  6141. # (#3412), and the card is read again while the print runs.
  6142. _timelapse_baselines_unread.add(printer_id)
  6143. logger.warning(
  6144. "[TIMELAPSE] Baseline for printer %s taken while its card could not be read — "
  6145. "treating it as empty for now and reading it again during the print",
  6146. printer_id,
  6147. )
  6148. logger.info(
  6149. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  6150. len(names),
  6151. printer_id,
  6152. )
  6153. except Exception as e:
  6154. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  6155. run_started_at: datetime | None = None
  6156. run_id: int | None = None
  6157. if archive_id is not None:
  6158. try:
  6159. async with async_session() as db:
  6160. from backend.app.models.archive import PrintArchive
  6161. from backend.app.services.print_log import open_run_on_printer
  6162. archive = await db.get(PrintArchive, archive_id)
  6163. if archive is not None:
  6164. # Written even when the listing failed, and then as NULL. A
  6165. # reprint reuses the archive row, so leaving the previous
  6166. # run's baseline in place would have the scan diff this print
  6167. # against the state of the printer before the *last* one —
  6168. # and a stale baseline reads as authoritative, where NULL
  6169. # correctly falls back to a fresh snapshot.
  6170. baseline = sorted(names) if names is not None else None
  6171. archive.timelapse_baseline = baseline
  6172. archive.timelapse_baseline_unread = unread
  6173. run_started_at = archive.started_at
  6174. # And on the run this print opened, whose scan reads it:
  6175. # the archive's is its latest start's, which another plate
  6176. # of it on another printer can take over.
  6177. run = await open_run_on_printer(db, printer_id)
  6178. if run is not None and run.archive_id == archive_id:
  6179. run.timelapse_baseline = baseline
  6180. run.timelapse_baseline_unread = unread
  6181. run_id = run.id
  6182. await db.commit()
  6183. except Exception as e:
  6184. # In-memory baseline still covers the normal completion path.
  6185. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  6186. if unread and names is not None:
  6187. spawn_background_task(
  6188. _reread_unread_timelapse_baseline(printer_id, names, archive_id, run_started_at, run_id),
  6189. name=f"reread-timelapse-baseline-{printer_id}",
  6190. )
  6191. # Before the print has ended there is no video yet: a long PREPARE (heating,
  6192. # levelling) counts as much as the print itself.
  6193. _BASELINE_REREAD_STATES = _ACTIVE_PRINT_STATES | {"PREPARE", "SLICING"}
  6194. def _schedule_timelapse_scan(
  6195. archive_id: int, printer_id: int, *, plate_id: int | None, run_id: int | None = None
  6196. ) -> None:
  6197. """Start the completion scan with the print-start baseline: the names, and
  6198. whether they were taken off a card that could not be read. Taking them
  6199. ends any re-read still running for it. ``run_id`` is the print that
  6200. ended, whose video it looks for."""
  6201. unread = printer_id in _timelapse_baselines_unread
  6202. _timelapse_baselines_unread.discard(printer_id)
  6203. baseline = _timelapse_baselines.pop(printer_id, None)
  6204. from backend.app.services import archive_work
  6205. # Held while it looks: it finds its print by the archive's id, which a
  6206. # merge would move away (archive redesign P2).
  6207. spawn_background_task(
  6208. archive_work.held_while(
  6209. archive_id,
  6210. _scan_for_timelapse_with_retries(
  6211. archive_id, baseline, plate_id=plate_id, baseline_unread=unread, run_id=run_id
  6212. ),
  6213. ),
  6214. name=f"scan-timelapse-{archive_id}",
  6215. )
  6216. def _unread_baseline_round(printer_id: int, names: set[str]) -> bool | None:
  6217. """Whether to read an unread baseline again now: True to read, None to
  6218. skip this round, False once it is over -- the print it was taken for is
  6219. no longer the one on the printer, has stopped printing, or the baseline
  6220. has been read.
  6221. ``names`` is the very set object recorded at print start: completion pops
  6222. it and the next print records a new one, so identity marks the run. A
  6223. printer that is momentarily disconnected says nothing about its print, so
  6224. that only skips the round.
  6225. """
  6226. if _timelapse_baselines.get(printer_id) is not names or printer_id not in _timelapse_baselines_unread:
  6227. return False
  6228. state = printer_manager.get_status(printer_id)
  6229. if state is None or not state.connected:
  6230. return None
  6231. return state.state in _BASELINE_REREAD_STATES
  6232. async def _reread_unread_timelapse_baseline(
  6233. printer_id: int,
  6234. names: set[str],
  6235. archive_id: int | None,
  6236. run_started_at: datetime | None,
  6237. run_id: int | None = None,
  6238. ) -> None:
  6239. """Read again a print-start baseline the card could not give (#3412).
  6240. The printer writes the video only once the print has ended, so the card
  6241. read at any point during the print holds exactly what it held at the
  6242. start. Each round stops once the print is no longer the one the baseline
  6243. was taken for or has stopped printing, and checks that again after the
  6244. listing returns, before anything is recorded.
  6245. """
  6246. from backend.app.models.archive import PrintArchive
  6247. from backend.app.models.printer import Printer
  6248. from backend.app.services.print_log import run_of
  6249. logger = logging.getLogger(__name__)
  6250. for _ in range(_TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS):
  6251. await asyncio.sleep(_TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS)
  6252. now = _unread_baseline_round(printer_id, names)
  6253. if now is False:
  6254. return
  6255. if now is None:
  6256. continue
  6257. try:
  6258. async with async_session() as db:
  6259. printer = await db.get(Printer, printer_id)
  6260. if printer is None:
  6261. return
  6262. fresh, read = await _read_timelapse_baseline(printer)
  6263. except Exception as e:
  6264. logger.debug("[TIMELAPSE] Re-reading the baseline for printer %s failed: %s", printer_id, e)
  6265. continue
  6266. if not read:
  6267. continue
  6268. now = _unread_baseline_round(printer_id, names)
  6269. if now is False:
  6270. return
  6271. if now is None:
  6272. # The printer dropped off while the listing was out, so nothing
  6273. # says it did not end meanwhile: keep the reading for a round that
  6274. # can vouch for it.
  6275. continue
  6276. names.update(fresh)
  6277. _timelapse_baselines_unread.discard(printer_id)
  6278. logger.info(
  6279. "[TIMELAPSE] Baseline for printer %s read during the print: %s video files",
  6280. printer_id,
  6281. len(fresh),
  6282. )
  6283. if archive_id is None:
  6284. return
  6285. try:
  6286. async with async_session() as db:
  6287. archive = await db.get(PrintArchive, archive_id)
  6288. # Only the run it was taken for: by now the row can belong to a
  6289. # reprint, whose baseline is its own.
  6290. if archive is not None and archive.started_at == run_started_at and archive.timelapse_baseline_unread:
  6291. archive.timelapse_baseline = sorted(names)
  6292. archive.timelapse_baseline_unread = False
  6293. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6294. if run is not None and run.timelapse_baseline_unread:
  6295. run.timelapse_baseline = sorted(names)
  6296. run.timelapse_baseline_unread = False
  6297. await db.commit()
  6298. except Exception as e:
  6299. # The in-memory baseline is read now, which covers completion
  6300. # unless Bambuddy restarts first.
  6301. logger.warning("[TIMELAPSE] Failed to persist the re-read baseline for archive %s: %s", archive_id, e)
  6302. return
  6303. async def _timelapse_still_wanted(db, archive, run_id: int | None, run_started_at: datetime | None) -> bool:
  6304. """Whether the print a timelapse is for still has none: its run, by id,
  6305. exists without a video and no later print took over (``superseded``).
  6306. Without a run, the archive is still on that print's start (a newer run's
  6307. video is its own) and has none."""
  6308. from backend.app.services.print_log import run_of, superseded
  6309. if run_id is not None:
  6310. run = await run_of(db, archive.id, run_id)
  6311. return run is not None and run.timelapse_path is None and not await superseded(db, run)
  6312. return archive.timelapse_path is None and archive.started_at == run_started_at
  6313. async def _scan_for_timelapse_with_retries(
  6314. archive_id: int,
  6315. baseline_names: set[str] | None = None,
  6316. *,
  6317. plate_id: int | None = None,
  6318. baseline_unread: bool = False,
  6319. run_id: int | None = None,
  6320. ):
  6321. """Poll the printer for this print's timelapse and attach it.
  6322. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  6323. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  6324. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  6325. (#2704). Comparing the current listing against the set of filenames that
  6326. existed when the print started needs no clock at all, because the printer
  6327. writes the video only once the print has ended.
  6328. Baseline precedence: the caller's in-memory set, then the one persisted on
  6329. the archive at print start, then a snapshot taken now. The last of those is
  6330. a poor substitute — by completion the new video may already be on the card,
  6331. in which case it lands in the "baseline" and no diff can ever match — but it
  6332. is all that is available for a print that began before Bambuddy started.
  6333. On success the video is deleted from the printer, which keeps ``/timelapse``
  6334. down to the unclaimed files and makes the next diff unambiguous.
  6335. ``baseline_unread`` marks the caller's baseline as taken off a card that
  6336. could not be read; a stored one carries the same mark on the archive.
  6337. ``run_id`` is the print that ended (archive redesign): the video is that
  6338. run's, the stored baseline is the run's own, and the poll ends once the
  6339. run has a video or is gone. Without it (no run was written), the run is
  6340. whichever the archive is on when the scan starts.
  6341. """
  6342. from backend.app.services.print_log import run_of
  6343. logger = logging.getLogger(__name__)
  6344. # Cleared when the baseline was taken off a card we could not read, so the
  6345. # attach step refuses to choose between several candidates (#2957, #3412).
  6346. baseline_trusted = True
  6347. # --- Phase 1: establish the baseline -------------------------------------
  6348. try:
  6349. async with async_session() as db:
  6350. from backend.app.models.printer import Printer
  6351. service = ArchiveService(db)
  6352. archive = await service.get_archive(archive_id)
  6353. if not archive:
  6354. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  6355. return
  6356. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6357. if run_id is not None and run is None:
  6358. logger.info("[TIMELAPSE] Run %s of archive %s is gone, aborting", run_id, archive_id)
  6359. return
  6360. if run.timelapse_path if run is not None else archive.timelapse_path:
  6361. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  6362. return
  6363. # The printer the print ran on: plates of one archive can print on
  6364. # two printers, and the archive's is the one that started last.
  6365. scan_printer_id = run.printer_id if run is not None and run.printer_id else archive.printer_id
  6366. if not scan_printer_id:
  6367. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  6368. return
  6369. # The run this scan is for. The archive row passes to a newer run
  6370. # when it prints again (the next plate, a reprint), and that run's
  6371. # video is its own.
  6372. run_started_at = run.started_at if run is not None else archive.started_at
  6373. # The baseline stored for it: the run's own, else the archive's
  6374. # while that is still this run's start's.
  6375. stored_baseline, stored_unread = None, False
  6376. if run is not None and run.timelapse_baseline is not None:
  6377. stored_baseline, stored_unread = run.timelapse_baseline, bool(run.timelapse_baseline_unread)
  6378. elif archive.started_at == run_started_at:
  6379. stored_baseline, stored_unread = archive.timelapse_baseline, archive.timelapse_baseline_unread
  6380. if baseline_names is not None and baseline_unread and stored_baseline is not None and not stored_unread:
  6381. # The card was read at print start, and the in-memory copy is
  6382. # one Bambuddy took after a restart off a card it could not
  6383. # read: the stored one is this run's and is evidence.
  6384. baseline_names = set(stored_baseline)
  6385. logger.info(
  6386. "[TIMELAPSE] Using stored baseline over an unread one: %s existing video files for archive %s",
  6387. len(baseline_names),
  6388. archive_id,
  6389. )
  6390. elif baseline_names is not None:
  6391. baseline_trusted = not baseline_unread
  6392. logger.info(
  6393. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  6394. len(baseline_names),
  6395. archive_id,
  6396. )
  6397. elif stored_baseline is not None:
  6398. # Persisted at print start — survives a restart mid-print.
  6399. baseline_names = set(stored_baseline)
  6400. baseline_trusted = not stored_unread
  6401. logger.info(
  6402. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  6403. len(baseline_names),
  6404. archive_id,
  6405. )
  6406. else:
  6407. result = await db.execute(select(Printer).where(Printer.id == scan_printer_id))
  6408. printer = result.scalar_one_or_none()
  6409. if not printer:
  6410. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  6411. return
  6412. baseline_names, baseline_trusted = await _read_timelapse_baseline(printer)
  6413. if not baseline_trusted:
  6414. # The card is unreadable at the one moment a baseline has to
  6415. # be taken, so the empty listing means "we never looked",
  6416. # not "these are all new". Carry on with it anyway — the
  6417. # usual card holds exactly one video, which resolves
  6418. # correctly — but stop the poll from *choosing* between
  6419. # several, which is how a stale video got attached to this
  6420. # print and then deleted off the printer (#2957 follow-up).
  6421. logger.warning(
  6422. "[TIMELAPSE] Baseline for archive %s taken while printer %s's card could not be "
  6423. "read. A single new video still resolves; several will not be guessed between — "
  6424. "use Scan for Timelapse to pick one by hand",
  6425. archive_id,
  6426. scan_printer_id,
  6427. )
  6428. logger.info(
  6429. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  6430. len(baseline_names),
  6431. archive_id,
  6432. )
  6433. except Exception as e:
  6434. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  6435. return
  6436. # --- Phase 2: poll for a file that was not there when the print began -----
  6437. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  6438. max_attempts = _timelapse_scan_max_attempts()
  6439. seen_names: set[str] = set()
  6440. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  6441. attempt = 0
  6442. while True:
  6443. await asyncio.sleep(delay)
  6444. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  6445. attempt += 1
  6446. try:
  6447. from backend.app.models.printer import Printer
  6448. # Read phase: fetch archive + printer in a short session and release
  6449. # the pooled connection BEFORE the FTP list/download below. Holding it
  6450. # across the FTP round-trips left one connection idle-in-transaction per
  6451. # in-flight scan (issue #2572).
  6452. async with async_session() as db:
  6453. from backend.app.services.print_log import claimed_timelapse_stems
  6454. service = ArchiveService(db)
  6455. archive = await service.get_archive(archive_id)
  6456. if not archive:
  6457. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  6458. return
  6459. if not await _timelapse_still_wanted(db, archive, run_id, run_started_at):
  6460. logger.info(
  6461. "[TIMELAPSE] Archive %s has its video or is printing again, stopping the run's poll",
  6462. archive_id,
  6463. )
  6464. return
  6465. result = await db.execute(select(Printer).where(Printer.id == scan_printer_id))
  6466. printer = result.scalar_one_or_none()
  6467. if not printer:
  6468. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  6469. return
  6470. claimed = await claimed_timelapse_stems(db, scan_printer_id, archive_id=archive_id, run_id=run_id)
  6471. # I/O phase (no DB connection held): FTP list + download.
  6472. video_files, found_path = await _list_timelapse_videos(printer)
  6473. # The poll can run for dozens of rounds, so only narrate a round
  6474. # that saw something change. Repeating the whole listing every 30 s
  6475. # would bury the one interesting line in the support bundle.
  6476. names_now = {f.get("name", "") for f in video_files}
  6477. changed = attempt == 1 or names_now != seen_names
  6478. seen_names = names_now
  6479. speak = logger.info if changed else logger.debug
  6480. if video_files:
  6481. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  6482. if changed:
  6483. for f in video_files[:5]:
  6484. logger.info("[TIMELAPSE] - %s", f.get("name"))
  6485. attached = await _attach_first_unclaimed_timelapse(
  6486. archive_id,
  6487. printer,
  6488. video_files,
  6489. baseline_names,
  6490. claimed,
  6491. attempt,
  6492. logger,
  6493. quiet=not changed,
  6494. require_unambiguous=not baseline_trusted,
  6495. plate_id=plate_id,
  6496. run_started_at=run_started_at,
  6497. run_id=run_id,
  6498. )
  6499. if attached:
  6500. return
  6501. else:
  6502. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  6503. except Exception as e:
  6504. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  6505. if attempt >= max_attempts or time.monotonic() >= deadline:
  6506. break
  6507. # No name-match fallback: it compared the print name against the filename,
  6508. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  6509. # bundles it fired 159 times and matched zero times, so all it added was a
  6510. # misleading log line before giving up.
  6511. logger.warning(
  6512. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  6513. archive_id,
  6514. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  6515. )
  6516. async def _attach_layer_timelapse(
  6517. archive_id: int,
  6518. timelapse_path: Path,
  6519. plate_id: int | None,
  6520. run_started_at: datetime | None,
  6521. run_id: int | None = None,
  6522. ) -> None:
  6523. """Attach the external camera's stitched timelapse to the archive.
  6524. The camera's video is the one the user set up in Bambuddy, so it wins
  6525. over the printer's own when both are on: it replaces the printer's video
  6526. (usually there first; stitching takes minutes) and that file is deleted,
  6527. leaving nothing in the archive folder unreferenced. ``run_started_at`` is
  6528. the run the frames were taken for: when the archive is printing again by
  6529. the time the stitch is done, the video is not the new run's and is
  6530. dropped. The stitched file is a temporary either way.
  6531. ``run_id`` is the print that ended (archive redesign): the video is that
  6532. run's and replaces that run's printer video; the poll by start above is
  6533. for a print without a run.
  6534. """
  6535. from backend.app.services.print_log import run_of, superseded
  6536. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  6537. logger = logging.getLogger(__name__)
  6538. try:
  6539. async with async_session() as db:
  6540. service = ArchiveService(db)
  6541. archive = await service.get_archive(archive_id)
  6542. if archive is None:
  6543. return
  6544. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6545. if run_id is not None and run is None:
  6546. logger.info("[LAYER-TL] Run %s of archive %s is gone; dropping its layer timelapse", run_id, archive_id)
  6547. return
  6548. if run is not None and await superseded(db, run):
  6549. logger.info(
  6550. "[LAYER-TL] A later print took over run %s of archive %s; dropping its layer timelapse",
  6551. run_id,
  6552. archive_id,
  6553. )
  6554. return
  6555. if run is None and archive.started_at != run_started_at:
  6556. logger.info(
  6557. "[LAYER-TL] Archive %s is printing again; dropping the previous run's layer timelapse", archive_id
  6558. )
  6559. return
  6560. holder = run if run is not None else archive
  6561. replaced = holder.timelapse_path
  6562. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  6563. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  6564. if not await service.attach_timelapse(
  6565. archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=plate_id, run_id=run_id
  6566. ):
  6567. return
  6568. attached = holder.timelapse_path
  6569. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  6570. if replaced and replaced != attached:
  6571. try:
  6572. old = safe_join_under(app_settings.base_dir, replaced, http=False)
  6573. except PathTraversalError:
  6574. return
  6575. await asyncio.to_thread(old.unlink, missing_ok=True)
  6576. logger.info("[LAYER-TL] Replaced the printer's timelapse %s on archive %s", replaced, archive_id)
  6577. finally:
  6578. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6579. # ``run_started_at`` not given: attach whichever run the archive is on.
  6580. _ANY_RUN = object()
  6581. async def _attach_first_unclaimed_timelapse(
  6582. archive_id: int,
  6583. printer,
  6584. video_files: list[dict],
  6585. baseline_names: set[str],
  6586. claimed: set[str],
  6587. attempt: int,
  6588. logger: logging.Logger,
  6589. *,
  6590. quiet: bool = False,
  6591. require_unambiguous: bool = False,
  6592. plate_id: int | None = None,
  6593. run_started_at: datetime | None | object = _ANY_RUN,
  6594. run_id: int | None = None,
  6595. ) -> bool:
  6596. """Download and attach the one video that belongs to this print.
  6597. A candidate is any file absent from the print-start baseline. More than one
  6598. can qualify when a previous print's video landed late, after this print's
  6599. baseline was taken — those are filtered out by name, because they are
  6600. already attached to another archive. Sorting the candidates instead would
  6601. mean sorting on mtime or on the filename timestamp, both of which come from
  6602. the printer's unsynced clock.
  6603. Returns True once a video is attached. The printer's copy is deleted only
  6604. after the attach succeeds on bytes whose length matched the listing.
  6605. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  6606. already seen this exact listing — the poll runs for many rounds and only the
  6607. rounds where something changed are worth an INFO line.
  6608. """
  6609. from backend.app.services.bambu_ftp import (
  6610. DownloadDeadlineExceeded,
  6611. delete_archived_timelapse,
  6612. download_file_bytes_async,
  6613. remote_file_settled,
  6614. )
  6615. speak = logger.debug if quiet else logger.info
  6616. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  6617. if not new_files:
  6618. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  6619. return False
  6620. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  6621. if not candidates:
  6622. speak(
  6623. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  6624. attempt,
  6625. len(new_files),
  6626. )
  6627. return False
  6628. if len(candidates) > 1:
  6629. if require_unambiguous:
  6630. # The baseline is not evidence -- it was taken off a card that could
  6631. # not be read -- so "new since the baseline" does not narrow these
  6632. # down at all. Taking the first would attach an arbitrary video to
  6633. # this print and then delete it from the printer.
  6634. logger.warning(
  6635. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  6636. "leaving all of them on the printer for manual selection",
  6637. attempt,
  6638. len(candidates),
  6639. ", ".join(str(f.get("name")) for f in candidates),
  6640. )
  6641. return False
  6642. logger.warning(
  6643. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  6644. "the rest stay on the printer for manual selection",
  6645. attempt,
  6646. len(candidates),
  6647. ", ".join(str(f.get("name")) for f in candidates),
  6648. )
  6649. target = candidates[0]
  6650. file_name = str(target.get("name") or "") # every listed entry has one
  6651. remote_path = target.get("path") or f"/timelapse/{file_name}"
  6652. logger.info(
  6653. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  6654. attempt,
  6655. file_name,
  6656. archive_id,
  6657. )
  6658. # The listing always carries a size (`list_files` skips entries it can't
  6659. # parse), but read it explicitly: the delete below is destructive and must
  6660. # depend on a size we actually had, not on one we hoped was there.
  6661. expected_size = target.get("size")
  6662. try:
  6663. timelapse_data = await download_file_bytes_async(
  6664. printer.ip_address,
  6665. printer.access_code,
  6666. remote_path,
  6667. printer_model=printer.model,
  6668. expected_size=expected_size,
  6669. )
  6670. except DownloadDeadlineExceeded:
  6671. # Too slow for its size this round; the printer keeps its copy.
  6672. timelapse_data = None
  6673. if not timelapse_data:
  6674. # Short or failed transfer. The printer keeps its copy, so the next
  6675. # round can try again — which is exactly why the delete below is
  6676. # gated on a verified download.
  6677. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  6678. return False
  6679. # The length check above proves we got what the listing said, not that the
  6680. # printer had finished writing. A video still being written can be listed
  6681. # short, served short, and pass — so confirm it has stopped growing before
  6682. # committing to it and deleting the original (#2704).
  6683. if not await remote_file_settled(
  6684. printer.ip_address,
  6685. printer.access_code,
  6686. remote_path,
  6687. len(timelapse_data),
  6688. printer_model=printer.model,
  6689. ):
  6690. return False
  6691. # Write phase: attach in a fresh short-lived session. The download took a
  6692. # while: by now the archive may have its video, or be printing again for a
  6693. # newer run, whose video this is not. Then nothing is attached or deleted,
  6694. # and the poll ends (True).
  6695. async with async_session() as db:
  6696. service = ArchiveService(db)
  6697. if run_id is not None or run_started_at is not _ANY_RUN:
  6698. current = await service.get_archive(archive_id)
  6699. started = None if run_started_at is _ANY_RUN else cast("datetime | None", run_started_at)
  6700. if current is None or not await _timelapse_still_wanted(db, current, run_id, started):
  6701. logger.info(
  6702. "[TIMELAPSE] Archive %s moved on during the download (video attached or printing again); "
  6703. "%s stays on the printer",
  6704. archive_id,
  6705. file_name,
  6706. )
  6707. return True
  6708. success = await service.attach_timelapse(
  6709. archive_id, timelapse_data, file_name, plate_id=plate_id, run_id=run_id
  6710. )
  6711. if not success:
  6712. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  6713. return False
  6714. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  6715. await delete_archived_timelapse(
  6716. printer.ip_address,
  6717. printer.access_code,
  6718. remote_path,
  6719. verified=expected_size is not None,
  6720. printer_model=printer.model,
  6721. printer_name=printer.name,
  6722. )
  6723. return True
  6724. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  6725. # module-level so tests can monkeypatch them down to ~0 without timing out.
  6726. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  6727. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  6728. # How long the *background* upgrade keeps waiting after the notification has
  6729. # already gone out (#2704 follow-up). The short bound above exists so a slow
  6730. # printer can't hold up the print-complete notification; this one exists so the
  6731. # archive still ends up with the better frame afterwards.
  6732. #
  6733. # Measured across 261 attaches in the support bundles, the video lands a median
  6734. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  6735. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  6736. # was 546s. Every other model was inside 26s. The long budget is therefore
  6737. # almost entirely for P1-series users; on everything else the short wait already
  6738. # wins and this task never runs.
  6739. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  6740. async def _capture_finish_photo_from_timelapse(
  6741. archive_id: int,
  6742. archive_dir: Path,
  6743. timeout: float | None = None,
  6744. rotation: int = 0,
  6745. run_id: int | None = None,
  6746. ) -> tuple[str | None, bool]:
  6747. """Wait for the per-print timelapse to land on the archive and extract its
  6748. last frame as the finish photo (#1397).
  6749. Bambu firmware stops timelapse recording after the toolhead parks but
  6750. before the bed-drop end-gcode runs, so the last frame frames the finished
  6751. print correctly. A live camera grab at gcode_state=FINISH captures the
  6752. bed already lowered.
  6753. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  6754. ``archive.timelapse_path`` when the file lands. This function polls for
  6755. that field.
  6756. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  6757. the wait ran out with no video on the archive yet — i.e. the video may
  6758. still be coming and a later attempt could succeed. It is False when the
  6759. video landed (whether or not extraction worked), because in that case
  6760. waiting longer changes nothing. The caller uses that to decide between
  6761. falling back permanently and scheduling a background upgrade.
  6762. ``rotation`` is the printer's camera_rotation, applied to the extracted
  6763. still (#2708) so this source agrees with every other finish-photo source.
  6764. The archived video itself is the printer's own file and is left alone —
  6765. rotating it would mean re-encoding it.
  6766. ``run_id`` is the print that ended: its own video is the one waited for,
  6767. not the archive's, which can be another plate's.
  6768. """
  6769. import uuid
  6770. from backend.app.models.archive import PrintArchive
  6771. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  6772. from backend.app.services.print_log import run_of
  6773. logger = logging.getLogger(__name__)
  6774. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  6775. deadline = asyncio.get_event_loop().time() + budget
  6776. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  6777. while True:
  6778. async with async_session() as db:
  6779. if run_id is not None:
  6780. run = await run_of(db, archive_id, run_id)
  6781. timelapse_relpath = run.timelapse_path if run else None
  6782. else:
  6783. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6784. archive = result.scalar_one_or_none()
  6785. timelapse_relpath = archive.timelapse_path if archive else None
  6786. if timelapse_relpath:
  6787. video_path = app_settings.base_dir / timelapse_relpath
  6788. if video_path.exists() and video_path.stat().st_size > 0:
  6789. photos_dir = archive_dir / "photos"
  6790. photos_dir.mkdir(parents=True, exist_ok=True)
  6791. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6792. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6793. output_path = photos_dir / filename
  6794. if await extract_video_last_frame(video_path, output_path):
  6795. await apply_camera_rotation_to_file(output_path, rotation, logger)
  6796. logger.info(
  6797. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  6798. video_path.name,
  6799. archive_id,
  6800. )
  6801. return filename, False
  6802. logger.warning(
  6803. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  6804. video_path.name,
  6805. archive_id,
  6806. )
  6807. return None, False
  6808. if asyncio.get_event_loop().time() >= deadline:
  6809. logger.info(
  6810. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  6811. archive_id,
  6812. budget,
  6813. )
  6814. return None, True
  6815. await asyncio.sleep(poll_interval)
  6816. async def _upgrade_finish_photo_from_timelapse(
  6817. archive_id: int, archive_dir: Path, rotation: int = 0, run_id: int | None = None
  6818. ) -> None:
  6819. """Add the timelapse's last frame to an archive after the fact (#2704).
  6820. The print-complete notification waits only ~60s for the video, because
  6821. holding a notification for minutes is worse than sending it with a live
  6822. camera grab. On a P1-series printer the video often lands well after that,
  6823. so the archive used to be stuck with the live grab — which is taken at
  6824. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  6825. the worse photo of the two.
  6826. This keeps waiting in the background and, when the video arrives, extracts
  6827. the frame and puts it *first* in the archive's photo list, so opening the
  6828. gallery shows it. The live grab is deliberately kept: the notification that
  6829. already went out links to that exact file, and deleting it would leave a
  6830. broken image in Discord or Telegram. ``run_id`` is the print it is for,
  6831. whose list leads with it too.
  6832. """
  6833. from backend.app.services.print_log import add_run_photo, run_of
  6834. logger = logging.getLogger(__name__)
  6835. filename, _ = await _capture_finish_photo_from_timelapse(
  6836. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation, run_id=run_id
  6837. )
  6838. if not filename:
  6839. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  6840. return
  6841. try:
  6842. async with async_session() as db:
  6843. from backend.app.models.archive import PrintArchive
  6844. archive = await db.get(PrintArchive, archive_id)
  6845. if archive is None:
  6846. return
  6847. photos = list(archive.photos or [])
  6848. if filename in photos:
  6849. return
  6850. # Front of the list: PhotoGalleryModal opens at index 0.
  6851. archive.photos = [filename, *photos]
  6852. add_run_photo(await run_of(db, archive_id, run_id) if run_id is not None else None, filename, first=True)
  6853. await db.commit()
  6854. except Exception as e:
  6855. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  6856. return
  6857. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  6858. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  6859. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  6860. """Put the filament-attribution context back after a restart mid-print.
  6861. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  6862. both die with the process. The print keeps running, so at completion the
  6863. tracker would fall back to whatever the printer reports *now* — and AMS
  6864. filament backup makes "now" the substitute tray, charging the whole print
  6865. to the spool that only finished it.
  6866. The persisted row is only trusted when its print name still matches what
  6867. the printer says it is running: a row left behind by a completion we never
  6868. saw must not attach itself to the next print.
  6869. """
  6870. try:
  6871. from backend.app.api.routes.settings import get_setting
  6872. from backend.app.services.usage_tracker import (
  6873. clear_persisted_session,
  6874. get_persisted_ams_mapping,
  6875. get_persisted_print_name,
  6876. get_persisted_spool_change_log,
  6877. restore_session,
  6878. )
  6879. persisted_name = await get_persisted_print_name(db, printer_id)
  6880. current_name = (state.subtask_name or "").strip()
  6881. if persisted_name and current_name and persisted_name.strip() != current_name:
  6882. logger.info(
  6883. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  6884. printer_id,
  6885. persisted_name,
  6886. current_name,
  6887. )
  6888. await clear_persisted_session(db, printer_id)
  6889. # Fall through to seeding: the print on the printer is real, it just
  6890. # isn't the one the row described.
  6891. persisted_log = None
  6892. else:
  6893. # Spoolman users get the tray-change log back but no in-memory
  6894. # session — see ``on_print_start`` on why that dict is load-bearing
  6895. # for the remain%-sync guard.
  6896. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6897. persisted_log = await restore_session(
  6898. db,
  6899. printer_id,
  6900. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  6901. )
  6902. # The slot pills (#1762) read the mapping captured from the print
  6903. # command, which dies with the process as well. One this process
  6904. # has captured since is newer.
  6905. if state.print_ams_mapping is None:
  6906. state.print_ams_mapping = await get_persisted_ams_mapping(db, printer_id)
  6907. # Spools swapped on a tray before the restart (#3325); anything this
  6908. # process has recorded since goes after them.
  6909. persisted_swaps = await get_persisted_spool_change_log(db, printer_id)
  6910. if persisted_swaps:
  6911. seen = getattr(state, "spool_change_log", None) or []
  6912. state.spool_change_log = persisted_swaps + [item for item in seen if item not in persisted_swaps]
  6913. if persisted_log:
  6914. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  6915. # Anything this process already observed goes after the persisted
  6916. # history — the log is ordered by layer, and a fresh process can
  6917. # only have seen changes from later in the print.
  6918. for entry in state.tray_change_log or []:
  6919. if tuple(entry) not in restored:
  6920. restored.append(tuple(entry))
  6921. state.tray_change_log = restored
  6922. tray_now = state.tray_now
  6923. if 0 <= tray_now <= 254:
  6924. if not state.tray_change_log:
  6925. # No persisted history — a print that started before this build,
  6926. # or before the row existed. Seed with the tray feeding right
  6927. # now so the remainder of the print is at least attributable to
  6928. # the right spool.
  6929. state.tray_change_log = [(tray_now, state.layer_num)]
  6930. logger.info(
  6931. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  6932. printer_id,
  6933. tray_now,
  6934. state.layer_num,
  6935. )
  6936. # The tray handler updates ``last_loaded_tray`` on every push
  6937. # regardless of whether it logged a change, so re-align it to avoid
  6938. # a duplicate entry on the next push. Only ever with a real tray:
  6939. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  6940. # 255" fallback, and writing 255 into it would defeat that.
  6941. state.last_loaded_tray = tray_now
  6942. except Exception:
  6943. # Never let attribution recovery cost the caller its timelapse
  6944. # baseline — that capture has to happen before the printer uploads
  6945. # the in-flight MP4 and there is no second chance at it.
  6946. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  6947. async def on_print_running_observed(printer_id: int, data: dict):
  6948. """Restart-recovery for a print that started before Bambuddy came up.
  6949. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  6950. after Bambuddy startup (#1304 guard, prevents duplicate archive
  6951. creation). This hook restores the persisted archive into ``_active_prints``
  6952. and captures the timelapse baseline that normally hangs off print start.
  6953. Fires once per session, in lieu of on_print_start when restart-recovery
  6954. kicks in. The printer doesn't upload the timelapse until after PRINT
  6955. COMPLETE, so a baseline captured any time during the print is still
  6956. pre-upload.
  6957. """
  6958. logger = logging.getLogger(__name__)
  6959. async with async_session() as db:
  6960. from backend.app.models.printer import Printer
  6961. state = printer_manager.get_status(printer_id)
  6962. if state is not None:
  6963. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  6964. if authorization is True:
  6965. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  6966. await _restore_usage_tracking_session(printer_id, state, db, logger)
  6967. await _restore_printable_objects(printer_id, state, db, logger)
  6968. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6969. printer = result.scalar_one_or_none()
  6970. if not printer:
  6971. logger.warning(
  6972. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  6973. printer_id,
  6974. )
  6975. return
  6976. # Avoid double-capture: ownership reconciliation above must still run when
  6977. # a baseline already exists, but the camera work itself is one-shot.
  6978. if printer_id in _timelapse_baselines:
  6979. logger.debug(
  6980. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  6981. printer_id,
  6982. )
  6983. return
  6984. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  6985. class _RunOfArchive:
  6986. """An archive as one of its runs printed it: the run's job id, start and
  6987. plate, the rest the archive's. What the reconcile judges and closes."""
  6988. def __init__(self, archive, run):
  6989. self._archive = archive
  6990. self.subtask_id = run.subtask_id
  6991. self.started_at = run.started_at
  6992. self.plate_id = run.plate_id if run.plate_id is not None else archive.plate_id
  6993. def __getattr__(self, name):
  6994. return getattr(self._archive, name)
  6995. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  6996. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  6997. against the printer's current MQTT state.
  6998. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  6999. COMPLETE events, typically a print finishing during an MQTT disconnect
  7000. window followed by a smart-plug power cycle):
  7001. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  7002. provably not running anymore — only branch that should fire under
  7003. normal disconnect-then-reconnect timing.
  7004. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  7005. firmware mints a fresh ``subtask_id`` for each print, including the
  7006. ghost replay it runs after a power cycle from a leftover SD file —
  7007. so a mismatch unambiguously means the in-DB archive is no longer
  7008. the print on the printer.
  7009. 3. Printer is running but ``subtask_name`` is empty. The printer
  7010. doesn't know what it's running; the archive's reference to it is
  7011. already broken.
  7012. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  7013. with matching subtask_id+subtask_name is left alone. The cost of a false
  7014. positive is a print closed while it still runs: the reconcile takes its
  7015. ``_active_prints`` entry and the archive is no longer ``printing``, so
  7016. the real PRINT COMPLETE later finds no archive to close (#1679). The
  7017. cost of a false negative is the ghost-print loop in #1542. What the
  7018. archive is closed as is ``_reconciled_outcome``'s call.
  7019. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  7020. MQTT has connected but the first ``push_status`` response hasn't been
  7021. applied yet — ``PrinterState`` is sitting on its construction defaults.
  7022. The reconcile caller in ``on_printer_status_change`` is already gated
  7023. on a real ``state.state``, so in normal operation this branch is
  7024. unreachable; it's kept as belt-and-braces for future callers and for
  7025. the narrow window where a partial state update could arrive
  7026. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  7027. ``not stale`` on degenerate input is strictly conservative: a real
  7028. stale archive will still be caught by the next push_status arriving
  7029. with terminal state.
  7030. """
  7031. current_state = (state.state or "").upper()
  7032. if current_state in ("", "UNKNOWN"):
  7033. # No real push_status yet — PrinterState defaults are not evidence.
  7034. return False, ""
  7035. if current_state in ("IDLE", "FINISH", "FAILED"):
  7036. return True, f"printer state {current_state}"
  7037. # Below here the printer is in a running / pre-running state (RUNNING /
  7038. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  7039. current_subtask_id = (state.subtask_id or "").strip()
  7040. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  7041. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  7042. current_subtask_name = (state.subtask_name or "").strip()
  7043. if not current_subtask_name:
  7044. return True, "printer subtask_name empty"
  7045. return False, ""
  7046. async def prime_kprofile_table(printer_id: int) -> int:
  7047. """Read the printer's calibration table once per connection.
  7048. The AMS slot card shows a K value per slot (#2854). On the printers whose
  7049. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  7050. report ``cali_idx`` and nothing else -- that number can only come from
  7051. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  7052. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  7053. backup, or the printer answering a query BambuStudio made on the report
  7054. topic we share. A Bambuddy that nobody visited showed a card with no K
  7055. values at all.
  7056. Only the diameters actually fitted are asked for, which is one request on a
  7057. single-nozzle printer and two on a dual. Probing the four sizes blind is
  7058. what the backup does, and it is both wasteful and the thing that used to
  7059. blank the table.
  7060. Returns the number of nozzles whose table was read.
  7061. """
  7062. client = printer_manager.get_client(printer_id)
  7063. state = printer_manager.get_status(printer_id)
  7064. if client is None or state is None or not state.connected:
  7065. return 0
  7066. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  7067. # ask once, and both entries are empty until the first push_status lands.
  7068. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  7069. if not diameters:
  7070. logging.getLogger(__name__).debug(
  7071. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  7072. printer_id,
  7073. )
  7074. return 0
  7075. primed = 0
  7076. for diameter in diameters:
  7077. try:
  7078. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  7079. except Exception as exc: # noqa: BLE001
  7080. # A printer that won't answer costs the card its K values, nothing
  7081. # more — never the connection this runs on the back of.
  7082. logging.getLogger(__name__).warning(
  7083. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  7084. )
  7085. continue
  7086. primed += 1
  7087. logging.getLogger(__name__).info(
  7088. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  7089. )
  7090. return primed
  7091. def _sd_files_in_use(state) -> set[str]:
  7092. """Names of the SD-card files the printer may be printing right now (#3009).
  7093. The post-print cleanup works out what to delete from the finished archive,
  7094. not from the printer. When reconciliation closes an old archive because the
  7095. printer has moved on to a new job, and that job is the same file reprinted
  7096. from the printer's screen, the cleanup would delete the file mid-print.
  7097. Empty unless the printer is busy: on an ordinary completion the state is
  7098. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  7099. name, a path or a URL depending on firmware, and some report only the
  7100. plate's G-code, so the job name is matched as well, in the same spellings
  7101. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  7102. ignores case.
  7103. """
  7104. def _text(value) -> str:
  7105. return value.strip() if isinstance(value, str) else ""
  7106. if state is None:
  7107. return set()
  7108. current_state = _text(getattr(state, "state", None)).upper()
  7109. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  7110. return set()
  7111. in_use: set[str] = set()
  7112. gcode_file = _text(getattr(state, "gcode_file", None))
  7113. if gcode_file:
  7114. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  7115. # both legal in a file name, and raises on some inputs.
  7116. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  7117. if name:
  7118. in_use.add(name.lower())
  7119. subtask_name = _text(getattr(state, "subtask_name", None))
  7120. if subtask_name:
  7121. for name in (subtask_name, subtask_name.replace(" ", "_")):
  7122. for ext in (".3mf", ".gcode"):
  7123. in_use.add(f"{name}{ext}".lower())
  7124. return in_use
  7125. def _reconciled_outcome(archive, state) -> str:
  7126. """What a stale archive is closed as at reconnect (#3310).
  7127. A print that ends while Bambuddy restarts is never seen to end: the new
  7128. MQTT client's first status is already FINISH, which is not a transition.
  7129. The printer keeps reporting the finished job's ``subtask_id`` until the
  7130. next print, so a matching id proves the FINISH or FAILED is this
  7131. archive's. Anything else -- IDLE, another job, an id of "0" (a print
  7132. started outside the cloud) or none -- says only that the print is over,
  7133. not how, and stays ``aborted``.
  7134. """
  7135. current_state = (state.state or "").upper()
  7136. if current_state not in ("FINISH", "FAILED"):
  7137. return "aborted"
  7138. archive_id = (archive.subtask_id or "").strip()
  7139. current_id = str(state.subtask_id or "").strip()
  7140. if archive_id in ("", "0") or archive_id != current_id:
  7141. return "aborted"
  7142. return "completed" if current_state == "FINISH" else "failed"
  7143. def _reconciled_end_time(archive, now: datetime, plate_id: int | None = None) -> datetime | None:
  7144. """When a print reconciled as completed most likely ended, or None (#3310).
  7145. The printer does not say when it finished, and the reconnect can be hours
  7146. later. Its start plus the slicer's estimate for the plate it printed,
  7147. never later than now, is the best guess; None when either is missing,
  7148. and the run then keeps no duration, as an aborted one does.
  7149. ``plate_id`` is the plate this run printed, from its queue job: a reprint
  7150. of another plate reuses the archive without changing ``archive.plate_id``.
  7151. """
  7152. started = archive.started_at
  7153. if not started:
  7154. return None
  7155. if started.tzinfo is None:
  7156. started = started.replace(tzinfo=timezone.utc)
  7157. plate = plate_id if plate_id is not None else archive.plate_id
  7158. estimate = None
  7159. if archive.file_path:
  7160. from backend.app.utils.threemf_tools import extract_print_time_from_3mf
  7161. full_path = (
  7162. app_settings.base_dir / archive.file_path
  7163. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7164. try:
  7165. estimate = extract_print_time_from_3mf(full_path, plate)
  7166. except Exception as exc: # noqa: BLE001
  7167. logging.getLogger(__name__).debug(
  7168. "Plate estimate for reconciled archive %s unreadable: %s", archive.id, exc
  7169. )
  7170. if plate is None and estimate != archive.print_time_seconds:
  7171. # Without a plate the first plate's estimate is read. The archive
  7172. # carries the sum over all plates (#1593), so a difference means
  7173. # several plates and no telling which one printed.
  7174. estimate = None
  7175. elif plate is None:
  7176. # Nothing to read the plate from; the archive's own estimate, as for
  7177. # a single-plate file.
  7178. estimate = archive.print_time_seconds
  7179. if not estimate or estimate <= 0:
  7180. return None
  7181. return min(started + timedelta(seconds=int(estimate)), now)
  7182. async def reconcile_stale_active_prints(printer_id: int) -> int:
  7183. """Synthesise ``on_print_complete`` for archives whose print can't be
  7184. running on the printer anymore.
  7185. Called once per MQTT (re)connection (from on_printer_status_change when
  7186. the connected edge flips False → True) and at Bambuddy startup (from
  7187. the FastAPI lifespan). Without this, a print that completes during a
  7188. disconnect window — followed by a smart-plug-driven power cycle — leaves
  7189. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  7190. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  7191. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  7192. power cycle until the operator notices (#1542 follow-up). Reconciliation
  7193. closes the loop by faking the missed PRINT COMPLETE — the existing
  7194. cleanup chain handles SD-file deletion, status updates, usage tracking,
  7195. and notifications.
  7196. The status is ``_reconciled_outcome``'s: ``completed`` or ``failed``
  7197. when the printer still reports the archive's own job as finished or
  7198. failed, ``aborted`` otherwise. Nothing corrects it later: the archive is
  7199. no longer ``printing``, so a later PRINT COMPLETE finds no archive, and
  7200. after a restart the printer's FINISH is not one (#3310).
  7201. Returns the number of archives reconciled.
  7202. """
  7203. state = printer_manager.get_status(printer_id)
  7204. if not state:
  7205. return 0
  7206. # Don't reconcile while disconnected — we'd be making a decision against
  7207. # stale cached state. The connected → reconcile edge handles this.
  7208. if not state.connected:
  7209. return 0
  7210. from backend.app.models.archive import PrintArchive
  7211. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
  7212. reconciled = 0
  7213. async with async_session() as db:
  7214. # The prints on this printer Bambuddy saw start: their runs open here.
  7215. # The archive row is shared by every plate of a file, its printer, job
  7216. # and start the latest start's, so each is judged as its run.
  7217. open_runs = (
  7218. await db.scalars(
  7219. select(PrintLogEntry)
  7220. .where(PrintLogEntry.printer_id == printer_id, PrintLogEntry.status == RUN_OPEN)
  7221. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7222. )
  7223. ).all()
  7224. by_run = {
  7225. archive.id: archive
  7226. for archive in (
  7227. await db.scalars(
  7228. select(PrintArchive).where(
  7229. PrintArchive.id.in_([run.archive_id for run in open_runs if run.archive_id is not None])
  7230. )
  7231. )
  7232. ).all()
  7233. }
  7234. active: list = [_RunOfArchive(by_run[run.archive_id], run) for run in open_runs if run.archive_id in by_run]
  7235. # And as before runs were opened at the start: a printing archive of
  7236. # this printer with no run open anywhere (printing since before).
  7237. archives_with_open_runs = select(PrintLogEntry.archive_id).where(
  7238. PrintLogEntry.status == RUN_OPEN, PrintLogEntry.archive_id.is_not(None)
  7239. )
  7240. result = await db.execute(
  7241. select(PrintArchive)
  7242. .where(
  7243. PrintArchive.printer_id == printer_id,
  7244. PrintArchive.status == "printing",
  7245. PrintArchive.id.not_in(archives_with_open_runs),
  7246. )
  7247. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7248. )
  7249. active.extend(result.scalars().all())
  7250. if not active:
  7251. return 0
  7252. # The plate each run printed, from its queue job (#3310).
  7253. from backend.app.models.print_queue import PrintQueueItem
  7254. async with async_session() as db:
  7255. plate_rows = await db.execute(
  7256. select(PrintQueueItem.archive_id, PrintQueueItem.plate_id).where(
  7257. PrintQueueItem.printer_id == printer_id,
  7258. PrintQueueItem.status == "printing",
  7259. PrintQueueItem.archive_id.in_([a.id for a in active]),
  7260. )
  7261. )
  7262. run_plates = {archive_id: plate for archive_id, plate in plate_rows.all() if plate is not None}
  7263. logger = logging.getLogger(__name__)
  7264. for archive in active:
  7265. is_stale, reason = _is_active_archive_stale(archive, state)
  7266. if not is_stale:
  7267. continue
  7268. logger.info(
  7269. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  7270. printer_id,
  7271. archive.id,
  7272. archive.filename,
  7273. reason,
  7274. )
  7275. # Synthesised payload: minimal fields the on_print_complete chain
  7276. # needs. `_reconciled` marker lets downstream code distinguish this
  7277. # from a real MQTT-driven completion if it ever needs to (e.g. for
  7278. # metrics / debug logging). raw_data is the live printer state so
  7279. # the usage tracker can compare end-of-print remain% against the
  7280. # captured start values.
  7281. outcome = _reconciled_outcome(archive, state)
  7282. payload = {
  7283. "status": outcome,
  7284. "filename": archive.filename,
  7285. "subtask_name": archive.print_name or "",
  7286. "subtask_id": archive.subtask_id or "",
  7287. "raw_data": state.raw_data or {},
  7288. "_reconciled": True,
  7289. }
  7290. if isinstance(archive, _RunOfArchive):
  7291. # The archive it closes, which its names and printer may not find:
  7292. # another printer's plate of it can have started since.
  7293. payload["_reconciled_archive_id"] = archive.id
  7294. if outcome != "aborted":
  7295. # The printer's progress and layer are this job's, so a partial
  7296. # run is charged what it printed rather than nothing.
  7297. if state.progress:
  7298. payload["last_progress"] = state.progress
  7299. if state.layer_num:
  7300. payload["last_layer_num"] = state.layer_num
  7301. if outcome == "failed":
  7302. payload["hms_errors"] = [e.completion_payload() for e in state.hms_errors or []]
  7303. if outcome == "completed":
  7304. ended = _reconciled_end_time(archive, datetime.now(timezone.utc), run_plates.get(archive.id))
  7305. if ended:
  7306. payload["_reconciled_completed_at"] = ended
  7307. try:
  7308. await on_print_complete(printer_id, payload)
  7309. reconciled += 1
  7310. except Exception as e:
  7311. # Catch-all: a reconciliation failure must not block the
  7312. # printer's normal status flow. The archive stays in
  7313. # ``status="printing"`` and the next reconnect retries.
  7314. logger.warning(
  7315. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  7316. archive.id,
  7317. e,
  7318. )
  7319. return reconciled
  7320. # #2547: clearance left between the nozzle and the top of the print when the
  7321. # plate is commanded back into camera framing. The nozzle is parked away from
  7322. # the part by then, so this is belt-and-braces against a max_z_height that
  7323. # under-reports (e.g. a slicer that excludes a final Z hop).
  7324. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  7325. # How far below the restored position to drop the plate again afterwards, so
  7326. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  7327. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  7328. # on machines with less headroom.
  7329. _PLATE_PARK_DROP_MM = 100.0
  7330. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  7331. # this axis, so it is a proven-safe speed for the full travel.
  7332. _PLATE_RESTORE_FEEDRATE = 600
  7333. # Time allowed for the plate to reach the restored position before the camera
  7334. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  7335. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  7336. # How long `_background_finish_photo` waits for this producer. Must cover the
  7337. # settle window plus a worst-case RTSP grab (15s), and stay below the
  7338. # notification path's own photo wait so a slow producer degrades to a
  7339. # photo-less notification rather than a missed one. The chamber light's
  7340. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  7341. # camera_light.MAX_DELAY_SECONDS stays below it.
  7342. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  7343. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  7344. """The ``_active_prints`` keys a finished print may be registered under.
  7345. Matching how they were registered in on_print_start. Shared by
  7346. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  7347. to find the same binding.
  7348. """
  7349. possible_keys = []
  7350. # Try subtask_name variations first (most reliable for matching)
  7351. if subtask_name:
  7352. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  7353. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  7354. possible_keys.append((printer_id, subtask_name))
  7355. # Try filename variations
  7356. if filename:
  7357. # Extract just the filename if it's a path
  7358. fname = filename.split("/")[-1] if "/" in filename else filename
  7359. if fname.endswith(".3mf"):
  7360. possible_keys.append((printer_id, fname))
  7361. elif fname.endswith(".gcode"):
  7362. base_name = fname.rsplit(".", 1)[0]
  7363. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  7364. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7365. possible_keys.append((printer_id, fname))
  7366. else:
  7367. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  7368. possible_keys.append((printer_id, f"{fname}.3mf"))
  7369. possible_keys.append((printer_id, fname))
  7370. # Also try full path versions
  7371. if filename.endswith(".3mf"):
  7372. possible_keys.append((printer_id, filename))
  7373. elif filename.endswith(".gcode"):
  7374. base_name = filename.rsplit(".", 1)[0]
  7375. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7376. possible_keys.append((printer_id, filename))
  7377. else:
  7378. possible_keys.append((printer_id, f"{filename}.3mf"))
  7379. possible_keys.append((printer_id, filename))
  7380. return possible_keys
  7381. def _archive_name_forms(archive) -> set[str]:
  7382. """The names an archive could be echoed back as, in normalised form (#3240).
  7383. Its print name, and its filename with and without the 3MF extension.
  7384. """
  7385. forms = set()
  7386. if archive.print_name:
  7387. forms.add(_normalise_subtask_name(archive.print_name))
  7388. if archive.filename:
  7389. forms.add(_normalise_subtask_name(archive.filename))
  7390. for suffix in (".gcode.3mf", ".3mf"):
  7391. if archive.filename.lower().endswith(suffix):
  7392. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  7393. forms.discard("")
  7394. return forms
  7395. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  7396. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  7397. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  7398. from the plate recorded when the job was dispatched. Neither is touched:
  7399. ``on_print_complete`` pops both, which is why the finish-photo producer
  7400. calls this before its first await, while they are still there.
  7401. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  7402. archive, or that it only knows by a name -- and on any error: the producer
  7403. calls this before the ``try`` that always releases the photo consumer, so
  7404. it must not raise.
  7405. """
  7406. try:
  7407. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  7408. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  7409. if archive_id is None:
  7410. return None, None
  7411. return archive_id, _print_plate_ids.get((printer_id, archive_id))
  7412. except Exception:
  7413. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  7414. return None, None
  7415. async def _max_z_for_current_print(
  7416. printer_id: int,
  7417. data: dict,
  7418. logger,
  7419. archive_id: int | None,
  7420. plate_id: int | None = None,
  7421. ) -> float | None:
  7422. """Height of the print that just finished on ``printer_id``, or None (#2547).
  7423. This number becomes the target of a real Z move, so every step here refuses
  7424. rather than guesses. A height belonging to some *other* print is the one
  7425. failure that could drive the nozzle into the model: 20 mm carried onto a
  7426. 200 mm print would command the plate up through the part.
  7427. Three independent things therefore have to agree before a height is
  7428. returned:
  7429. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  7430. when it started (see ``_bound_print``), never one found by name. A name
  7431. is not an identity: every plate of a multi-plate file shares one, and a
  7432. reprint reuses its archive row, so the newest archive with the right
  7433. name can be another plate of the same file. Support bundles show the
  7434. old name lookup doing exactly that (archive 288 for a print bound to
  7435. 169, 313 layers against 125), stopped only by the layer check below.
  7436. No binding, no move.
  7437. 2. **Identity.** The bound archive's name still has to be the finished
  7438. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  7439. because the printer echoes spaces as underscores (#3240). Exact: not a
  7440. substring, and not the completion check's tolerance for a truncated
  7441. echo.
  7442. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  7443. match the layer count the printer itself reported over MQTT for the print
  7444. that just ended. These come from genuinely different sources, so a
  7445. mismatch means the row is not this print, whatever its name says.
  7446. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  7447. plate of a multi-plate file reuses the archive row without updating its
  7448. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  7449. ``on_print_complete`` may already have flipped the status by the time we
  7450. run.
  7451. """
  7452. subtask_name = (data.get("subtask_name") or "").strip()
  7453. if not subtask_name:
  7454. # Nothing to identify the print by — refuse rather than fall back to
  7455. # "whatever ran last on this printer".
  7456. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  7457. return None
  7458. if archive_id is None:
  7459. logger.info(
  7460. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  7461. printer_id,
  7462. subtask_name,
  7463. )
  7464. return None
  7465. try:
  7466. from backend.app.models.archive import PrintArchive
  7467. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  7468. async with async_session() as db:
  7469. result = await db.execute(
  7470. select(PrintArchive).where(
  7471. PrintArchive.id == archive_id,
  7472. PrintArchive.printer_id == printer_id,
  7473. PrintArchive.status.in_(("printing", "completed")),
  7474. PrintArchive.deleted_at.is_(None),
  7475. )
  7476. )
  7477. archive = result.scalar_one_or_none()
  7478. if archive is None or not archive.file_path:
  7479. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  7480. return None
  7481. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  7482. logger.warning(
  7483. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  7484. printer_id,
  7485. archive_id,
  7486. subtask_name,
  7487. )
  7488. return None
  7489. client = printer_manager.get_client(printer_id)
  7490. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  7491. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  7492. logger.warning(
  7493. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  7494. "— refusing to move the plate on a height that may not be this print's",
  7495. printer_id,
  7496. archive.id,
  7497. archive.total_layers,
  7498. reported_layers,
  7499. )
  7500. return None
  7501. # Stored relative to the data directory, like every other archive path
  7502. # (#3240: this read a `data_dir` setting that does not exist).
  7503. path = app_settings.base_dir / archive.file_path
  7504. plate = plate_id or archive.plate_id or 1
  7505. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  7506. except Exception as e:
  7507. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  7508. return None
  7509. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  7510. """Raise the plate back into camera framing before the finish photo (#2547).
  7511. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  7512. the time ``gcode_state`` reaches FINISH the finished print sits far below
  7513. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  7514. This commands an absolute ``G1 Z`` back to just above the last printed
  7515. layer.
  7516. Absolute, not relative, is the whole safety argument. ``max_z_height +
  7517. clearance`` is a height the toolhead was physically at seconds earlier, so
  7518. it is inside the travel limits by construction and leaves the nozzle above
  7519. the part. It is also unambiguous across model families: Z is the
  7520. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  7521. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  7522. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  7523. (#2579).
  7524. Returns True if the move was sent and waited out, False if it was skipped.
  7525. """
  7526. client = printer_manager.get_client(printer_id)
  7527. if client is None:
  7528. return False
  7529. # Re-read state immediately before commanding motion. If the queue has
  7530. # already started the next print, the printer is no longer ours to move.
  7531. state = getattr(client, "state", None)
  7532. if state is None or state.state != "FINISH":
  7533. logger.info(
  7534. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  7535. printer_id,
  7536. getattr(state, "state", "unknown"),
  7537. )
  7538. return False
  7539. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  7540. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  7541. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  7542. return False
  7543. logger.info(
  7544. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  7545. printer_id,
  7546. target_z,
  7547. max_z_height,
  7548. _PLATE_RESTORE_CLEARANCE_MM,
  7549. _PLATE_RESTORE_SETTLE_SECONDS,
  7550. )
  7551. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  7552. return True
  7553. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  7554. """Drop the plate again after the finish photo (#2547).
  7555. Without this the user walks up to a finished print sitting just under the
  7556. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  7557. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  7558. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  7559. print homes anyway.
  7560. """
  7561. client = printer_manager.get_client(printer_id)
  7562. state = getattr(client, "state", None) if client else None
  7563. if client is None or state is None or state.state != "FINISH":
  7564. return
  7565. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  7566. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  7567. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  7568. """True if a queue item is about to take this printer (#2547).
  7569. The scheduler dispatches the next job the moment a print completes, and a
  7570. plate move interleaved with a print start is not a race worth having. The
  7571. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  7572. this window; this closes the head of it.
  7573. """
  7574. try:
  7575. from backend.app.models.print_queue import PrintQueueItem
  7576. async with async_session() as db:
  7577. result = await db.execute(
  7578. select(PrintQueueItem.id)
  7579. .where(
  7580. PrintQueueItem.printer_id == printer_id,
  7581. PrintQueueItem.status.in_(("pending", "printing")),
  7582. )
  7583. .limit(1)
  7584. )
  7585. return result.scalar_one_or_none() is not None
  7586. except Exception as e:
  7587. # Fail closed: if we can't tell, don't move the plate.
  7588. logging.getLogger(__name__).debug(
  7589. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  7590. )
  7591. return True
  7592. async def on_finish_photo_moment(printer_id: int, data: dict):
  7593. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  7594. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  7595. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  7596. fallback for prints that skip stage 22 (cancel, external-spool-only,
  7597. HMS halt, firmware variants). Grabs one frame via the same
  7598. external-camera / RTSP path the post-completion fallback uses, stores
  7599. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  7600. ``_background_finish_photo`` consume the cached bytes when it runs.
  7601. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  7602. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  7603. set to Smooth (#1721). No force-on now means the user's explicit
  7604. timelapse=off in the slicer send dialog is respected.
  7605. """
  7606. logger = logging.getLogger(__name__)
  7607. trigger = data.get("trigger", "unknown")
  7608. timelapse_was_active = bool(data.get("timelapse_was_active"))
  7609. logger.info(
  7610. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  7611. printer_id,
  7612. trigger,
  7613. timelapse_was_active,
  7614. )
  7615. # If a timelapse is actively recording, skip the pre-capture — the
  7616. # post-completion path will extract the last frame from the recorded
  7617. # video, which still provides the best framing (toolhead parked,
  7618. # before bed drop) without the per-layer parking side effects.
  7619. if timelapse_was_active:
  7620. logger.info(
  7621. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  7622. printer_id,
  7623. )
  7624. return
  7625. # #1790: register the producer-done event BEFORE the first await so the
  7626. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  7627. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  7628. # The `finally` below guarantees `set()` runs on every exit, including
  7629. # early returns and exceptions, so the consumer's bounded wait can't hang.
  7630. producer_done = asyncio.Event()
  7631. _stage22_finish_in_flight[printer_id] = producer_done
  7632. # #3240: also before the first await. On the FINISH-state path
  7633. # `on_print_complete` is dispatched right behind us and pops both the
  7634. # print's archive binding and its plate; read here, they are still there.
  7635. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  7636. # #2547: set once the plate has actually been raised, and read by the
  7637. # `finally` below. Declared out here so a failure anywhere after the move —
  7638. # a camera timeout, a DB error — still lowers the plate again.
  7639. restore_max_z: float | None = None
  7640. try:
  7641. async with async_session() as db:
  7642. from backend.app.api.routes.settings import get_setting
  7643. from backend.app.models.printer import Printer
  7644. capture_setting = await get_setting(db, "capture_finish_photo")
  7645. if capture_setting is not None and capture_setting.lower() != "true":
  7646. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  7647. return
  7648. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7649. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  7650. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7651. printer = result.scalar_one_or_none()
  7652. if printer is None:
  7653. logger.warning(
  7654. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  7655. printer_id,
  7656. )
  7657. return
  7658. frame_bytes: bytes | None = None
  7659. # #2708: the banked frame arrives already rotated — it comes from
  7660. # `_capture_snapshot_for_notification`, which rotates before returning.
  7661. # Every other source below is a raw grab. Tracking which lets us store
  7662. # exactly one rotation in `_stage22_finish_frames` either way.
  7663. frame_already_rotated = False
  7664. # On the FINISH-state path the End G-code has already run, and two very
  7665. # different situations arrive here needing opposite answers.
  7666. #
  7667. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  7668. # snippet may have ejected the plate — the scene in front of the camera
  7669. # is no longer the finished print, and no amount of moving the plate
  7670. # brings it back. Use the banked in-print frame instead.
  7671. #
  7672. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  7673. # than the camera frames well, and the toolhead is parked out of the
  7674. # way. That is the *best* moment available on firmware that never emits
  7675. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  7676. # back. Preferring the bank here unconditionally, as this code used to,
  7677. # is what shipped a mid-print photo with the toolhead over the part.
  7678. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  7679. banked = _inprint_frame_bank.get(printer_id)
  7680. if banked:
  7681. frame_bytes = banked
  7682. frame_already_rotated = True
  7683. logger.info(
  7684. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  7685. "frame (%d bytes) instead of a post-swap live grab",
  7686. len(banked),
  7687. )
  7688. else:
  7689. logger.warning(
  7690. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  7691. "in-print bank is empty — falling back to a live grab, which may show a "
  7692. "swapped or empty plate",
  7693. printer_id,
  7694. )
  7695. # `restore_max_z` is set only once the plate is actually up, because the
  7696. # `finally` reads it to decide whether it owes a move back down.
  7697. #
  7698. # Never on a print whose End G-code Bambuddy injected, even when the bank
  7699. # came up empty above: that machine may have just ejected its plate, and
  7700. # driving Z into whatever a swap mechanism is doing is not a risk worth
  7701. # taking for a photo of a bed we already know may be bare.
  7702. if (
  7703. frame_bytes is None
  7704. and trigger == "finish_state"
  7705. and restore_plate_enabled
  7706. and not print_dispatch_context.end_gcode_injected(printer_id)
  7707. ):
  7708. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  7709. if wants_restore is None:
  7710. logger.info(
  7711. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  7712. printer_id,
  7713. )
  7714. elif await _plate_restore_is_blocked_by_queue(printer_id):
  7715. logger.info(
  7716. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  7717. printer_id,
  7718. )
  7719. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  7720. restore_max_z = wants_restore
  7721. # Chamber light for the live capture below (#1655). The banked frame
  7722. # above was taken without it, like every in-print bank.
  7723. async with camera_light(printer if frame_bytes is None else None):
  7724. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  7725. from backend.app.api.routes.camera import live_frame_for_capture
  7726. from backend.app.services.external_camera import capture_frame
  7727. # #2707: this used to collide with the live view and fail, which is
  7728. # how finish-photo notifications went out with no image attached.
  7729. # Leaving frame_bytes None keeps the rest of the fallback chain.
  7730. defer, buffered = live_frame_for_capture(printer_id)
  7731. if defer:
  7732. frame_bytes = buffered
  7733. else:
  7734. frame_bytes = await capture_frame(
  7735. printer.external_camera_url,
  7736. printer.external_camera_type or "mjpeg",
  7737. snapshot_url=printer.external_camera_snapshot_url,
  7738. )
  7739. if frame_bytes:
  7740. logger.info(
  7741. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  7742. len(frame_bytes),
  7743. )
  7744. elif frame_bytes is None:
  7745. from backend.app.api.routes.camera import get_buffered_frame
  7746. buffered = get_buffered_frame(printer_id)
  7747. if buffered:
  7748. frame_bytes = buffered
  7749. logger.info(
  7750. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  7751. len(frame_bytes),
  7752. )
  7753. else:
  7754. from backend.app.services.camera import capture_camera_frame_bytes
  7755. frame_bytes = await capture_camera_frame_bytes(
  7756. ip_address=printer.ip_address,
  7757. access_code=printer.access_code,
  7758. model=printer.model,
  7759. timeout=15,
  7760. )
  7761. if frame_bytes:
  7762. logger.info(
  7763. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  7764. len(frame_bytes),
  7765. )
  7766. if frame_bytes:
  7767. if not frame_already_rotated:
  7768. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  7769. _stage22_finish_frames[printer_id] = frame_bytes
  7770. else:
  7771. logger.warning(
  7772. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  7773. printer_id,
  7774. )
  7775. except Exception as e:
  7776. logger.warning(
  7777. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  7778. printer_id,
  7779. e,
  7780. )
  7781. finally:
  7782. # #2547: we raised the plate, so we own lowering it — including when the
  7783. # capture above failed or threw partway through.
  7784. if restore_max_z is not None:
  7785. try:
  7786. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  7787. except Exception as e:
  7788. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7789. # #1790: always unblock the consumer's bounded wait — whether we stored
  7790. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  7791. # dict entry by the consumer doesn't affect signalling.
  7792. producer_done.set()
  7793. def _subtask_name_from_filename(filename: str) -> str:
  7794. """Recover the subtask name a print command would have carried for *filename*.
  7795. The dispatcher derives the printer-facing subtask name from the archive's
  7796. file name, so stripping the extensions back off gives the value MQTT echoes
  7797. on completion. Only the two extensions Bambuddy actually stores are removed,
  7798. and in the order they nest (``.gcode.3mf``), so a model whose own name
  7799. contains a dot -- ``My.Model.3mf`` -- keeps it.
  7800. """
  7801. name = PurePosixPath(filename).name
  7802. for suffix in (".3mf", ".gcode"):
  7803. if name.lower().endswith(suffix):
  7804. name = name[: -len(suffix)]
  7805. return name
  7806. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  7807. """Whether the subtask name is the printed 3MF's own file name.
  7808. A print started from the printer's screen reports the same full name, with
  7809. its extension, as both subtask and file (#3009). A dispatched print reports
  7810. a bare subtask name; one that merely ends in ".3mf" can be a model named
  7811. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  7812. """
  7813. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  7814. return False
  7815. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  7816. # How the printer marks a subtask name it had to cut short. Observed on real
  7817. # hardware at ~100 characters, but the cut-off is not a fixed character count
  7818. # (a name with multibyte characters came back at 98), so match the marker
  7819. # rather than a length.
  7820. _SUBTASK_TRUNCATION_MARKER = "..."
  7821. def _normalise_subtask_name(name: str) -> str:
  7822. """Canonical form for comparing a dispatched name against MQTT's echo.
  7823. The printer does not echo the name back verbatim: it substitutes
  7824. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  7825. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  7826. The 3MF lookup in this module has always known that -- it builds
  7827. space-to-underscore variants of every candidate filename, and its
  7828. directory search normalises both sides before comparing. This exists so
  7829. the completion check reads the same rule from the same place instead of
  7830. growing its own, which is exactly how it came to disagree (#2829).
  7831. A space at either end is substituted too: ``Part .gcode.3mf`` is
  7832. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  7833. are dropped after the substitution so both sides agree (#3241).
  7834. """
  7835. return name.strip().replace(" ", "_").strip("_").casefold()
  7836. def _3mf_files_for_print(paths: list[str], search_term: str) -> list[str]:
  7837. """The 3MF files of the printer's folder listings that are this print's.
  7838. A file of the print's own name wins, in whichever folder. Only without one
  7839. is a file that merely contains the name taken, and then only when it is
  7840. the one such file: "Cube_large.3mf" is not "Cube"'s file, and of several
  7841. candidates none can be told apart. Paths keep the listings' order.
  7842. """
  7843. threemf = [path for path in paths if path.lower().endswith(".3mf")]
  7844. exact = [path for path in threemf if _subtask_names_match(_subtask_name_from_filename(path), search_term)]
  7845. if exact:
  7846. return exact
  7847. term = _normalise_subtask_name(search_term)
  7848. partial = [path for path in threemf if term in _normalise_subtask_name(PurePosixPath(path).name)]
  7849. if len(partial) > 1:
  7850. logging.getLogger(__name__).info(
  7851. "Several 3MF files contain %r and none is named for it: %s", search_term, partial
  7852. )
  7853. return []
  7854. return partial
  7855. def _subtask_names_match(expected: str, observed: str) -> bool:
  7856. """Whether two subtask names describe the same print.
  7857. Beyond the space/underscore substitution, the printer truncates long names
  7858. and marks the cut with ``...``. A truncated echo has to count as a match or
  7859. every print with a long name strands its queue item the same way.
  7860. """
  7861. expected_n = _normalise_subtask_name(expected)
  7862. observed_n = _normalise_subtask_name(observed)
  7863. if expected_n == observed_n:
  7864. return True
  7865. # Either side can be the truncated one: the printer truncates what it
  7866. # echoes, and an archive whose own filename was recorded from a previous
  7867. # truncated echo carries the marker too.
  7868. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  7869. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  7870. continue
  7871. # The full side has lost its edge underscores; a cut that lands right
  7872. # after one keeps it, so drop it here too (#3241). Nothing left before
  7873. # the marker is no evidence of anything, and must not match every name.
  7874. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  7875. if kept and full.startswith(kept):
  7876. return True
  7877. return False
  7878. async def _queue_item_dispatched_name(db, item) -> str:
  7879. """The subtask name *item* was dispatched under, or "" when unknowable.
  7880. A row with no archive, or an archive with no file name, is unverifiable
  7881. rather than wrong; every caller answers that with its permissive branch.
  7882. """
  7883. if item.archive_id is None:
  7884. return ""
  7885. from backend.app.models.archive import PrintArchive
  7886. archive = await db.get(PrintArchive, item.archive_id)
  7887. if archive is None or not archive.filename:
  7888. return ""
  7889. return _subtask_name_from_filename(archive.filename)
  7890. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  7891. """Whether this completion event is plausibly about *item*'s print.
  7892. The caller finds its queue row by printer and ``status='printing'`` alone,
  7893. which is all a completion event gives it -- there is no run identifier in
  7894. the MQTT payload to match on. That makes the lookup indiscriminate: any
  7895. completion delivered for this printer closes whichever row happens to be
  7896. printing, however unrelated. Comparing the subtask name against the archive
  7897. the row was dispatched with costs one primary-key load and rules that out.
  7898. Deliberately permissive: it answers False only on a positive disagreement
  7899. between two names we actually have. A row with no archive, an archive with
  7900. no file name, or an event with no subtask name is unverifiable rather than
  7901. wrong, and refusing those would strand the item in ``printing`` and wedge
  7902. the printer's queue -- a worse failure than the one being prevented.
  7903. """
  7904. observed = (data.get("subtask_name") or "").strip()
  7905. if not observed or item.archive_id is None:
  7906. return True
  7907. from backend.app.models.archive import PrintArchive
  7908. archive = await db.get(PrintArchive, item.archive_id)
  7909. if archive is None or not archive.filename:
  7910. return True
  7911. expected = _subtask_name_from_filename(archive.filename)
  7912. if not expected or _subtask_names_match(expected, observed):
  7913. return True
  7914. logging.getLogger(__name__).warning(
  7915. "Ignoring print completion for queue item %s: it was dispatched as %r "
  7916. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  7917. "printing rather than closing a run this event is not about.",
  7918. item.id,
  7919. expected,
  7920. archive.id,
  7921. archive.filename,
  7922. observed,
  7923. )
  7924. return False
  7925. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  7926. """Spend the 3MF download cache on a still-empty fallback archive.
  7927. ``on_print_complete`` drops the cache as its first act, which deletes the
  7928. file. If the cover endpoint (or anything else) pulled the 3MF while the
  7929. print ran and the archive never got one, this is the last moment those bytes
  7930. exist (#2957).
  7931. """
  7932. logger = logging.getLogger(__name__)
  7933. names = [
  7934. n
  7935. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  7936. if n
  7937. ]
  7938. for name in names:
  7939. try:
  7940. cached = get_cached_3mf(printer_id, name)
  7941. # The print has ended: its completion prices the archive, so no
  7942. # print-start estimate is scheduled to race it.
  7943. if cached and await try_recover_fallback_archive(printer_id, name, cached, price=False):
  7944. return
  7945. except Exception as e:
  7946. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  7947. # Longest the print's end waits for its file to be deleted from the SD card
  7948. _SD_CLEANUP_BUDGET_SECONDS = 45.0
  7949. async def _cleanup_sd_card_after_print(
  7950. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  7951. ) -> None:
  7952. """Delete a finished print's file from the printer's SD card."""
  7953. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  7954. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  7955. # auto-start files found in root on power cycle, causing ghost prints.
  7956. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  7957. try:
  7958. if subtask_name:
  7959. archive_filename: str | None = None
  7960. async with async_session() as db:
  7961. from backend.app.models.archive import PrintArchive
  7962. from backend.app.models.printer import Printer
  7963. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7964. printer = result.scalar_one_or_none()
  7965. if archive_id:
  7966. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  7967. archive_filename = archive_row.scalar_one_or_none()
  7968. if printer:
  7969. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  7970. from backend.app.utils.filename import derive_remote_filename
  7971. # Primary candidate: the exact path the dispatcher uploaded to
  7972. # (derived from archive.filename via the same rule as upload).
  7973. # Without it, a library row that ended up with a doubled
  7974. # .gcode.3mf (#1542) leaves the real file behind because the
  7975. # subtask_name + ext fallbacks below don't match what's on the
  7976. # SD card. Fallbacks remain for archive-less prints (subtask
  7977. # never resolved to an archive) and for older naming variants.
  7978. candidate_paths: list[str] = []
  7979. if archive_filename:
  7980. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  7981. for ext in (".3mf", ".gcode"):
  7982. fallback = f"/{subtask_name}{ext}"
  7983. if fallback not in candidate_paths:
  7984. candidate_paths.append(fallback)
  7985. # Three outcomes track across all candidates so the final log
  7986. # line reflects what actually happened. The A1 in #1721 always
  7987. # ends here with ``any_not_found=True`` and the others False
  7988. # — its firmware auto-cleans the SD card before our cleanup
  7989. # runs, every candidate FTP-DELE returns 550, and the old
  7990. # code burned 3 retries × 2 s × 3 candidates per print
  7991. # logging a misleading "may linger" WARNING on a successful
  7992. # print.
  7993. any_deleted = False
  7994. any_real_failure = False
  7995. any_not_found = False
  7996. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  7997. for remote_path in candidate_paths:
  7998. if PurePosixPath(remote_path).name.lower() in files_in_use:
  7999. logger.info(
  8000. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  8001. remote_path,
  8002. printer.name,
  8003. )
  8004. continue
  8005. # Retry only the FAILED case — 550 NOT_FOUND will never
  8006. # recover by waiting, so a "file isn't here" answer
  8007. # advances immediately to the next candidate without
  8008. # consuming the retry budget.
  8009. for attempt in range(1, 4):
  8010. try:
  8011. delete_result = await delete_file_async(
  8012. printer.ip_address,
  8013. printer.access_code,
  8014. remote_path,
  8015. printer_model=printer.model,
  8016. )
  8017. except Exception as e:
  8018. delete_result = DeleteResult.FAILED
  8019. logger.warning(
  8020. "SD card cleanup attempt %d/3 raised for %s: %s",
  8021. attempt,
  8022. remote_path,
  8023. e,
  8024. )
  8025. if delete_result == DeleteResult.DELETED:
  8026. any_deleted = True
  8027. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  8028. break
  8029. if delete_result == DeleteResult.NOT_FOUND:
  8030. any_not_found = True
  8031. break # 550 will not recover; try next candidate
  8032. # FAILED: real error — retry with backoff, then give up
  8033. if attempt < 3:
  8034. await asyncio.sleep(2)
  8035. else:
  8036. any_real_failure = True
  8037. logger.warning(
  8038. "SD card cleanup failed after 3 attempts for %s "
  8039. "(network/auth/transient error — file may linger on SD card)",
  8040. remote_path,
  8041. )
  8042. if not any_deleted and not any_real_failure and any_not_found:
  8043. # Every candidate said "not here." Either the printer
  8044. # firmware swept the SD card itself (common on A1) or the
  8045. # dispatcher's upload path doesn't match our candidate
  8046. # rule. Either way: nothing to clean up, no warning.
  8047. logger.debug(
  8048. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  8049. "(printer likely self-cleaned)",
  8050. printer.name,
  8051. )
  8052. except Exception as e:
  8053. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  8054. async def on_print_complete(printer_id: int, data: dict):
  8055. """Handle print completion - update the archive status.
  8056. The printer counts as printing until the print's usage is booked (or this
  8057. ends), so the AMS remain% weight sync can't charge it a second time while
  8058. the usage tracker works (WU-3). Marked before the first await.
  8059. """
  8060. from backend.app.services.usage_tracker import done_completing, mark_completing
  8061. mark_completing(printer_id)
  8062. try:
  8063. await _close_out_print(printer_id, data)
  8064. finally:
  8065. done_completing(printer_id)
  8066. async def _close_out_print(printer_id: int, data: dict):
  8067. import time
  8068. logger = logging.getLogger(__name__)
  8069. start_time = time.time()
  8070. def log_timing(section: str):
  8071. elapsed = time.time() - start_time
  8072. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  8073. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  8074. # A kill-switch stop sends its provider notification immediately. Keep the
  8075. # task so the later notification path can await it and avoid a duplicate;
  8076. # if that immediate attempt failed, the regular completion path retries.
  8077. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  8078. # Last chance before the bytes go: if this print's archive is still an empty
  8079. # fallback and something downloaded the 3MF while it ran, fill the archive in
  8080. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  8081. # below deletes the file (#2957).
  8082. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  8083. # A pending cool-off retry has nothing left to recover for — the cache is
  8084. # about to be dropped and the print is over.
  8085. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  8086. if retry_task and not retry_task.done():
  8087. retry_task.cancel()
  8088. # Drop the 3MF download cache for this printer (#972). The print is over,
  8089. # nothing else legitimately needs the bytes; keeping them would only risk
  8090. # handing a stale file to the next print if it reuses the same name.
  8091. clear_3mf_cache(printer_id)
  8092. try:
  8093. ws_data = {
  8094. "status": data.get("status"),
  8095. "filename": data.get("filename"),
  8096. "subtask_name": data.get("subtask_name"),
  8097. "timelapse_was_active": data.get("timelapse_was_active"),
  8098. }
  8099. await ws_manager.send_print_complete(printer_id, ws_data)
  8100. log_timing("WebSocket send_print_complete")
  8101. except Exception as e:
  8102. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  8103. # Capture user info before clearing (needed for print log entry)
  8104. _print_user_info = printer_manager.get_current_print_user(printer_id)
  8105. # Clear current print user tracking (Issue #206)
  8106. printer_manager.clear_current_print_user(printer_id)
  8107. # If the user explicitly stopped this print from the queue UI the printer will
  8108. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  8109. # correct "print stopped" notification/email is sent instead of a failure alert.
  8110. _raw_status = data.get("status", "completed")
  8111. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  8112. logger.info(
  8113. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  8114. _raw_status,
  8115. printer_id,
  8116. )
  8117. data = {**data, "status": "cancelled"}
  8118. elif printer_id in _kill_switch_stopped and _raw_status in ("failed", "aborted"):
  8119. logger.info(
  8120. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (stopped by the printer kill switch)",
  8121. _raw_status,
  8122. printer_id,
  8123. )
  8124. data = {**data, "status": "cancelled", "_kill_switch": True}
  8125. _user_stopped_printers.discard(printer_id)
  8126. _kill_switch_stopped.discard(printer_id)
  8127. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  8128. # may have left material on the bed: a user can cancel ten hours into a
  8129. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  8130. # touchscreen-stop reports `aborted` rather than `cancelled` because
  8131. # `_user_stopped_printers` is only populated when the user stops via the
  8132. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  8133. # which auto-dispatched the next queued print onto a fouled bed two seconds
  8134. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  8135. # Auto Off power cycles and Bambuddy restarts.
  8136. try:
  8137. notify_live_activities.print_finished(printer_id, data)
  8138. except Exception:
  8139. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  8140. _final_status = data.get("status", "completed")
  8141. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  8142. printer_manager.set_awaiting_plate_clear(printer_id, True)
  8143. # MQTT relay - publish print complete
  8144. try:
  8145. printer_info = printer_manager.get_printer(printer_id)
  8146. if printer_info:
  8147. await mqtt_relay.on_print_complete(
  8148. printer_id,
  8149. printer_info.name,
  8150. printer_info.serial_number,
  8151. data.get("filename", ""),
  8152. data.get("subtask_name", ""),
  8153. data.get("status", "completed"),
  8154. )
  8155. except Exception:
  8156. pass # Don't fail print complete callback if MQTT fails
  8157. filename = data.get("filename", "")
  8158. subtask_name = data.get("subtask_name", "")
  8159. if not filename and not subtask_name:
  8160. # Which print ended can't be told: the printer reported no name since
  8161. # Bambuddy started (a print that failed while preparing, a calibration).
  8162. # Charge nothing, but close the print session, which otherwise kept the
  8163. # AMS weight sync off until the next print (AS-5). A print archived as
  8164. # running is closed and charged by the reconnect reconcile.
  8165. logger.warning("Print complete without filename or subtask_name")
  8166. try:
  8167. from backend.app.services.usage_tracker import discard_session
  8168. async with async_session() as db:
  8169. await discard_session(db, printer_id)
  8170. except Exception as e:
  8171. logger.warning("Failed to clear print session for printer %s: %s", printer_id, e)
  8172. return
  8173. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  8174. # Build list of possible keys to try (matching how they were registered in on_print_start)
  8175. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  8176. # Find the archive for this print
  8177. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  8178. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  8179. archive_id = None
  8180. for key in possible_keys:
  8181. archive_id = _active_prints.pop(key, None)
  8182. if archive_id:
  8183. _owned_print_archive_ids.discard(archive_id)
  8184. logger.info("Found archive %s with key %s", archive_id, key)
  8185. # Also clean up the printer's other keys pointing to this archive;
  8186. # another printer's are a plate of it still printing there.
  8187. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id and k[0] == printer_id]
  8188. for k in keys_to_remove:
  8189. _active_prints.pop(k, None)
  8190. break
  8191. # The archive bound when the print started, before the name search below.
  8192. # Only this one may give the finish-photo plate restore a height (#3240):
  8193. # the search matches names by substring.
  8194. bound_archive_id = archive_id
  8195. if not archive_id and data.get("_reconciled") and data.get("_reconciled_archive_id"):
  8196. # The reconcile names the archive whose run on this printer it
  8197. # closes. Only while that run is open: the print's real end may have
  8198. # closed it meanwhile, or closed the print without managing to write
  8199. # it, and either way there is nothing left to end twice.
  8200. if await _archive_of_open_run(printer_id) != data["_reconciled_archive_id"]:
  8201. logger.info(
  8202. "[RECONCILE] Archive %s has no run open on printer %s any more; nothing to close",
  8203. data["_reconciled_archive_id"],
  8204. printer_id,
  8205. )
  8206. return
  8207. archive_id = data["_reconciled_archive_id"]
  8208. ending_job = str(data.get("subtask_id") or "").strip()
  8209. if not archive_id and ending_job not in ("", "0"):
  8210. # Not bound (a restart since the start): this job's run, open on the
  8211. # printer. Only by its job id: a run open there can be of the print
  8212. # running now, while the end is of an earlier one closed late (the
  8213. # restart's reconcile of a missed end).
  8214. archive_id = await _archive_of_open_run(printer_id, subtask_id=ending_job)
  8215. if archive_id:
  8216. logger.info("Found archive %s by the run of job %s open on printer %s", archive_id, ending_job, printer_id)
  8217. if not archive_id:
  8218. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  8219. async with async_session() as db:
  8220. from backend.app.models.archive import PrintArchive
  8221. # Try matching by subtask_name (stored as print_name) first. The
  8222. # same name rule as the queue's completion check: a name inside
  8223. # another ("Clip" in "Cable Clip") is a different print, and the
  8224. # printer's underscores for spaces and truncation still match.
  8225. if subtask_name:
  8226. printing = await db.scalars(
  8227. select(PrintArchive)
  8228. .where(PrintArchive.printer_id == printer_id)
  8229. .where(PrintArchive.status == "printing")
  8230. .order_by(PrintArchive.created_at.desc())
  8231. )
  8232. # A print started from the printer's screen reports its file
  8233. # name, extensions included, as the subtask (#3009).
  8234. reported = {subtask_name, _subtask_name_from_filename(subtask_name)}
  8235. archive = next(
  8236. (
  8237. candidate
  8238. for candidate in printing
  8239. if any(
  8240. (candidate.print_name and _subtask_names_match(candidate.print_name, name))
  8241. or (
  8242. candidate.filename
  8243. and _subtask_names_match(_subtask_name_from_filename(candidate.filename), name)
  8244. )
  8245. for name in reported
  8246. )
  8247. ),
  8248. None,
  8249. )
  8250. if archive:
  8251. archive_id = archive.id
  8252. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  8253. # Also try by filename
  8254. if not archive_id and filename:
  8255. result = await db.execute(
  8256. select(PrintArchive)
  8257. .where(PrintArchive.printer_id == printer_id)
  8258. .where(PrintArchive.filename == filename)
  8259. .where(PrintArchive.status == "printing")
  8260. .order_by(PrintArchive.created_at.desc())
  8261. .limit(1)
  8262. )
  8263. archive = result.scalar_one_or_none()
  8264. if archive:
  8265. archive_id = archive.id
  8266. # Bounded: a printer whose FTP hangs on DELE took up to 3 candidates x 3
  8267. # attempts x a 60 s timeout, about nine minutes, before the queue item was
  8268. # closed below. The stranded-job closer gives up after five and closed it
  8269. # first, so the job's auto-off and its billing never ran. Inline rather
  8270. # than in the background, so the next job of the same file isn't released
  8271. # (and uploaded under the name being deleted) while the cleanup still
  8272. # works on it. A delete already sent may still finish in its FTP thread
  8273. # after the cutoff, as one past delete_file_async's own timeout always did.
  8274. try:
  8275. await asyncio.wait_for(
  8276. _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger),
  8277. timeout=_SD_CLEANUP_BUDGET_SECONDS,
  8278. )
  8279. except TimeoutError:
  8280. logger.warning(
  8281. "SD card cleanup on printer %s took over %ss; leaving the file there and closing the print",
  8282. printer_id,
  8283. _SD_CLEANUP_BUDGET_SECONDS,
  8284. )
  8285. log_timing("SD card cleanup")
  8286. # Update queue item status early — must run before the archive_id early-return
  8287. # so queue items don't get stuck in "printing" when archive lookup fails.
  8288. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  8289. queue_item_id = None
  8290. billing_run_id: str | None = None
  8291. billing_user_id: int | None = None
  8292. billing_cost_center_id: int | None = None
  8293. billing_plate_id: int | None = None
  8294. queue_status = None
  8295. queue_auto_off = False
  8296. try:
  8297. from backend.app.core.database import run_with_retry
  8298. from backend.app.models.print_queue import PrintQueueItem
  8299. async def _update_queue_status(db):
  8300. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  8301. nonlocal queue_item_id, queue_status, queue_auto_off
  8302. result = await db.execute(
  8303. select(PrintQueueItem)
  8304. .where(PrintQueueItem.printer_id == printer_id)
  8305. .where(PrintQueueItem.status == "printing")
  8306. )
  8307. printing_items = list(result.scalars().all())
  8308. if len(printing_items) > 1:
  8309. logger.warning(
  8310. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  8311. printer_id,
  8312. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  8313. )
  8314. item = printing_items[0] if printing_items else None
  8315. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  8316. return
  8317. if item:
  8318. queue_status = data.get("status", "completed")
  8319. # MQTT sends "aborted" for cancelled prints; normalise to
  8320. # "cancelled" so it matches the queue schema Literal.
  8321. if queue_status == "aborted":
  8322. queue_status = "cancelled"
  8323. item.status = queue_status
  8324. item.completed_at = datetime.now(timezone.utc)
  8325. if queue_status == "failed" and not item.error_message:
  8326. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  8327. # Bump usage counters on the source library file so admins can
  8328. # sort by "last printed" and (eventually) auto-purge stale
  8329. # files — #1008.
  8330. await _bump_library_file_usage_if_completed(db, item, queue_status)
  8331. await db.commit()
  8332. queue_item_id = item.id
  8333. billing_run_id = item.billing_run_id
  8334. billing_user_id = item.created_by_id
  8335. billing_cost_center_id = item.cost_center_id
  8336. billing_plate_id = item.plate_id
  8337. queue_auto_off = item.auto_off_after
  8338. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  8339. await run_with_retry(_update_queue_status, label="queue status update")
  8340. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  8341. # their own sessions and have their own error handling — no retry needed.
  8342. if queue_item_id is not None:
  8343. # Batch orders (#342): this run may have been the last one an order
  8344. # owed. Re-evaluate here rather than lazily on read, so a finished
  8345. # order reports itself complete without someone opening the page.
  8346. try:
  8347. from backend.app.services.print_batch import refresh_batch_status_for_item
  8348. async with async_session() as db:
  8349. await refresh_batch_status_for_item(db, queue_item_id)
  8350. await db.commit()
  8351. except Exception as e:
  8352. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  8353. # MQTT relay - publish queue job completed
  8354. try:
  8355. printer_info = printer_manager.get_printer(printer_id)
  8356. await mqtt_relay.on_queue_job_completed(
  8357. job_id=queue_item_id,
  8358. filename=filename or subtask_name,
  8359. printer_id=printer_id,
  8360. printer_name=printer_info.name if printer_info else "Unknown",
  8361. status=queue_status,
  8362. )
  8363. except Exception:
  8364. pass # Don't fail if MQTT fails
  8365. # Check if queue is now empty and send notification
  8366. try:
  8367. from sqlalchemy import func as sa_func
  8368. async with async_session() as db:
  8369. count_result = await db.execute(
  8370. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  8371. )
  8372. pending_count = count_result.scalar() or 0
  8373. if pending_count == 0:
  8374. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  8375. completed_result = await db.execute(
  8376. select(sa_func.count(PrintQueueItem.id)).where(
  8377. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  8378. PrintQueueItem.completed_at >= today_start,
  8379. )
  8380. )
  8381. completed_count = completed_result.scalar() or 1
  8382. await notification_service.on_queue_completed(
  8383. completed_count=completed_count,
  8384. db=db,
  8385. )
  8386. except Exception:
  8387. pass # Don't fail if notification fails
  8388. # Handle auto_off_after - power off printer if the queue item opted
  8389. # in. Delegates to the smart-plug manager so the off honours each
  8390. # plug's configured strategy (time delay or temperature threshold),
  8391. # is cancelled if the printer starts printing again, and never cuts
  8392. # power on a loaded print (#1890). Previously an inline block here
  8393. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  8394. # timeout regardless of print state — cutting a touchscreen reprint.
  8395. if queue_auto_off:
  8396. try:
  8397. async with async_session() as db:
  8398. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  8399. except Exception as e:
  8400. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  8401. except Exception as e:
  8402. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  8403. log_timing("Queue item update")
  8404. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  8405. # Must run before archive_id early-return so it fires for all prints (including
  8406. # prints started from BambuStudio/touchscreen that have no archive).
  8407. if data.get("status") == "completed":
  8408. try:
  8409. from backend.app.api.routes.settings import get_setting
  8410. async with async_session() as db:
  8411. threshold_str = await get_setting(db, "bed_cooled_threshold")
  8412. threshold = float(threshold_str) if threshold_str else 35.0
  8413. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  8414. async with async_session() as db:
  8415. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  8416. if providers:
  8417. _bed_cool_waiters[printer_id] = {
  8418. "threshold": threshold,
  8419. "filename": filename or subtask_name or "",
  8420. "registered_at": time.time(),
  8421. }
  8422. logger.info(
  8423. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  8424. printer_id,
  8425. threshold,
  8426. )
  8427. else:
  8428. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  8429. except Exception as e:
  8430. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  8431. # Capture the slicer estimate before usage tracking runs. The tracker may
  8432. # update archive.cost with this run's measured cost; billing partial runs
  8433. # against that already-partial value would discount the charge twice.
  8434. billing_planned_grams: float | None = None
  8435. billing_base_cost: float | None = None
  8436. if archive_id:
  8437. try:
  8438. async with async_session() as db:
  8439. from backend.app.models.archive import PrintArchive
  8440. billing_archive = await db.get(PrintArchive, archive_id)
  8441. if billing_archive:
  8442. billing_path = (
  8443. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  8444. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8445. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  8446. billing_archive,
  8447. billing_path,
  8448. billing_plate_id
  8449. if billing_plate_id is not None
  8450. else _get_start_plate_id(printer_id, archive_id),
  8451. )
  8452. except Exception as e:
  8453. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  8454. # --- Track filament consumption (must run before archive_id early-return so usage
  8455. # is recorded even when auto-archive is disabled) ---
  8456. usage_results: list[dict] = []
  8457. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  8458. stored_ams_mapping = data.get("ams_mapping")
  8459. # Fallback to _print_ams_mappings for queue/reprint (set before print starts).
  8460. # Drained either way, like the plate below: left over, it would be read by
  8461. # the archive's next run, dispatched without a mapping.
  8462. registered_ams_mapping = _print_ams_mappings.pop((printer_id, archive_id), None) if archive_id else None
  8463. if not stored_ams_mapping:
  8464. stored_ams_mapping = registered_ams_mapping
  8465. # Always drain the plate_id register on completion — the session already
  8466. # consumed it at print-start injection; leaving it would leak into the next
  8467. # print on the same archive_id (rare but possible with reprints) (#1697).
  8468. # Capture the popped value so the completion notification can scope the
  8469. # archive-level (summed-across-plates per #1593) filament + time totals
  8470. # down to the single plate that was actually printed (#1785).
  8471. notify_plate_id: int | None = None
  8472. if archive_id:
  8473. notify_plate_id = _print_plate_ids.pop((printer_id, archive_id), None)
  8474. # The start estimate must not outlive the real cost written below (COST-4).
  8475. if archive_id:
  8476. await _settle_archive_cost_estimate(archive_id)
  8477. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  8478. try:
  8479. async with async_session() as db:
  8480. from backend.app.api.routes.settings import get_setting
  8481. _spoolman_on = await get_setting(db, "spoolman_enabled")
  8482. if not _spoolman_on or _spoolman_on.lower() != "true":
  8483. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  8484. async with async_session() as db:
  8485. usage_results = await usage_on_print_complete(
  8486. printer_id,
  8487. data,
  8488. printer_manager,
  8489. db,
  8490. archive_id=archive_id,
  8491. ams_mapping=stored_ams_mapping,
  8492. )
  8493. if usage_results:
  8494. await ws_manager.broadcast(
  8495. {
  8496. "type": "spool_usage_logged",
  8497. "printer_id": printer_id,
  8498. "usage": usage_results,
  8499. }
  8500. )
  8501. log_timing("Usage tracker")
  8502. except Exception as e:
  8503. logger.warning("Usage tracker on_print_complete failed: %s", e)
  8504. # Drop the print-start context unconditionally — the Spoolman branch above
  8505. # skips the internal tracker entirely, so nothing else would clear what
  8506. # print start captured, and a row surviving its print would be restored
  8507. # onto the next one after a restart.
  8508. try:
  8509. from backend.app.services.usage_tracker import discard_session
  8510. async with async_session() as db:
  8511. await discard_session(db, printer_id)
  8512. except Exception as e:
  8513. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  8514. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  8515. # A partial run's cost from the Spoolman spools it was charged to; the
  8516. # built-in inventory's comes in usage_results.
  8517. spoolman_run_cost: float | None = None
  8518. if archive_id:
  8519. if data.get("status") == "completed":
  8520. try:
  8521. await _report_spoolman_usage(printer_id, archive_id)
  8522. log_timing("Spoolman usage report")
  8523. except Exception as e:
  8524. logger.warning("Spoolman usage reporting failed: %s", e)
  8525. else:
  8526. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  8527. try:
  8528. async with async_session() as db:
  8529. spoolman_run_cost = await _cleanup_spoolman_tracking(
  8530. printer_id,
  8531. archive_id,
  8532. db,
  8533. last_layer_num=data.get("last_layer_num"),
  8534. last_progress=data.get("last_progress"),
  8535. status=data.get("status") or "failed",
  8536. )
  8537. except Exception as e:
  8538. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  8539. await _release_archived_spoolman_slots(printer_id)
  8540. log_timing("Filament usage tracking")
  8541. if not archive_id:
  8542. # The printer's own calibration run has no archive by design, so this
  8543. # arrives here every time one finishes. Returning before the no-archive
  8544. # notification keeps a calibration from being announced as a finished
  8545. # print. Everything above this point has already run — the plate-clear
  8546. # gate, the queue reconciliation, the SD-card cleanup — so only the
  8547. # notification is skipped.
  8548. if is_internal_printer_job(filename, subtask_name):
  8549. logger.info(
  8550. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  8551. filename,
  8552. subtask_name,
  8553. )
  8554. return
  8555. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  8556. # Still send print-complete/failed/stopped notifications even without an archive.
  8557. # Try to enrich with queue/library-file data so user-specific emails work too.
  8558. async def _notify_no_archive():
  8559. try:
  8560. async with async_session() as db:
  8561. from backend.app.models.library import LibraryFile
  8562. from backend.app.models.print_queue import PrintQueueItem
  8563. from backend.app.models.printer import Printer
  8564. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8565. printer_obj = result.scalar_one_or_none()
  8566. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  8567. # Only the queue item this completion itself closed (the
  8568. # reconciliation above, which checks the run belongs to it).
  8569. # A print started outside Bambuddy closed none, and must not
  8570. # borrow an earlier job's owner, email or times.
  8571. no_archive_data: dict | None = None
  8572. try:
  8573. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  8574. if queue_item:
  8575. no_archive_data = {"created_by_id": queue_item.created_by_id}
  8576. # How long it really ran, as the archive path reports it (#1198).
  8577. started = to_naive_utc(queue_item.started_at)
  8578. ended = to_naive_utc(queue_item.completed_at)
  8579. # Not for a completion reconciled at reconnect: it
  8580. # ended at an unknown time while the printer was
  8581. # offline, and "now" is the reconnect (DB-C9).
  8582. if (
  8583. not data.get("_reconciled")
  8584. and started
  8585. and ended
  8586. and (ended - started).total_seconds() > 0
  8587. ):
  8588. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  8589. # Estimated time: the queue item caches it from its
  8590. # archive or library file; otherwise read the library
  8591. # file's metadata (LibraryFile has no column for it).
  8592. if queue_item.print_time_seconds:
  8593. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  8594. elif queue_item.library_file_id:
  8595. lib_result = await db.execute(
  8596. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  8597. )
  8598. lib_file = lib_result.scalar_one_or_none()
  8599. estimate = (
  8600. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  8601. )
  8602. if estimate:
  8603. no_archive_data["print_time_seconds"] = estimate
  8604. except Exception as lookup_err:
  8605. logger.debug(
  8606. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  8607. )
  8608. # Enrich with usage tracker results (captured in enclosing scope)
  8609. if usage_results:
  8610. if no_archive_data is None:
  8611. no_archive_data = {}
  8612. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  8613. if total_from_usage > 0:
  8614. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8615. no_archive_data["usage_results"] = usage_results
  8616. # Try MQTT remaining_time for print duration when no queue/library data
  8617. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  8618. mqtt_remaining = data.get("remaining_time")
  8619. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  8620. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  8621. ps = data.get("status", "completed")
  8622. logger.info(
  8623. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  8624. )
  8625. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8626. await notification_service.on_print_complete(
  8627. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  8628. )
  8629. else:
  8630. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8631. # Send user-specific email if we have a created_by_id
  8632. if no_archive_data and no_archive_data.get("created_by_id"):
  8633. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8634. await _dispatch_user_print_email(
  8635. ps,
  8636. no_archive_data["created_by_id"],
  8637. p_name,
  8638. raw_filename,
  8639. db,
  8640. )
  8641. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  8642. except Exception as e:
  8643. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  8644. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  8645. return
  8646. log_timing("Archive lookup")
  8647. # Update archive status
  8648. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  8649. try:
  8650. async with async_session() as db:
  8651. service = ArchiveService(db)
  8652. status = data.get("status", "completed")
  8653. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  8654. if hms_errors:
  8655. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  8656. failure_reason = derive_failure_reason(status, hms_errors)
  8657. if data.get("_reconciled") and (status == "aborted" or (status == "failed" and not failure_reason)):
  8658. # A reconciled completion closes out a stale archive at
  8659. # reconnect — it is not a user action, so don't mislabel it
  8660. # "userCancelled". It shares the stale-cleanup path's key
  8661. # (issue #2974) and records that the real end time is unknown,
  8662. # which is also why its logged duration is 0 (#2592). A failed
  8663. # one the printer's errors explain keeps their reason (#3310).
  8664. failure_reason = "noStatusUpdate"
  8665. elif data.get("_kill_switch"):
  8666. # Not the user's cancel: the kill switch stopped a print that did
  8667. # not come from Bambuddy.
  8668. failure_reason = "killSwitch"
  8669. if failure_reason:
  8670. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  8671. elif status == "failed" and hms_errors:
  8672. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  8673. await service.update_archive_status(
  8674. archive_id,
  8675. status=status,
  8676. completed_at=(
  8677. # A reconciled completed print ended at an estimated time,
  8678. # not at the reconnect (#3310).
  8679. data.get("_reconciled_completed_at") or datetime.now(timezone.utc)
  8680. if status in ("completed", "failed", "aborted", "cancelled")
  8681. else None
  8682. ),
  8683. failure_reason=failure_reason,
  8684. )
  8685. logger.info(
  8686. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  8687. )
  8688. await ws_manager.send_archive_updated(
  8689. {
  8690. "id": archive_id,
  8691. "status": status,
  8692. }
  8693. )
  8694. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  8695. # MQTT relay - publish archive updated
  8696. try:
  8697. await mqtt_relay.on_archive_updated(
  8698. archive_id=archive_id,
  8699. print_name=filename or subtask_name,
  8700. status=status,
  8701. )
  8702. except Exception:
  8703. pass # Don't fail if MQTT fails
  8704. except Exception as e:
  8705. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  8706. # Continue with other operations even if archive update fails
  8707. log_timing("Archive status update")
  8708. # Apply finance wallet charge or release reservations once. For all partial
  8709. # terminal states (failed, aborted at the printer display, or cancelled via
  8710. # Bambuddy) use this run's measured spool delta, falling back to the last
  8711. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  8712. # estimate and therefore cannot represent an interrupted run.
  8713. try:
  8714. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  8715. async with async_session() as db:
  8716. from backend.app.models.archive import PrintArchive
  8717. from backend.app.services.finance_billing import apply_print_charge_for_archive
  8718. from backend.app.services.print_log import run_being_ended
  8719. archive = await db.get(PrintArchive, archive_id)
  8720. # The run this end fills in below: charged as its own, not as
  8721. # the archive's latest dispatch (another plate of it, maybe).
  8722. charged_run = await run_being_ended(db, archive_id, printer_id, archive.started_at) if archive else None
  8723. if archive and billing_run_id is None and charged_run is None:
  8724. billing_run_id = getattr(archive, "billing_run_id", None)
  8725. if archive and archive.created_by_id is None and _print_user_info:
  8726. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  8727. await db.flush()
  8728. run_status = data.get("status", "completed")
  8729. last_progress = data.get("last_progress")
  8730. if last_progress is None:
  8731. last_progress = data.get("progress")
  8732. actual_run_grams = _compute_run_filament_grams(
  8733. run_status,
  8734. billing_planned_grams,
  8735. last_progress,
  8736. usage_results,
  8737. )
  8738. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  8739. in_memory_cost_center_id = _print_cost_center_ids.pop((printer_id, archive_id), None)
  8740. charged = await apply_print_charge_for_archive(
  8741. db,
  8742. archive_id,
  8743. charged_user_id=billing_user_id,
  8744. cost_center_id=(
  8745. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  8746. ),
  8747. print_queue_id=queue_item_id,
  8748. print_run_id=billing_run_id,
  8749. base_cost_override=billing_base_cost,
  8750. filament_usage=filament_usage,
  8751. run_entry_id=charged_run.id if charged_run is not None else None,
  8752. run_status=run_status,
  8753. )
  8754. await db.commit()
  8755. if charged:
  8756. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  8757. except Exception as e:
  8758. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  8759. printer_info = printer_manager.get_printer(printer_id)
  8760. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  8761. billing_filename = filename or subtask_name or "Unknown"
  8762. billing_error = str(e)
  8763. try:
  8764. await ws_manager.broadcast(
  8765. {
  8766. "type": "billing_charge_failed",
  8767. "printer_id": printer_id,
  8768. "printer_name": billing_printer_name,
  8769. "filename": billing_filename,
  8770. "archive_id": archive_id,
  8771. }
  8772. )
  8773. except Exception as notification_error:
  8774. logger.error(
  8775. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  8776. archive_id,
  8777. notification_error,
  8778. )
  8779. async def _notify_billing_charge_failed() -> None:
  8780. try:
  8781. async with async_session() as notification_db:
  8782. await notification_service.on_billing_charge_failed(
  8783. printer_id,
  8784. billing_printer_name,
  8785. billing_filename,
  8786. archive_id,
  8787. billing_error,
  8788. notification_db,
  8789. )
  8790. except Exception as provider_error:
  8791. logger.error(
  8792. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  8793. archive_id,
  8794. provider_error,
  8795. exc_info=True,
  8796. )
  8797. spawn_background_task(
  8798. _notify_billing_charge_failed(),
  8799. name=f"billing-charge-failed-{archive_id}",
  8800. )
  8801. log_timing("Finance charge update")
  8802. # Write independent print log entry (separate table, never touches archives)
  8803. # The run's id, for the energy work below: the archive's newest run is
  8804. # the one started last, which with plates of it on two printers need not
  8805. # be the one that just ended.
  8806. completed_run_id: int | None = None
  8807. async def _write_run(db):
  8808. # Retried on a locked SQLite database: a run left open here would be
  8809. # closed again by the next reconnect's reconcile.
  8810. nonlocal completed_run_id
  8811. from backend.app.models.archive import PrintArchive
  8812. from backend.app.services.print_log import discard_open_runs, record_archive_wear, write_log_entry
  8813. archive = await db.get(PrintArchive, archive_id)
  8814. if archive is None:
  8815. # Deleted while it printed: its run has nothing left to end on.
  8816. discarded = await discard_open_runs(db, printer_id)
  8817. await db.commit()
  8818. await _announce_discarded_runs(discarded, printer_id)
  8819. if archive:
  8820. # Back-fill created_by_id on reprint (#730): reprint reuses the
  8821. # source archive row rather than creating a new one, so an
  8822. # archive that was auto-created from a printer-initiated
  8823. # print (created_by_id=NULL) would otherwise stay unattributed
  8824. # forever. When we have a print-session user AND the archive
  8825. # has no attribution yet, credit the current user. Never
  8826. # overwrite an existing attribution — the original uploader
  8827. # keeps ownership.
  8828. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  8829. if archive.created_by_id is None and _print_user_id is not None:
  8830. archive.created_by_id = _print_user_id
  8831. p_info = printer_manager.get_printer(printer_id)
  8832. # Per-run actuals — written to PrintLogEntry so stats reflect
  8833. # what THIS print actually used, not the source archive's
  8834. # first-run values (#1378). Helper handles the partial-print
  8835. # math (failed / cancelled / stopped get scaled to progress
  8836. # or to tracked spool deltas).
  8837. _run_status = data.get("status", "completed")
  8838. # #2614: scope the per-run estimate to the printed plate. For a
  8839. # multi-plate 3MF dispatched one plate at a time, the archive's
  8840. # filament/cost are the whole-file totals; the PrintLogEntry must
  8841. # reflect only this plate. No effect on single-plate archives (the
  8842. # plate estimate equals the whole-file value) or on the tracker
  8843. # path (measured spool deltas win in _compute_run_filament_grams).
  8844. _est_full_path = (
  8845. app_settings.base_dir / archive.file_path if archive.file_path else None
  8846. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8847. # The plate that printed, as billing reads it: a reprint of
  8848. # another plate must not log the archive's first plate.
  8849. _run_plate_id = billing_plate_id if billing_plate_id is not None else notify_plate_id
  8850. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path, _run_plate_id)
  8851. if _run_plate_id is None:
  8852. _run_plate_id = archive.plate_id
  8853. _run_grams = _compute_run_filament_grams(
  8854. _run_status,
  8855. _est_grams,
  8856. data.get("last_progress", data.get("progress")),
  8857. usage_results,
  8858. )
  8859. # Per-run cost — prefer usage_results sum. For partial prints
  8860. # we deliberately skip the topup-to-estimate logic in
  8861. # usage_tracker (which assumes the print completed); the raw
  8862. # tracked-spool sum is closer to what THIS run actually cost.
  8863. _run_cost: float | None = None
  8864. if usage_results:
  8865. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  8866. if _run_cost is None and _run_status != "completed":
  8867. _run_cost = spoolman_run_cost
  8868. if _run_cost is None and _run_status == "completed":
  8869. _run_cost = _est_cost
  8870. from backend.app.models.printer import Printer as _Printer
  8871. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  8872. run_entry = await write_log_entry(
  8873. db,
  8874. archive_id=archive.id,
  8875. # Captured by _update_queue_status above; None for
  8876. # printer-initiated prints with no queue row. Batch
  8877. # cost/energy roll-up joins on it (#342).
  8878. queue_item_id=queue_item_id,
  8879. status=_run_status,
  8880. print_name=archive.print_name,
  8881. # The plate this run printed, as the estimate above takes
  8882. # it; the archive's own is the latest run's.
  8883. plate_id=_run_plate_id,
  8884. printer_name=p_info.name if p_info else None,
  8885. printer_id=printer_id,
  8886. started_at=archive.started_at,
  8887. completed_at=archive.completed_at,
  8888. filament_type=archive.filament_type,
  8889. filament_color=archive.filament_color,
  8890. filament_used_grams=_run_grams,
  8891. cost=_run_cost,
  8892. wear_cost_per_hour=_wear_rate,
  8893. failure_reason=archive.failure_reason,
  8894. thumbnail_path=archive.thumbnail_path,
  8895. created_by_id=archive.created_by_id,
  8896. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  8897. # Reconciled completions have an unknown real end time —
  8898. # log 0 duration instead of the whole disconnect gap (#2592),
  8899. # unless it was estimated (#3310).
  8900. reconciled=bool(data.get("_reconciled")) and not data.get("_reconciled_completed_at"),
  8901. # Its time is the estimate or nothing, never measured (#3310).
  8902. duration_unmeasured=bool(data.get("_reconciled")),
  8903. # The real end of a print stopped while its printer was offline.
  8904. replaces_offline_stop=True,
  8905. )
  8906. await record_archive_wear(db, archive, run_entry)
  8907. await db.commit()
  8908. completed_run_id = run_entry.id
  8909. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  8910. try:
  8911. from backend.app.core.database import run_with_retry
  8912. await run_with_retry(_write_run, label="print log entry")
  8913. except Exception as e:
  8914. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  8915. await _publish_run_completed(completed_run_id, printer_id)
  8916. log_timing("Print log entry")
  8917. # Run slow operations as background tasks to avoid blocking the event loop
  8918. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  8919. async def _background_energy_calculation():
  8920. """Calculate and save energy usage in background.
  8921. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  8922. backend restart no longer loses per-print energy data).
  8923. """
  8924. try:
  8925. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  8926. async with async_session() as db:
  8927. from backend.app.models.archive import PrintArchive
  8928. from backend.app.models.print_log import PrintLogEntry
  8929. from backend.app.services.print_log import energy_start_of
  8930. archive = await db.get(PrintArchive, archive_id)
  8931. if archive is None:
  8932. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  8933. return
  8934. # The ended run's own start reading: the archive's is its
  8935. # latest start's, maybe another plate's on another printer.
  8936. run_row = await db.get(PrintLogEntry, completed_run_id) if completed_run_id is not None else None
  8937. start = energy_start_of(run_row, archive)
  8938. if start is None:
  8939. logger.info("[ENERGY-BG] No start kWh recorded for archive %s's run", archive_id)
  8940. return
  8941. starting_kwh = start.kwh
  8942. candidates = await energy_plug_candidates(db, printer_id)
  8943. if not candidates:
  8944. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  8945. return
  8946. # Same ordering as the start reading, so the delta below is
  8947. # against the counter that produced `starting_kwh` (#2859).
  8948. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  8949. if selected is None:
  8950. logger.warning(
  8951. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  8952. printer_id,
  8953. ", ".join(plug.name for plug in candidates),
  8954. )
  8955. return
  8956. plug, energy = selected
  8957. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  8958. energy_used = round(energy["total"] - starting_kwh, 4)
  8959. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  8960. if energy_used < 0:
  8961. logger.warning(
  8962. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  8963. archive_id,
  8964. starting_kwh,
  8965. energy["total"],
  8966. )
  8967. return
  8968. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  8969. # Each hour of the print at the price of that hour (#1251). If
  8970. # that fails, the last price known, as before, rather than no
  8971. # energy at all. Read first: the session may be unusable after.
  8972. last_price = await stored_price(db)
  8973. try:
  8974. energy_cost_value = round(
  8975. await print_energy_cost(
  8976. db,
  8977. plug_id=start.plug_id,
  8978. start_at=start.at,
  8979. start_kwh=starting_kwh,
  8980. start_price=start.price,
  8981. end_kwh=energy["total"],
  8982. end_plug_id=plug.id,
  8983. price_now=await current_price(db),
  8984. ),
  8985. 3,
  8986. )
  8987. except Exception as e:
  8988. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  8989. energy_cost_value = round(energy_used * last_price, 3)
  8990. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  8991. # reprint doesn't visually clobber the source archive's energy data
  8992. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  8993. from sqlalchemy import func
  8994. existing_runs = await db.scalar(
  8995. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  8996. )
  8997. if (existing_runs or 0) <= 1:
  8998. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  8999. # we just wrote for THIS print. Either way it's the first run.
  9000. archive.energy_kwh = energy_used
  9001. archive.energy_cost = energy_cost_value
  9002. # The ended run's energy (write_log_entry above ran before this
  9003. # background task, so its energy fields are still NULL). With
  9004. # no run written, none: the archive's newest is another print's.
  9005. if run_row is not None:
  9006. run_row.energy_kwh = energy_used
  9007. run_row.energy_cost = energy_cost_value
  9008. await db.commit()
  9009. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  9010. except Exception as e:
  9011. logger.warning("[ENERGY-BG] Failed: %s", e)
  9012. async def _background_finish_photo() -> str | None:
  9013. """Capture finish photo in background. Returns photo filename if captured."""
  9014. # #2547: set once this function has raised the plate itself (the
  9015. # timelapse path, where the moment producer returned without doing it).
  9016. # Declared out here so the `finally` can lower it again no matter where
  9017. # the capture below fails.
  9018. plate_restored_z: float | None = None
  9019. try:
  9020. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  9021. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  9022. # Read phase: settings + printer + archive in a short session, released
  9023. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  9024. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  9025. # tens of seconds; holding this session across it pinned one pooled
  9026. # connection idle-in-transaction per finishing print (issue #2572).
  9027. async with async_session() as db:
  9028. from backend.app.api.routes.settings import get_setting
  9029. from backend.app.models.archive import PrintArchive
  9030. from backend.app.models.printer import Printer
  9031. capture_enabled = await get_setting(db, "capture_finish_photo")
  9032. if capture_enabled is not None and capture_enabled.lower() != "true":
  9033. return None
  9034. if not archive_id:
  9035. return None
  9036. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  9037. archive = (
  9038. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  9039. ).scalar_one_or_none()
  9040. if not printer or not archive:
  9041. return None
  9042. import uuid
  9043. from datetime import datetime
  9044. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  9045. if not archive.file_path:
  9046. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  9047. archive_dir = resolve_archive_dir(archive)
  9048. photo_filename = None
  9049. # Prefer the timelapse last-frame source when a timelapse was
  9050. # recording — it captures the moment after the toolhead parks
  9051. # but before the bed drops, which the live-camera grab below
  9052. # would miss (#1397). Skipped for external cameras (those have
  9053. # their own framing and don't see a Bambu timelapse). Only
  9054. # runs when the USER explicitly enabled timelapse for this
  9055. # print — #1721 removed Bambuddy's force-on at dispatch
  9056. # because it caused per-layer nozzle parking on Smooth-mode
  9057. # slicer profiles.
  9058. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  9059. printer.external_camera_enabled and printer.external_camera_url
  9060. )
  9061. timelapse_still_pending = False
  9062. if prefer_timelapse_source:
  9063. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  9064. archive_id=archive_id,
  9065. archive_dir=archive_dir,
  9066. rotation=getattr(printer, "camera_rotation", 0),
  9067. run_id=completed_run_id,
  9068. )
  9069. # #1721: replacement framing path — on_finish_photo_moment
  9070. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  9071. # parked, bed not yet dropped) and cached the JPEG bytes in
  9072. # _stage22_finish_frames. Consume them now so the saved photo
  9073. # has the better framing instead of the post-bed-drop angle
  9074. # the live-camera fallback below would give.
  9075. if not photo_filename:
  9076. # #1790: on the FINISH-state fallback path the producer
  9077. # task is dispatched back-to-back with this consumer, so
  9078. # a bare pop would race past with an empty result and
  9079. # the RTSP fallback below would collide with the
  9080. # producer's still-in-flight grab (single-client RTSP
  9081. # on Bambu printers). Wait for the producer to finish
  9082. # or give up before touching the cache.
  9083. #
  9084. # #2547: 20s was enough when the producer only ever grabbed a
  9085. # frame. It now also raises the plate first, which costs the
  9086. # settle window before the grab even starts — so the budget has
  9087. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  9088. # under the notification's own photo wait below.
  9089. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  9090. if in_flight is not None:
  9091. try:
  9092. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  9093. except TimeoutError:
  9094. logger.warning(
  9095. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  9096. printer_id,
  9097. )
  9098. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  9099. if cached_frame:
  9100. # Already rotated by the producer (#2708) — rotating again
  9101. # here would undo the fix on the banked-frame path, whose
  9102. # bytes reach the cache having been rotated once already.
  9103. photos_dir = archive_dir / "photos"
  9104. photos_dir.mkdir(parents=True, exist_ok=True)
  9105. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9106. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9107. photo_path = photos_dir / photo_filename
  9108. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  9109. logger.info(
  9110. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  9111. photo_filename,
  9112. len(cached_frame),
  9113. )
  9114. # #2547: the timelapse path reaches the live grab below whenever the
  9115. # video hasn't landed in time — the documented usual outcome on
  9116. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  9117. # returned early for those prints without raising the plate, so
  9118. # without this the photo that actually ships in the notification is
  9119. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  9120. # asked us to fix. The archive still gets the better video frame
  9121. # later; this is about the image the user is sent.
  9122. #
  9123. # Gated on `timelapse_was_active` precisely because that is the
  9124. # condition under which the producer skipped. On every other path it
  9125. # has already raised and lowered the plate, and repeating that here
  9126. # would be a second pointless round trip.
  9127. if (
  9128. not photo_filename
  9129. and data.get("timelapse_was_active")
  9130. and not print_dispatch_context.end_gcode_injected(printer_id)
  9131. ):
  9132. try:
  9133. async with async_session() as db:
  9134. from backend.app.api.routes.settings import get_setting
  9135. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  9136. if restore_setting is None or restore_setting.lower() == "true":
  9137. max_z = await _max_z_for_current_print(
  9138. printer_id, data, logger, bound_archive_id, notify_plate_id
  9139. )
  9140. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  9141. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  9142. plate_restored_z = max_z
  9143. except Exception as e:
  9144. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  9145. # Fallback chain: external camera → buffered live frame →
  9146. # fresh RTSP capture. Only runs if the timelapse path above
  9147. # didn't already produce a photo.
  9148. # Chamber light for the live capture below (#1655).
  9149. async with camera_light(printer if not photo_filename else None):
  9150. if not photo_filename:
  9151. if printer.external_camera_enabled and printer.external_camera_url:
  9152. logger.info("[PHOTO-BG] Using external camera")
  9153. from backend.app.api.routes.camera import live_frame_for_capture
  9154. from backend.app.services.external_camera import capture_frame
  9155. # #2707: the second half of the finish-photo failure — the
  9156. # pre-capture and this fallback both collided with the live
  9157. # view. None here continues down the fallback chain.
  9158. defer, buffered = live_frame_for_capture(printer_id)
  9159. if defer:
  9160. frame_data = buffered
  9161. else:
  9162. frame_data = await capture_frame(
  9163. printer.external_camera_url,
  9164. printer.external_camera_type or "mjpeg",
  9165. snapshot_url=printer.external_camera_snapshot_url,
  9166. )
  9167. if frame_data:
  9168. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  9169. photos_dir = archive_dir / "photos"
  9170. photos_dir.mkdir(parents=True, exist_ok=True)
  9171. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9172. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9173. photo_path = photos_dir / photo_filename
  9174. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  9175. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  9176. else:
  9177. # Check if camera stream is active - use buffered frame to avoid freeze
  9178. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  9179. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  9180. active_chamber_for_printer = [
  9181. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  9182. ]
  9183. buffered_frame = get_buffered_frame(printer_id)
  9184. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  9185. # Use frame from active stream
  9186. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  9187. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  9188. photos_dir = archive_dir / "photos"
  9189. photos_dir.mkdir(parents=True, exist_ok=True)
  9190. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9191. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9192. photo_path = photos_dir / photo_filename
  9193. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  9194. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  9195. else:
  9196. # No active stream - capture new frame
  9197. from backend.app.services.camera import capture_finish_photo
  9198. photo_filename = await capture_finish_photo(
  9199. printer_id=printer_id,
  9200. ip_address=printer.ip_address,
  9201. access_code=printer.access_code,
  9202. model=printer.model,
  9203. archive_dir=archive_dir,
  9204. rotation=getattr(printer, "camera_rotation", 0),
  9205. )
  9206. # Write phase: attach the photo in a fresh short-lived session.
  9207. if photo_filename:
  9208. async with async_session() as db:
  9209. from backend.app.models.archive import PrintArchive
  9210. from backend.app.services.print_log import add_run_photo, run_of
  9211. arch = await db.get(PrintArchive, archive_id)
  9212. # The ended print's own list takes it too: the archive's
  9213. # holds every print's.
  9214. run = await run_of(db, archive_id, completed_run_id) if completed_run_id is not None else None
  9215. if arch is not None:
  9216. photos = arch.photos or []
  9217. photos.append(photo_filename)
  9218. arch.photos = photos
  9219. add_run_photo(run, photo_filename)
  9220. await db.commit()
  9221. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  9222. # The short wait above is bounded so a slow printer can't hold up
  9223. # the print-complete notification, which is what the caller is
  9224. # blocking on. When it ran out with the video still on its way,
  9225. # keep waiting off to the side and add the better frame to the
  9226. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  9227. # users, whose videos routinely take minutes to transfer, never get
  9228. # the pre-bed-drop framing this path exists to provide.
  9229. #
  9230. # Spawned here rather than at the point the wait gave up: both this
  9231. # function and the upgrade do a read-modify-write on `photos`, and
  9232. # the live-camera fallback above can take tens of seconds. Starting
  9233. # the upgrade before that write means the two can interleave and one
  9234. # silently drops the other's entry, leaving a JPEG on disk that the
  9235. # gallery never lists.
  9236. if timelapse_still_pending:
  9237. from backend.app.services import archive_work
  9238. spawn_background_task(
  9239. archive_work.held_while(
  9240. archive_id,
  9241. _upgrade_finish_photo_from_timelapse(
  9242. archive_id,
  9243. archive_dir,
  9244. rotation=getattr(printer, "camera_rotation", 0),
  9245. run_id=completed_run_id,
  9246. ),
  9247. ),
  9248. name=f"finish-photo-upgrade-{archive_id}",
  9249. )
  9250. return photo_filename
  9251. except Exception as e:
  9252. logger.warning("[PHOTO-BG] Failed: %s", e)
  9253. return None
  9254. finally:
  9255. # #2547: we raised the plate, so we owe the move back down — even if
  9256. # the capture in between threw. Otherwise the user finds the print
  9257. # pinned under the nozzle.
  9258. if plate_restored_z is not None:
  9259. try:
  9260. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  9261. except Exception as e:
  9262. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  9263. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  9264. # Photo capture task - result will be used by notifications
  9265. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  9266. log_timing("Background tasks scheduled (energy, photo)")
  9267. # Also run smart plug, notifications, and maintenance as background tasks
  9268. print_status = data.get("status", "completed")
  9269. async def _background_smart_plug():
  9270. """Handle smart plug automation in background."""
  9271. try:
  9272. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  9273. async with async_session() as db:
  9274. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  9275. logger.info("[AUTO-OFF-BG] Completed")
  9276. except Exception as e:
  9277. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  9278. async def _background_notifications(finish_photo_filename: str | None = None):
  9279. """Send print complete notifications in background."""
  9280. try:
  9281. logger.info(
  9282. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  9283. )
  9284. async with async_session() as db:
  9285. from backend.app.models.archive import PrintArchive
  9286. from backend.app.models.printer import Printer
  9287. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9288. printer = result.scalar_one_or_none()
  9289. printer_name = printer.name if printer else f"Printer {printer_id}"
  9290. archive_data = None
  9291. if archive_id:
  9292. from backend.app.models.print_log import PrintLogEntry
  9293. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  9294. archive = archive_result.scalar_one_or_none()
  9295. # The run that ended: the archive shows its latest, which
  9296. # with another plate of it printing elsewhere is not this.
  9297. run = await db.get(PrintLogEntry, completed_run_id) if completed_run_id is not None else None
  9298. run_started = run.started_at if run is not None else archive.started_at if archive else None
  9299. run_completed = run.completed_at if run is not None else archive.completed_at if archive else None
  9300. if archive:
  9301. # Actual elapsed time from started_at/completed_at when both are
  9302. # populated (every terminal status sets completed_at after #1198).
  9303. # Falls back to None so the notification path can decide whether to
  9304. # render the slicer estimate as a last resort.
  9305. actual_time_seconds = None
  9306. # Unknown for a completion reconciled at reconnect: the
  9307. # print ended while the printer was offline and
  9308. # completed_at is the reconnect, so the gap would read
  9309. # as the duration -- 14 h for a night offline (DB-C9).
  9310. # An estimated end (#3310) gives the estimate.
  9311. if (
  9312. run_started
  9313. and run_completed
  9314. and (not data.get("_reconciled") or data.get("_reconciled_completed_at"))
  9315. ):
  9316. elapsed = (run_completed - run_started).total_seconds()
  9317. if elapsed > 0:
  9318. actual_time_seconds = int(elapsed)
  9319. archive_data = {
  9320. "print_time_seconds": archive.print_time_seconds,
  9321. "actual_time_seconds": actual_time_seconds,
  9322. "actual_filament_grams": archive.filament_used_grams,
  9323. "failure_reason": run.failure_reason if run is not None else archive.failure_reason,
  9324. "created_by_id": archive.created_by_id,
  9325. }
  9326. # Scale filament usage for partial prints
  9327. if print_status != "completed" and archive.filament_used_grams:
  9328. progress = data.get("progress") or 0
  9329. scale = _partial_progress_scale(progress)
  9330. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  9331. archive_data["progress"] = progress
  9332. # Pass per-slot data from archive.extra_data
  9333. if archive.extra_data and archive.extra_data.get("filament_slots"):
  9334. slots = archive.extra_data["filament_slots"]
  9335. if print_status != "completed":
  9336. scale = _partial_progress_scale(data.get("progress"))
  9337. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  9338. archive_data["filament_slots"] = slots
  9339. # Scope project-summed totals down to the plate that was
  9340. # actually printed — see _scope_notification_archive_data_to_plate
  9341. # for the why (#1785).
  9342. archive_data = _scope_notification_archive_data_to_plate(
  9343. archive_data,
  9344. archive.file_path,
  9345. notify_plate_id,
  9346. print_status,
  9347. data.get("progress"),
  9348. app_settings.base_dir,
  9349. )
  9350. # Enrich filament_grams from usage_results when archive has no 3MF data
  9351. if not archive_data.get("actual_filament_grams") and usage_results:
  9352. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  9353. if total_from_usage > 0:
  9354. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  9355. # Pass usage tracker results for AMS slot info in notifications
  9356. if usage_results:
  9357. archive_data["usage_results"] = usage_results
  9358. # Which archive and print it was (archive redesign).
  9359. archive_data["archive_id"] = archive_id
  9360. archive_data["run_id"] = completed_run_id
  9361. # Add finish photo URL and image bytes if available
  9362. if finish_photo_filename:
  9363. photo_url, photo_bytes = await _finish_photo_for_notification(
  9364. db, archive, archive_id, finish_photo_filename
  9365. )
  9366. if photo_url:
  9367. archive_data["finish_photo_url"] = photo_url
  9368. if photo_bytes:
  9369. archive_data["image_data"] = photo_bytes
  9370. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  9371. await notification_service.on_print_complete(
  9372. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  9373. )
  9374. else:
  9375. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  9376. # Post-print outcome confirmation (#1898). Runs in this
  9377. # background task so the finish photo fetched above rides
  9378. # along with the prompt.
  9379. if print_status == "completed" and archive_id:
  9380. await _dispatch_outcome_confirmation_safely(
  9381. db, printer_id, printer_name, data, archive_id, archive_data, run_id=completed_run_id
  9382. )
  9383. # Send user-specific email notification
  9384. if archive_data:
  9385. created_by_id = archive_data.get("created_by_id")
  9386. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  9387. await _dispatch_user_print_email(
  9388. print_status,
  9389. created_by_id,
  9390. printer_name,
  9391. raw_filename,
  9392. db,
  9393. image_data=archive_data.get("image_data"),
  9394. finish_photo_url=archive_data.get("finish_photo_url"),
  9395. )
  9396. logger.info("[NOTIFY-BG] Completed")
  9397. except Exception as e:
  9398. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  9399. async def _background_maintenance_check():
  9400. """Check for maintenance due in background."""
  9401. if print_status != "completed":
  9402. return
  9403. try:
  9404. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  9405. async with async_session() as db:
  9406. from backend.app.models.printer import Printer
  9407. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9408. printer = result.scalar_one_or_none()
  9409. printer_name = printer.name if printer else f"Printer {printer_id}"
  9410. await ensure_default_types(db)
  9411. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  9412. attention = [
  9413. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  9414. ]
  9415. items_needing_attention = [
  9416. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  9417. for item in attention
  9418. ]
  9419. if items_needing_attention:
  9420. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  9421. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  9422. # MQTT relay - publish maintenance alerts
  9423. for item in attention:
  9424. current_value, threshold, unit = maintenance_alert_values(item)
  9425. try:
  9426. await mqtt_relay.on_maintenance_alert(
  9427. printer_id=printer_id,
  9428. printer_name=printer_name,
  9429. maintenance_type=item.maintenance_type_name,
  9430. current_value=current_value,
  9431. threshold=threshold,
  9432. unit=unit,
  9433. )
  9434. except Exception:
  9435. pass # Don't fail if MQTT fails
  9436. else:
  9437. logger.info("[MAINT-BG] Completed (no items need attention)")
  9438. except Exception as e:
  9439. logger.warning("[MAINT-BG] Failed: %s", e)
  9440. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  9441. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  9442. # Notification task waits for photo capture to complete first (with timeout).
  9443. # When a timelapse was recording, photo sourcing polls the per-print
  9444. # timelapse for up to 60s (#1397) — extend the budget so the notification
  9445. # carries the correct bed-up photo instead of falling through to the
  9446. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  9447. #
  9448. # #2547: both budgets now have to cover a plate restore as well.
  9449. #
  9450. # Without timelapse, the wait is on the moment producer, which raises the
  9451. # plate before its grab — so this has to outlast that producer's own budget.
  9452. #
  9453. # With timelapse, the capture polls up to
  9454. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  9455. # falls back to a live grab, which is the case that raises the plate. At the
  9456. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  9457. # restore would have moved the plate for a photo nobody waited for.
  9458. photo_wait_timeout = (
  9459. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  9460. if data.get("timelapse_was_active")
  9461. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  9462. )
  9463. async def _photo_then_notify():
  9464. """Wait for photo capture, then send notification with photo URL."""
  9465. finish_photo = None
  9466. try:
  9467. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  9468. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  9469. except TimeoutError:
  9470. logger.warning(
  9471. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  9472. photo_wait_timeout,
  9473. )
  9474. except Exception as e:
  9475. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  9476. try:
  9477. await _background_notifications(finish_photo)
  9478. except Exception as e:
  9479. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  9480. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  9481. # Stitch external camera layer timelapse if session was active
  9482. print_status = data.get("status", "completed")
  9483. async def _background_layer_timelapse():
  9484. """Stitch layer timelapse and attach to archive."""
  9485. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  9486. try:
  9487. if print_status == "completed":
  9488. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  9489. # The run the frames belong to, read before the stitch: it can
  9490. # take long enough for the archive to start printing again.
  9491. run_started_at = None
  9492. if archive_id:
  9493. async with async_session() as db:
  9494. run_archive = await ArchiveService(db).get_archive(archive_id)
  9495. run_started_at = run_archive.started_at if run_archive else None
  9496. timelapse_path = await tl_complete(printer_id)
  9497. if timelapse_path and archive_id:
  9498. await _attach_layer_timelapse(
  9499. archive_id, timelapse_path, notify_plate_id, run_started_at, run_id=completed_run_id
  9500. )
  9501. elif timelapse_path:
  9502. # Timelapse created but no archive - just clean up
  9503. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  9504. else:
  9505. # Print failed or cancelled - cancel timelapse session
  9506. cancel_session(printer_id)
  9507. logger.info(
  9508. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  9509. )
  9510. except Exception as e:
  9511. logger.warning("[LAYER-TL] Failed: %s", e)
  9512. # A completed print's session left _active_sessions when its stitch
  9513. # began: the one there now belongs to the next print, which may have
  9514. # started during the stitch, and must not lose its frames.
  9515. if print_status != "completed":
  9516. try:
  9517. cancel_session(printer_id)
  9518. except Exception:
  9519. pass # Best-effort timelapse session cancellation on error
  9520. from backend.app.services import archive_work
  9521. # Held through the stitch, which can take longer than a merge waits after
  9522. # a print (archive redesign P2).
  9523. layer_timelapse = _background_layer_timelapse()
  9524. if archive_id:
  9525. layer_timelapse = archive_work.held_while(archive_id, layer_timelapse)
  9526. spawn_background_task(layer_timelapse, name="background-layer-timelapse")
  9527. log_timing("All background tasks scheduled")
  9528. # Auto-scan for timelapse if recording was active during the print
  9529. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  9530. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  9531. # Schedule timelapse scan as background task with retries
  9532. # The printer needs time to encode the video after print completion
  9533. _schedule_timelapse_scan(archive_id, printer_id, plate_id=notify_plate_id, run_id=completed_run_id)
  9534. log_timing("Timelapse scan scheduled")
  9535. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  9536. # AMS sensor history recording
  9537. _ams_history_task: asyncio.Task | None = None
  9538. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  9539. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  9540. def _retention_days(stored: str | None, default: int) -> int:
  9541. """A history retention setting as days to keep: at least 1, the default
  9542. when unset or unreadable. A stored 0 or less (the API took one before it
  9543. had a minimum) would put the cutoff at now and delete all history."""
  9544. try:
  9545. return max(1, int(stored)) if stored is not None else default
  9546. except (TypeError, ValueError):
  9547. return default
  9548. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  9549. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  9550. _ams_alarm_cooldown: dict[str, datetime] = {}
  9551. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  9552. # (printer_id, ams_id) already reported as sending the drop index and no
  9553. # percentage. Logged once each so a supported printer that turns out to do this
  9554. # shows up in a support bundle rather than as a user wondering where the
  9555. # humidity reading went -- see the note at the read site below (#3140).
  9556. _ams_index_only_logged: set[tuple[int, int]] = set()
  9557. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  9558. """Temperature at which the AMS alarm fires, falling back to the display band.
  9559. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  9560. when a notification was sent as well, which is why a room above it made the
  9561. alarm fire once an hour for as long as the weather lasted -- and the only way
  9562. to stop that was to raise the display band and lose the colour that says the
  9563. unit is warm (#2905).
  9564. Unset resolves to the fair threshold, so an install that never sets one is
  9565. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  9566. so that arrives here as a string and is handled by the same branch as any
  9567. other unparseable value -- there is no separate sentinel to keep in sync.
  9568. A non-positive value is refused rather than honoured: zero would alarm
  9569. permanently, and it is far more likely to be a cleared field than a
  9570. deliberate choice.
  9571. """
  9572. if raw_alarm_value is None:
  9573. return fair_threshold
  9574. try:
  9575. value = float(raw_alarm_value)
  9576. except (TypeError, ValueError):
  9577. return fair_threshold
  9578. if not math.isfinite(value) or value <= 0:
  9579. return fair_threshold
  9580. return value
  9581. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  9582. # through a cycle and the cool-down after it (#1802). Stored in the settings
  9583. # table rather than alongside _ams_alarm_cooldown above, because a restart
  9584. # partway through a cool-down would otherwise resume alarming about heat the
  9585. # user asked for — the same internal-timestamp-row pattern as
  9586. # support.py's debug_logging_enabled_at.
  9587. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  9588. # Upper bound on that suppression. The latch normally clears as soon as the unit
  9589. # reads at or below the threshold; see utils.ams_drying for why this cap only
  9590. # matters when it never does.
  9591. AMS_DRYING_GRACE_MINUTES = 120
  9592. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  9593. """Read the persisted per-AMS drying latch, dropping entries out of window.
  9594. Anything older than the grace cap would expire on its next visit anyway, so
  9595. discarding it here costs nothing and stops rows for deleted printers from
  9596. accumulating.
  9597. Stamps ahead of now get two defences, because a box whose clock jumps
  9598. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  9599. ones are discarded outright, and the rest are clamped to now. Without the
  9600. clamp the cap would measure from a moment that has not happened yet and hold
  9601. the alarm quiet for the skew on top of the cap. One unnecessary notification
  9602. after a clock jump is a far better failure than an alarm silently disabled
  9603. for hours.
  9604. """
  9605. from backend.app.models.settings import Settings
  9606. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9607. setting = result.scalar_one_or_none()
  9608. if not setting or not setting.value:
  9609. return {}
  9610. try:
  9611. raw = json.loads(setting.value)
  9612. except (ValueError, TypeError):
  9613. return {} # Corrupted row → no latch, alarms behave as they did before
  9614. if not isinstance(raw, dict):
  9615. return {}
  9616. now = datetime.now(timezone.utc)
  9617. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  9618. latch: dict[str, datetime] = {}
  9619. for key, value in raw.items():
  9620. try:
  9621. stamp = datetime.fromisoformat(str(value))
  9622. except (ValueError, TypeError):
  9623. continue
  9624. if stamp.tzinfo is None:
  9625. stamp = stamp.replace(tzinfo=timezone.utc)
  9626. if not (now - window <= stamp <= now + window):
  9627. continue
  9628. # Nothing may sit in the future: suppression is measured as now minus
  9629. # the stamp, so a stamp ahead of now would extend it by the skew on top
  9630. # of the cap. Clamping the survivors keeps the cap an actual cap.
  9631. latch[str(key)] = min(stamp, now)
  9632. return latch
  9633. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  9634. """Persist the latch, writing only when it actually changed.
  9635. Adds the session change but does not commit — the caller's own commit
  9636. carries it, so the latch lands in the same transaction as the sensor rows
  9637. that produced it.
  9638. """
  9639. from backend.app.models.settings import Settings
  9640. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  9641. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9642. setting = result.scalar_one_or_none()
  9643. if setting is None:
  9644. # Don't create the row on installs that never dry anything.
  9645. if payload != "{}":
  9646. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  9647. elif setting.value != payload:
  9648. setting.value = payload
  9649. def _ams_has_filament(ams_data: dict) -> bool:
  9650. """True if this AMS unit has at least one tray slot holding filament.
  9651. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  9652. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  9653. still report sensor readings, but those readings are ambient and not
  9654. actionable: no filament to dry, no humidity to push down. #1619 — gate
  9655. humidity/temperature alarms on this check so empty units don't generate
  9656. hourly noise. Sensor history still records regardless so the UI charts
  9657. stay continuous.
  9658. Fallback path inspects the `tray` array's `tray_type` fields for setups
  9659. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  9660. """
  9661. bits = ams_data.get("tray_exist_bits")
  9662. if isinstance(bits, str) and bits.strip():
  9663. try:
  9664. return int(bits, 16) > 0
  9665. except ValueError:
  9666. pass
  9667. trays = ams_data.get("tray")
  9668. if isinstance(trays, list):
  9669. return any(
  9670. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  9671. )
  9672. return False
  9673. async def record_ams_history():
  9674. """Background task to record AMS humidity and temperature data."""
  9675. logger = logging.getLogger(__name__)
  9676. # Wait a short time for MQTT connections to establish on startup
  9677. await asyncio.sleep(10)
  9678. while True:
  9679. try:
  9680. from backend.app.models.ams_history import AMSSensorHistory
  9681. from backend.app.models.printer import Printer
  9682. from backend.app.models.settings import Settings
  9683. async with async_session() as db:
  9684. # Get all active printers
  9685. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9686. printers = result.scalars().all()
  9687. # Get alarm thresholds from settings
  9688. humidity_threshold = 60.0 # Default: fair threshold
  9689. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  9690. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  9691. setting = result.scalar_one_or_none()
  9692. if setting:
  9693. try:
  9694. humidity_threshold = float(setting.value)
  9695. except (ValueError, TypeError):
  9696. pass # Keep default threshold if stored value is invalid
  9697. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  9698. setting = result.scalar_one_or_none()
  9699. if setting:
  9700. try:
  9701. temp_fair_threshold = float(setting.value)
  9702. except (ValueError, TypeError):
  9703. pass # Keep default threshold if stored value is invalid
  9704. # The alarm gets its own threshold, seeded from the resolved fair
  9705. # value so an install that has never set one behaves exactly as
  9706. # it did before (#2905). ams_temp_fair decides when the card turns
  9707. # amber; 35 C is a reasonable place to change a colour and not a
  9708. # reasonable place to page someone. A room above it makes the
  9709. # alarm fire once an hour for as long as the weather lasts, and
  9710. # the only way to stop it was to raise the display band and lose
  9711. # the colour that says the unit is warm.
  9712. #
  9713. # An unset value is stored as the literal "None", which the except
  9714. # below swallows the same way it swallows garbage -- so the
  9715. # fallback costs nothing and needs no sentinel of its own.
  9716. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  9717. setting = result.scalar_one_or_none()
  9718. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  9719. temp_fair_threshold, setting.value if setting else None
  9720. )
  9721. # Per-filament humidity threshold overrides (#1605) — resolved
  9722. # per-AMS below from the loaded tray types. Reuses the same
  9723. # resolver as the auto-drying scheduler so behavior stays in
  9724. # lockstep across both consumers.
  9725. from backend.app.services.print_scheduler import PrintScheduler
  9726. per_type_humidity_thresholds: dict[str, int] = {}
  9727. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  9728. setting = result.scalar_one_or_none()
  9729. if setting and setting.value:
  9730. try:
  9731. raw = json.loads(setting.value)
  9732. if isinstance(raw, dict):
  9733. for k, v in raw.items():
  9734. try:
  9735. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  9736. v
  9737. )
  9738. except (TypeError, ValueError):
  9739. continue
  9740. except (ValueError, TypeError):
  9741. pass # Invalid JSON → no overrides, fall through to global threshold
  9742. # Per-AMS drying latch (#1802), loaded once per pass and written
  9743. # back below only if a unit changed it.
  9744. drying_latch = await _load_ams_drying_latch(db)
  9745. drying_latch_before = dict(drying_latch)
  9746. recorded_count = 0
  9747. for printer in printers:
  9748. # Get current state from printer manager
  9749. state = printer_manager.get_status(printer.id)
  9750. if not state or not state.connected or not state.raw_data:
  9751. continue # Skip disconnected printers - don't use stale data
  9752. raw_data = state.raw_data
  9753. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  9754. continue
  9755. # Record data for each AMS unit
  9756. for ams_data in raw_data["ams"]:
  9757. ams_id = int(ams_data.get("id", 0))
  9758. # Percentage only. The 1-5 index is inverted, so
  9759. # charting it as a percentage drew the wettest units as
  9760. # the driest (#3140); a unit that reports no percentage
  9761. # leaves a gap in the chart instead. See
  9762. # utils/ams_humidity.
  9763. humidity = ams_humidity_percent(ams_data)
  9764. # No supported printer is known to send the index
  9765. # alone -- the report came from unsupported firmware,
  9766. # and no install has been seen using the old fallback.
  9767. # "Known" is doing work there, so say so once per unit:
  9768. # the alternative is a silent blank card.
  9769. if humidity is None and ams_data.get("humidity") is not None:
  9770. unit_key = (printer.id, ams_id)
  9771. if unit_key not in _ams_index_only_logged:
  9772. _ams_index_only_logged.add(unit_key)
  9773. logger.info(
  9774. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  9775. "percentage. The index is inverted and is not shown as a percentage "
  9776. "(#3140), so this unit has no humidity reading, chart or alarm. "
  9777. "Please report this with the printer and AMS firmware versions.",
  9778. printer.name,
  9779. ams_id,
  9780. )
  9781. # Get temperature
  9782. temperature = None
  9783. temp_str = ams_data.get("temp")
  9784. if temp_str is not None:
  9785. try:
  9786. temperature = float(temp_str)
  9787. except (ValueError, TypeError):
  9788. pass # Skip unparseable temperature value
  9789. # Skip if no data
  9790. if humidity is None and temperature is None:
  9791. continue
  9792. # Record the data point
  9793. history = AMSSensorHistory(
  9794. printer_id=printer.id,
  9795. ams_id=ams_id,
  9796. humidity=humidity,
  9797. # Both columns hold the same reading now that the
  9798. # index can no longer reach ``humidity``. Writing it
  9799. # through the same value also stops a genuine 0%
  9800. # from being stored as NULL, which the old truthiness
  9801. # test did.
  9802. humidity_raw=humidity,
  9803. temperature=temperature,
  9804. )
  9805. db.add(history)
  9806. recorded_count += 1
  9807. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  9808. is_ams_ht = ams_id >= 128
  9809. if is_ams_ht:
  9810. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  9811. else:
  9812. ams_label = f"AMS-{chr(65 + ams_id)}"
  9813. # Skip alarm dispatch for empty AMS units — humidity /
  9814. # temperature readings are ambient with no filament to
  9815. # protect, and the hourly notification just becomes
  9816. # noise. Sensor history was already recorded above so
  9817. # the UI charts stay continuous (#1619). Per-AMS check
  9818. # so a multi-AMS setup with one loaded + one empty
  9819. # still alarms on the loaded unit.
  9820. if not _ams_has_filament(ams_data):
  9821. continue
  9822. # Resolve per-filament humidity threshold for this AMS
  9823. # unit (#1605). Falls back to the global ams_humidity_fair
  9824. # when no per-type overrides are configured.
  9825. trays = ams_data.get("tray", []) or []
  9826. effective_humidity_threshold = float(
  9827. PrintScheduler.resolve_humidity_threshold(
  9828. trays, per_type_humidity_thresholds, int(humidity_threshold)
  9829. )
  9830. )
  9831. # Check humidity alarm (only if above threshold)
  9832. if humidity is not None and humidity > effective_humidity_threshold:
  9833. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  9834. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9835. now = datetime.now(timezone.utc)
  9836. if (
  9837. last_alarm is None
  9838. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9839. ):
  9840. _ams_alarm_cooldown[cooldown_key] = now
  9841. logger.info(
  9842. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  9843. )
  9844. try:
  9845. # Call different notification method based on AMS type
  9846. if is_ams_ht:
  9847. await notification_service.on_ams_ht_humidity_high(
  9848. printer.id,
  9849. printer.name,
  9850. ams_label,
  9851. humidity,
  9852. effective_humidity_threshold,
  9853. db,
  9854. )
  9855. else:
  9856. await notification_service.on_ams_humidity_high(
  9857. printer.id,
  9858. printer.name,
  9859. ams_label,
  9860. humidity,
  9861. effective_humidity_threshold,
  9862. db,
  9863. )
  9864. except Exception as e:
  9865. logger.warning("Failed to send humidity alarm: %s", e)
  9866. # A drying cycle heats the unit far past ams_temp_fair on
  9867. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  9868. # AMS-HT, against a 35 C default — so the alarm fired
  9869. # once an hour for the whole cycle and kept firing while
  9870. # the unit cooled back down (#1802). Latch on the
  9871. # firmware's own drying state and hold until the reading
  9872. # returns to normal. Humidity is deliberately left alone:
  9873. # it falls during drying, which is the whole point.
  9874. latch_key = f"{printer.id}:{ams_id}"
  9875. # The latch releases at `threshold`, so it takes the alarm
  9876. # number too. Handing it the display band would strand the
  9877. # latch on any unit that settles back above it -- a room
  9878. # where the AMS rests at 37.7 C never returns under a 35 C
  9879. # band, so the latch could only expire on the grace cap
  9880. # rather than releasing when the unit had actually cooled.
  9881. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  9882. drying_active=is_drying_active(ams_data),
  9883. temperature=temperature,
  9884. threshold=temp_alarm_threshold,
  9885. latched_at=drying_latch.get(latch_key),
  9886. now=datetime.now(timezone.utc),
  9887. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  9888. )
  9889. if new_latch is None:
  9890. drying_latch.pop(latch_key, None)
  9891. else:
  9892. drying_latch[latch_key] = new_latch
  9893. # Check temperature alarm (only if above threshold)
  9894. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  9895. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  9896. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9897. now = datetime.now(timezone.utc)
  9898. if (
  9899. last_alarm is None
  9900. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9901. ):
  9902. _ams_alarm_cooldown[cooldown_key] = now
  9903. logger.info(
  9904. f"Sending temperature alarm for {printer.name} {ams_label}: "
  9905. f"{temperature}°C > {temp_alarm_threshold}°C"
  9906. )
  9907. try:
  9908. # Call different notification method based on AMS type
  9909. if is_ams_ht:
  9910. # The reported threshold has to be the one
  9911. # that fired, or the message says "> 35 °C"
  9912. # while firing at 45.
  9913. await notification_service.on_ams_ht_temperature_high(
  9914. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9915. )
  9916. else:
  9917. await notification_service.on_ams_temperature_high(
  9918. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9919. )
  9920. except Exception as e:
  9921. logger.warning("Failed to send temperature alarm: %s", e)
  9922. if drying_latch != drying_latch_before:
  9923. await _save_ams_drying_latch(db, drying_latch)
  9924. await db.commit()
  9925. if recorded_count > 0:
  9926. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  9927. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  9928. global _ams_cleanup_counter
  9929. _ams_cleanup_counter += 1
  9930. if _ams_cleanup_counter >= 288:
  9931. _ams_cleanup_counter = 0
  9932. # Get retention days from settings
  9933. from backend.app.models.settings import Settings
  9934. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  9935. setting = result.scalar_one_or_none()
  9936. retention_days = _retention_days(setting.value if setting else None, AMS_HISTORY_RETENTION_DAYS)
  9937. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9938. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  9939. await db.commit()
  9940. if result.rowcount > 0:
  9941. logger.info(
  9942. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  9943. )
  9944. # Wait until next recording interval
  9945. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  9946. except asyncio.CancelledError:
  9947. break
  9948. except Exception as e:
  9949. logger.warning("AMS history recording failed: %s", e)
  9950. await asyncio.sleep(60) # Wait a bit before retrying
  9951. def start_ams_history_recording():
  9952. """Start the AMS history recording background task."""
  9953. global _ams_history_task
  9954. if _ams_history_task is None:
  9955. _ams_history_task = asyncio.create_task(record_ams_history())
  9956. logging.getLogger(__name__).info("AMS history recording started")
  9957. def stop_ams_history_recording():
  9958. """Stop the AMS history recording background task."""
  9959. global _ams_history_task
  9960. if _ams_history_task:
  9961. _ams_history_task.cancel()
  9962. _ams_history_task = None
  9963. logging.getLogger(__name__).info("AMS history recording stopped")
  9964. # Printer sensor history recording (nozzle / bed / chamber)
  9965. _printer_sensor_history_task: asyncio.Task | None = None
  9966. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  9967. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  9968. _printer_sensor_cleanup_counter = 0
  9969. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  9970. # MQTT parser writes, so we don't need to handle per-model field aliases here
  9971. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  9972. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  9973. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  9974. _SENSOR_TARGET_KEYS = {
  9975. "nozzle": "nozzle_target",
  9976. "nozzle_2": "nozzle_2_target",
  9977. "bed": "bed_target",
  9978. "chamber": "chamber_target",
  9979. }
  9980. async def record_printer_sensor_history():
  9981. """Background task to record nozzle / bed / chamber readings.
  9982. Pulls from `state.temperatures` (already normalised across all printer
  9983. models by the MQTT parser) rather than re-parsing raw_data, so we get
  9984. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  9985. """
  9986. logger = logging.getLogger(__name__)
  9987. await asyncio.sleep(10)
  9988. while True:
  9989. try:
  9990. from backend.app.models.printer import Printer
  9991. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  9992. from backend.app.models.settings import Settings
  9993. async with async_session() as db:
  9994. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9995. printers = result.scalars().all()
  9996. recorded_count = 0
  9997. for printer in printers:
  9998. state = printer_manager.get_status(printer.id)
  9999. if not state or not state.connected:
  10000. continue
  10001. temps = getattr(state, "temperatures", None) or {}
  10002. if not isinstance(temps, dict):
  10003. continue
  10004. for kind in _SENSOR_KINDS:
  10005. if kind not in temps:
  10006. continue
  10007. try:
  10008. value = float(temps[kind])
  10009. except (ValueError, TypeError):
  10010. continue
  10011. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  10012. target_val: float | None = None
  10013. if target_raw is not None:
  10014. try:
  10015. target_val = float(target_raw)
  10016. except (ValueError, TypeError):
  10017. target_val = None
  10018. db.add(
  10019. PrinterSensorHistory(
  10020. printer_id=printer.id,
  10021. sensor_kind=kind,
  10022. value=value,
  10023. target=target_val,
  10024. )
  10025. )
  10026. recorded_count += 1
  10027. await db.commit()
  10028. if recorded_count > 0:
  10029. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  10030. # Periodic cleanup — once every ~24h at this interval.
  10031. global _printer_sensor_cleanup_counter
  10032. _printer_sensor_cleanup_counter += 1
  10033. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  10034. if _printer_sensor_cleanup_counter >= cleanup_every:
  10035. _printer_sensor_cleanup_counter = 0
  10036. result = await db.execute(
  10037. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  10038. )
  10039. setting = result.scalar_one_or_none()
  10040. retention_days = _retention_days(
  10041. setting.value if setting else None, PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  10042. )
  10043. cutoff = utcnow_naive() - timedelta(days=retention_days)
  10044. cleanup = await db.execute(
  10045. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  10046. )
  10047. await db.commit()
  10048. if cleanup.rowcount > 0:
  10049. logger.info(
  10050. "Cleaned up %s old printer sensor history entries (older than %s days)",
  10051. cleanup.rowcount,
  10052. retention_days,
  10053. )
  10054. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  10055. except asyncio.CancelledError:
  10056. break
  10057. except Exception as e:
  10058. logger.warning("Printer sensor history recording failed: %s", e)
  10059. await asyncio.sleep(60)
  10060. def start_printer_sensor_history_recording():
  10061. global _printer_sensor_history_task
  10062. if _printer_sensor_history_task is None:
  10063. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  10064. logging.getLogger(__name__).info("Printer sensor history recording started")
  10065. def stop_printer_sensor_history_recording():
  10066. global _printer_sensor_history_task
  10067. if _printer_sensor_history_task:
  10068. _printer_sensor_history_task.cancel()
  10069. _printer_sensor_history_task = None
  10070. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  10071. # Printer runtime tracking
  10072. _runtime_tracking_task: asyncio.Task | None = None
  10073. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  10074. # Printers the runtime tracker has seen connected since startup. One of them
  10075. # going offline clears its timestamp, so the time it was away is not counted
  10076. # when it comes back printing (DB-C5). A printer not yet seen -- still
  10077. # connecting after a restart -- keeps it for a grace period: a print that ran
  10078. # on through a Bambuddy restart is counted from the stored timestamp, as before.
  10079. _runtime_seen_connected: set[int] = set()
  10080. # A printer never seen connected this long after the tracker started is
  10081. # offline, not still connecting: its stored timestamp predates a gap too.
  10082. RUNTIME_STARTUP_GRACE_SECONDS = 120
  10083. async def track_printer_runtime():
  10084. """Background task to track printer active runtime (RUNNING state only).
  10085. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  10086. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  10087. which track mechanical wear. Pause time has no motion and no wear, so
  10088. counting it inflates maintenance warnings (#1521).
  10089. """
  10090. logger = logging.getLogger(__name__)
  10091. # Wait for MQTT connections to establish on startup
  10092. await asyncio.sleep(15)
  10093. started = time.monotonic()
  10094. while True:
  10095. try:
  10096. from backend.app.models.printer import Printer
  10097. # Fetch printer IDs in a short-lived read-only session
  10098. async with async_session() as db:
  10099. result = await db.execute(
  10100. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  10101. Printer.is_active.is_(True)
  10102. )
  10103. )
  10104. printer_rows = result.all()
  10105. now = datetime.now(timezone.utc)
  10106. updated_count = 0
  10107. # Update each printer in its own short session to minimise write-lock
  10108. # hold time and avoid blocking critical commits like queue status
  10109. # updates (#897).
  10110. for pid, pname, runtime_secs, last_update in printer_rows:
  10111. state = printer_manager.get_status(pid)
  10112. if not state:
  10113. logger.debug("[%s] Runtime tracking: no state available", pname)
  10114. continue
  10115. if not state.connected:
  10116. logger.debug("[%s] Runtime tracking: not connected", pname)
  10117. offline = pid in _runtime_seen_connected or (
  10118. time.monotonic() - started > RUNTIME_STARTUP_GRACE_SECONDS
  10119. )
  10120. if offline and last_update is not None:
  10121. try:
  10122. async with async_session() as db:
  10123. printer = await db.get(Printer, pid)
  10124. if printer:
  10125. printer.last_runtime_update = None
  10126. await db.commit()
  10127. except Exception as e:
  10128. # Still marked: the next offline tick tries again.
  10129. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  10130. continue
  10131. _runtime_seen_connected.discard(pid)
  10132. continue
  10133. _runtime_seen_connected.add(pid)
  10134. needs_commit = False
  10135. new_runtime = runtime_secs
  10136. new_last_update = last_update
  10137. if state.state == "RUNNING":
  10138. if last_update:
  10139. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  10140. elapsed = (now - lu).total_seconds()
  10141. if elapsed > 0:
  10142. new_runtime = runtime_secs + int(elapsed)
  10143. updated_count += 1
  10144. needs_commit = True
  10145. logger.debug(
  10146. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  10147. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  10148. )
  10149. else:
  10150. needs_commit = True
  10151. logger.debug("[%s] Runtime tracking: first active detection", pname)
  10152. new_last_update = now
  10153. else:
  10154. if last_update is not None:
  10155. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  10156. new_last_update = None
  10157. needs_commit = True
  10158. if needs_commit:
  10159. try:
  10160. async with async_session() as db:
  10161. result = await db.execute(select(Printer).where(Printer.id == pid))
  10162. printer = result.scalar_one_or_none()
  10163. if printer:
  10164. printer.runtime_seconds = new_runtime
  10165. printer.last_runtime_update = new_last_update
  10166. await db.commit()
  10167. except Exception as e:
  10168. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  10169. if updated_count > 0:
  10170. logger.debug("Updated runtime for %s printer(s)", updated_count)
  10171. except asyncio.CancelledError:
  10172. logger.info("Runtime tracking cancelled")
  10173. break
  10174. except Exception as e:
  10175. logger.warning("Runtime tracking failed: %s", e)
  10176. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  10177. def start_runtime_tracking():
  10178. """Start the printer runtime tracking background task."""
  10179. global _runtime_tracking_task
  10180. if _runtime_tracking_task is None:
  10181. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  10182. logging.getLogger(__name__).info("Printer runtime tracking started")
  10183. def stop_runtime_tracking():
  10184. """Stop the printer runtime tracking background task."""
  10185. global _runtime_tracking_task
  10186. if _runtime_tracking_task:
  10187. _runtime_tracking_task.cancel()
  10188. _runtime_tracking_task = None
  10189. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  10190. # SpoolBuddy device watchdog
  10191. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  10192. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  10193. async def _spoolbuddy_watchdog_loop():
  10194. """Periodic check for SpoolBuddy devices that have gone offline."""
  10195. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  10196. while True:
  10197. try:
  10198. await spoolbuddy_watchdog()
  10199. except asyncio.CancelledError:
  10200. break
  10201. except Exception as e:
  10202. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  10203. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  10204. def start_spoolbuddy_watchdog():
  10205. global _spoolbuddy_watchdog_task
  10206. if _spoolbuddy_watchdog_task is None:
  10207. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  10208. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  10209. def stop_spoolbuddy_watchdog():
  10210. global _spoolbuddy_watchdog_task
  10211. if _spoolbuddy_watchdog_task:
  10212. _spoolbuddy_watchdog_task.cancel()
  10213. _spoolbuddy_watchdog_task = None
  10214. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  10215. # Dead-MQTT-session recovery
  10216. #
  10217. # check_staleness() covers the "connected but silent" half-broken session. It
  10218. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  10219. # is the only thing left watching at that point. When paho stops making
  10220. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  10221. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  10222. # offline with the UI open the whole time, recovered only when something
  10223. # happened to nudge it.
  10224. #
  10225. # This loop is that backstop. It only touches printers that had a working
  10226. # session and lost it, and only when the MQTT port still answers — a printer
  10227. # that is simply switched off is left to paho, since rebuilding a client
  10228. # against an unreachable host achieves nothing and would fill the log every
  10229. # night.
  10230. _connection_watchdog_task: asyncio.Task | None = None
  10231. CONNECTION_WATCHDOG_INTERVAL = 60
  10232. # How long a printer must have been silent before we stop trusting paho.
  10233. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  10234. # so a session that is recovering on its own is never interrupted.
  10235. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  10236. # Per-printer floor between rebuild attempts.
  10237. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  10238. _connection_watchdog_last_attempt: dict[int, float] = {}
  10239. async def _recover_dead_printer_sessions() -> int:
  10240. """Rebuild MQTT clients that have been offline too long to still be trying.
  10241. Returns the number of printers a rebuild was attempted for (for tests and
  10242. for the caller's logging). Never raises: one unreachable printer must not
  10243. stop the sweep for the rest of the farm.
  10244. """
  10245. logger = logging.getLogger(__name__)
  10246. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  10247. now = time.monotonic()
  10248. recovered = 0
  10249. for printer_id, client in list(printer_manager._clients.items()):
  10250. try:
  10251. if client.state.connected:
  10252. _connection_watchdog_last_attempt.pop(printer_id, None)
  10253. continue
  10254. # Time since the last inbound message is the age of the last known
  10255. # good session — no extra bookkeeping needed, and it is the same
  10256. # clock is_stale() reads. 0 means this client has never had one:
  10257. # that is the initial-connect path, where paho retrying is the
  10258. # correct and only behaviour, so leave it be.
  10259. last_msg = client._last_message_time
  10260. if not last_msg:
  10261. continue
  10262. offline_for = time.time() - last_msg
  10263. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  10264. continue
  10265. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  10266. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  10267. continue
  10268. if not await check_port(client.ip_address, PORT_MQTT):
  10269. # Switched off, unplugged, or off the network. Paho's retry is
  10270. # the right handler; say so at debug level and move on.
  10271. logger.debug(
  10272. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  10273. "— leaving the reconnect to paho",
  10274. printer_id,
  10275. offline_for,
  10276. )
  10277. _connection_watchdog_last_attempt[printer_id] = now
  10278. continue
  10279. _connection_watchdog_last_attempt[printer_id] = now
  10280. recovered += 1
  10281. logger.warning(
  10282. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  10283. "rebuilding the client with a fresh session (last connect error: %s)",
  10284. printer_id,
  10285. offline_for,
  10286. PORT_MQTT,
  10287. client.last_connect_error or "none recorded",
  10288. )
  10289. # Async context, so this takes the hard-reset path: fresh client_id,
  10290. # paho's QoS 1 queue dropped. That matters — a project_file left
  10291. # unacked on the dead session would otherwise replay into the new
  10292. # one and trip 0500_4003 on the printer (#1136).
  10293. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  10294. except Exception as e:
  10295. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  10296. return recovered
  10297. async def _connection_watchdog_loop():
  10298. logger = logging.getLogger(__name__)
  10299. # Let the initial connects settle before judging anyone offline.
  10300. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  10301. while True:
  10302. try:
  10303. await _recover_dead_printer_sessions()
  10304. except asyncio.CancelledError:
  10305. break
  10306. except Exception as e:
  10307. logger.warning("Connection watchdog sweep failed: %s", e)
  10308. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  10309. def start_connection_watchdog():
  10310. global _connection_watchdog_task
  10311. if _connection_watchdog_task is None:
  10312. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  10313. logging.getLogger(__name__).info("Printer connection watchdog started")
  10314. def stop_connection_watchdog():
  10315. global _connection_watchdog_task
  10316. if _connection_watchdog_task:
  10317. _connection_watchdog_task.cancel()
  10318. _connection_watchdog_task = None
  10319. _connection_watchdog_last_attempt.clear()
  10320. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  10321. # Camera stream orphan cleanup
  10322. _camera_cleanup_task: asyncio.Task | None = None
  10323. CAMERA_CLEANUP_INTERVAL = 60
  10324. # Every this many camera cleanups (about an hour), the timelapse janitor too:
  10325. # kept frames of a failed stitch go after a day, not at the next restart.
  10326. TIMELAPSE_CLEANUP_EVERY = 60
  10327. async def _camera_cleanup_loop():
  10328. """Periodically clean up orphaned ffmpeg processes and timelapse leftovers."""
  10329. from backend.app.api.routes.camera import cleanup_orphaned_streams
  10330. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10331. rounds = 0
  10332. while True:
  10333. try:
  10334. rounds += 1
  10335. await cleanup_orphaned_streams()
  10336. except asyncio.CancelledError:
  10337. break
  10338. except Exception as e:
  10339. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  10340. try:
  10341. if rounds % TIMELAPSE_CLEANUP_EVERY == 0:
  10342. await asyncio.to_thread(cleanup_orphaned_timelapse_sessions)
  10343. except asyncio.CancelledError:
  10344. break
  10345. except Exception as e:
  10346. logging.getLogger(__name__).warning("Timelapse frames cleanup failed: %s", e)
  10347. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  10348. def start_camera_cleanup():
  10349. global _camera_cleanup_task
  10350. if _camera_cleanup_task is None:
  10351. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  10352. logging.getLogger(__name__).info("Camera stream cleanup started")
  10353. def stop_camera_cleanup():
  10354. global _camera_cleanup_task
  10355. if _camera_cleanup_task:
  10356. _camera_cleanup_task.cancel()
  10357. _camera_cleanup_task = None
  10358. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  10359. # ---------------------------------------------------------------------------
  10360. # Expected-print TTL eviction
  10361. # ---------------------------------------------------------------------------
  10362. def _evict_stale_expected_prints() -> None:
  10363. """Remove entries from _expected_prints / _expected_print_creators that are
  10364. older than _EXPECTED_PRINT_TTL_SECONDS.
  10365. This prevents unbounded growth when a print is registered (via
  10366. register_expected_print) but on_print_start never fires — e.g. because the
  10367. printer disconnects, the app restarts, or the print is started directly from
  10368. the printer panel without going through the queue.
  10369. """
  10370. # Use monotonic time so the TTL is unaffected by system clock adjustments
  10371. # (e.g. NTP sync, DST changes).
  10372. # A print that ended without its archive being found at completion leaves
  10373. # its id here; only running prints are owned.
  10374. _owned_print_archive_ids.intersection_update(_active_prints.values())
  10375. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  10376. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  10377. if not stale_keys:
  10378. return
  10379. evicted: set[tuple[int, int]] = set()
  10380. for key in stale_keys:
  10381. archive_id = _expected_prints.pop(key, None)
  10382. if archive_id is not None:
  10383. evicted.add((key[0], archive_id))
  10384. _expected_print_creators.pop(key, None)
  10385. _expected_print_registered_at.pop(key, None)
  10386. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  10387. # that have no remaining live keys in _expected_prints (all variants
  10388. # were just evicted) and are not printing right now. Print start pops
  10389. # only the names the printer reported, so the "<base>.gcode" variant
  10390. # outlives it; without the printing check its eviction two hours after
  10391. # dispatch threw away a running print's plate, AMS mapping and cost
  10392. # centre, which completion still reads (#3275).
  10393. for printer_id, archive_id in evicted:
  10394. if not _expected_or_printing_here(printer_id, archive_id):
  10395. _drop_dispatch(printer_id, archive_id)
  10396. logging.getLogger(__name__).info(
  10397. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  10398. )
  10399. async def _expected_prints_cleanup_loop() -> None:
  10400. """Background task: periodically evict stale expected-print entries."""
  10401. while True:
  10402. try:
  10403. _evict_stale_expected_prints()
  10404. except asyncio.CancelledError:
  10405. raise
  10406. except Exception as e:
  10407. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  10408. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  10409. def start_expected_prints_cleanup() -> None:
  10410. global _expected_prints_cleanup_task
  10411. if _expected_prints_cleanup_task is None:
  10412. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  10413. logging.getLogger(__name__).info("Expected prints cleanup started")
  10414. def stop_expected_prints_cleanup() -> None:
  10415. global _expected_prints_cleanup_task
  10416. if _expected_prints_cleanup_task:
  10417. _expected_prints_cleanup_task.cancel()
  10418. _expected_prints_cleanup_task = None
  10419. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  10420. # ---------------------------------------------------------------------------
  10421. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  10422. # ---------------------------------------------------------------------------
  10423. _auth_cleanup_task: asyncio.Task | None = None
  10424. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  10425. async def _run_auth_cleanup() -> None:
  10426. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  10427. from backend.app.core.database import async_session
  10428. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  10429. from backend.app.models.user_totp import UserTOTP
  10430. now = datetime.now(timezone.utc)
  10431. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  10432. try:
  10433. async with async_session() as db:
  10434. stale_cutoff = now - timedelta(hours=1)
  10435. result = await db.execute(
  10436. select(UserTOTP).where(
  10437. UserTOTP.is_enabled.is_(False),
  10438. UserTOTP.created_at < stale_cutoff,
  10439. )
  10440. )
  10441. stale_records = result.scalars().all()
  10442. if stale_records:
  10443. for rec in stale_records:
  10444. await db.delete(rec)
  10445. await db.commit()
  10446. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  10447. except Exception as e:
  10448. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  10449. # Remove expired revoked-JTI entries (they are no longer needed once the
  10450. # original token's exp has passed — the token would be rejected by JWT
  10451. # signature verification regardless).
  10452. try:
  10453. async with async_session() as db:
  10454. await db.execute(
  10455. delete(AuthEphemeralToken).where(
  10456. AuthEphemeralToken.token_type == "revoked_jti",
  10457. AuthEphemeralToken.expires_at < now,
  10458. )
  10459. )
  10460. await db.commit()
  10461. except Exception as e:
  10462. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  10463. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  10464. # Events outside this window can never affect rate-limit decisions — they only
  10465. # consume DB space. Use the same window constant as the rate limiter so the
  10466. # two are always in sync.
  10467. try:
  10468. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  10469. async with async_session() as db:
  10470. await db.execute(
  10471. delete(AuthRateLimitEvent).where(
  10472. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  10473. )
  10474. )
  10475. await db.commit()
  10476. except Exception as e:
  10477. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  10478. async def _auth_cleanup_loop() -> None:
  10479. """Periodic background task: run auth cleanup every hour."""
  10480. while True:
  10481. try:
  10482. await _run_auth_cleanup()
  10483. except asyncio.CancelledError:
  10484. break
  10485. except Exception as e:
  10486. logging.warning("Auth cleanup loop error: %s", e)
  10487. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  10488. def start_auth_cleanup() -> None:
  10489. global _auth_cleanup_task
  10490. if _auth_cleanup_task is None:
  10491. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  10492. logging.getLogger(__name__).info("Auth periodic cleanup started")
  10493. def stop_auth_cleanup() -> None:
  10494. global _auth_cleanup_task
  10495. if _auth_cleanup_task:
  10496. _auth_cleanup_task.cancel()
  10497. _auth_cleanup_task = None
  10498. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  10499. @asynccontextmanager
  10500. async def lifespan(app: FastAPI):
  10501. # Startup
  10502. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  10503. # anything else can spawn tasks that might trip it.
  10504. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  10505. install_proactor_reset_filter()
  10506. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  10507. # what turned descriptor exhaustion into a corrupted database (#2883).
  10508. from backend.app.core.fd_limit import raise_open_file_limit
  10509. raise_open_file_limit()
  10510. # Before init_db, so the warning is near the top of the log rather than
  10511. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  10512. warn_if_running_on_uvloop()
  10513. await init_db()
  10514. # Browser download tokens expire after five minutes. Remove abandoned
  10515. # prepared ZIPs at startup as well as before each new preparation so a
  10516. # quiet appliance cannot retain an unusable bundle indefinitely.
  10517. try:
  10518. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  10519. await prune_stale_printer_file_bundles()
  10520. except Exception as exc:
  10521. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  10522. # After migrations, so the is_env_managed column exists. Never raises --
  10523. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  10524. # startup (see apply_env_oidc_provider).
  10525. from backend.app.core.oidc_env import apply_env_oidc_provider
  10526. async with async_session() as oidc_db:
  10527. await apply_env_oidc_provider(oidc_db)
  10528. # Close out batches that finished before `completed` was a reachable status
  10529. # (#342). Without this the Batches tab opens on every batch created since
  10530. # the feature shipped, all still marked active. Never blocks startup.
  10531. try:
  10532. from backend.app.services.print_batch import backfill_batch_statuses
  10533. async with async_session() as batch_db:
  10534. await backfill_batch_statuses(batch_db)
  10535. except Exception as exc:
  10536. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  10537. # Each plate's estimate of archives made before they were kept (#3375),
  10538. # read from their 3MFs in the background: the readers use the whole
  10539. # file's figures until then.
  10540. global _plate_estimates_task
  10541. _plate_estimates_task = asyncio.create_task(_fill_plate_estimates())
  10542. # Register an app-scoped httpx client for Bambu Cloud services so
  10543. # per-request BambuCloudService instances reuse the same connection pool
  10544. # (important for routes like /cloud/filament-info that chain many
  10545. # get_setting_detail calls). The shared client stores no region/token
  10546. # state, so the per-request ownership pattern that fixed the region-bleed
  10547. # bug is preserved.
  10548. import httpx as _httpx
  10549. from backend.app.services.bambu_cloud import set_shared_http_client
  10550. from backend.app.services.model_providers.makerworld.service import (
  10551. set_shared_http_client as set_shared_makerworld_http_client,
  10552. )
  10553. from backend.app.services.orca_cloud import (
  10554. set_shared_http_client as set_shared_orca_http_client,
  10555. )
  10556. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  10557. set_shared_http_client(_shared_cloud_http_client)
  10558. # Reuse the same connection pool for MakerWorld — different host, same
  10559. # keep-alive pool saves a TLS handshake per request.
  10560. set_shared_makerworld_http_client(_shared_cloud_http_client)
  10561. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  10562. # each spun up (and never closed) its own client, leaking sockets.
  10563. set_shared_orca_http_client(_shared_cloud_http_client)
  10564. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  10565. # This can happen when a print was cancelled mid-print on versions before this fix.
  10566. try:
  10567. async with async_session() as db:
  10568. from backend.app.models.print_queue import PrintQueueItem
  10569. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  10570. aborted_items = result.scalars().all()
  10571. if aborted_items:
  10572. for item in aborted_items:
  10573. item.status = "cancelled"
  10574. await db.commit()
  10575. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  10576. except Exception as e:
  10577. logging.warning("Failed to fix aborted queue items: %s", e)
  10578. # Restore debug logging state from previous session
  10579. await init_debug_logging()
  10580. # Set up printer manager callbacks
  10581. loop = asyncio.get_event_loop()
  10582. printer_manager.set_event_loop(loop)
  10583. printer_manager.set_status_change_callback(on_printer_status_change)
  10584. printer_manager.set_print_start_callback(on_print_start)
  10585. printer_manager.set_print_complete_callback(on_print_complete)
  10586. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  10587. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  10588. printer_manager.set_ams_change_callback(on_ams_change)
  10589. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  10590. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  10591. await printer_manager.load_awaiting_plate_clear_from_db()
  10592. # Layer change callback for external camera timelapse
  10593. async def on_layer_change(printer_id: int, layer_num: int):
  10594. """Capture timelapse frame on layer change + first layer notification."""
  10595. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  10596. await tl_layer_change(printer_id, layer_num)
  10597. # #1867: bank a recent in-print frame so the finish-photo path has a
  10598. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  10599. # #2547 added `on_print_progress` as a second driver — this one alone
  10600. # stops firing once the final layer begins.
  10601. await _maybe_bank_inprint_frame(printer_id, layer_num)
  10602. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  10603. # Gate on actual printing state — Bambu firmware ticks layer_num during
  10604. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  10605. # nozzle clean), so a bare layer_num check can fire minutes before the
  10606. # first real extrusion. We require gcode_state == RUNNING and
  10607. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  10608. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  10609. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  10610. # edge fires later; _first_layer_notified stays clear until we actually send
  10611. # so a deferred re-evaluation can win. See issue #1837.
  10612. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  10613. client = printer_manager.get_client(printer_id)
  10614. state = client.state if client else None
  10615. if not state or state.state != "RUNNING":
  10616. return
  10617. if state.mc_print_sub_stage not in (None, 0):
  10618. return
  10619. _first_layer_notified[printer_id] = True
  10620. try:
  10621. async with async_session() as db:
  10622. from backend.app.models.printer import Printer
  10623. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  10624. printer = result.scalar_one_or_none()
  10625. if not printer:
  10626. return
  10627. printer_name = printer.name
  10628. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  10629. total_layers = state.total_layers if state else 0
  10630. image_data = await _capture_snapshot_for_notification(
  10631. printer_id, printer, logging.getLogger(__name__)
  10632. )
  10633. await notification_service.on_first_layer_complete(
  10634. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  10635. )
  10636. except Exception as e:
  10637. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  10638. printer_manager.set_layer_change_callback(on_layer_change)
  10639. async def on_print_progress(printer_id: int, percent: int):
  10640. """#2547: keep the in-print frame bank fresh through the final layer.
  10641. `on_layer_change` stops the moment the last layer starts, which on the
  10642. H2C capture that closed #2547 left the bank stale for the three minutes
  10643. that layer took. Progress is the only field that keeps advancing there,
  10644. and it freezes before the End G-code runs — so banking on it stays
  10645. inside the print and never sees a swapped plate.
  10646. """
  10647. client = printer_manager.get_client(printer_id)
  10648. state = client.state if client else None
  10649. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  10650. printer_manager.set_print_progress_callback(on_print_progress)
  10651. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  10652. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  10653. waiter = _bed_cool_waiters.get(printer_id)
  10654. if not waiter:
  10655. return
  10656. threshold = waiter["threshold"]
  10657. if bed_temp > threshold:
  10658. return
  10659. # Bed is at or below threshold — fire notification and remove waiter
  10660. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  10661. if not waiter_info:
  10662. return # Another callback already handled it
  10663. bed_cool_logger = logging.getLogger(__name__)
  10664. bed_cool_logger.info(
  10665. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  10666. bed_temp,
  10667. printer_id,
  10668. threshold,
  10669. )
  10670. try:
  10671. printer_info = printer_manager.get_printer(printer_id)
  10672. p_name = printer_info.name if printer_info else "Unknown"
  10673. async with async_session() as db:
  10674. await notification_service.on_bed_cooled(
  10675. printer_id=printer_id,
  10676. printer_name=p_name,
  10677. bed_temp=bed_temp,
  10678. threshold=threshold,
  10679. filename=waiter_info["filename"],
  10680. db=db,
  10681. )
  10682. except Exception as e:
  10683. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  10684. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  10685. async def on_drying_complete(printer_id: int, ams_id: int):
  10686. """Smart-plug auto-off-after-drying trigger (#1349).
  10687. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  10688. manager walks all plugs linked to this printer and turns off only
  10689. the ones with ``auto_off_after_drying`` enabled, after their
  10690. per-plug delay. Multiple AMS units finishing close together (e.g. a
  10691. dual-AMS dry that ends within the same MQTT push) call this once
  10692. per unit — the manager's ``_cancel_pending_off`` collapses
  10693. repeated scheduling on the same plug to one timer, so duplicate
  10694. fires are safe.
  10695. """
  10696. try:
  10697. async with async_session() as db:
  10698. await smart_plug_manager.on_drying_complete(printer_id, db)
  10699. except Exception as e:
  10700. logging.getLogger(__name__).warning(
  10701. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  10702. printer_id,
  10703. ams_id,
  10704. e,
  10705. )
  10706. printer_manager.set_drying_complete_callback(on_drying_complete)
  10707. async def on_drying_cycle_end(printer_id: int, cycle):
  10708. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  10709. from backend.app.services.spool_drying import record_drying_cycle
  10710. try:
  10711. async with async_session() as db:
  10712. await record_drying_cycle(db, printer_id, cycle)
  10713. except Exception as e:
  10714. logging.getLogger(__name__).warning(
  10715. "Failed to record drying for printer %d (AMS %d): %s",
  10716. printer_id,
  10717. cycle.ams_id,
  10718. e,
  10719. )
  10720. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  10721. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  10722. """Surface the read-back result of a spool assignment to the UI (#2582).
  10723. The MQTT client confirms (or fails to confirm) that the tray telemetry
  10724. echoed back the filament id we pushed. We relay that as a websocket
  10725. event so the frontend can toast "loaded" / "assignment didn't take"
  10726. instead of the historic silent fire-and-forget, which made the
  10727. AMS→Studio hand-off feel random to users.
  10728. """
  10729. try:
  10730. from backend.app.services.spool_assignment_notifications import (
  10731. _slot_label_from_global_tray,
  10732. )
  10733. if ams_id == 255:
  10734. global_id = 254 + tray_id
  10735. elif ams_id >= 128:
  10736. global_id = ams_id
  10737. else:
  10738. global_id = ams_id * 4 + tray_id
  10739. slot_label = _slot_label_from_global_tray(global_id)
  10740. printer_info = printer_manager.get_printer(printer_id)
  10741. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  10742. await ws_manager.broadcast(
  10743. {
  10744. "type": "spool_assignment_verified",
  10745. "printer_id": printer_id,
  10746. "printer_name": printer_name,
  10747. "ams_id": ams_id,
  10748. "tray_id": tray_id,
  10749. "slot": slot_label,
  10750. "verified": verified,
  10751. # Present on success: False means the filament setting landed
  10752. # but the K-profile (cali_idx) did not — the reporter's exact
  10753. # "loaded but no flow profile" symptom.
  10754. "kprofile_applied": detail.get("kprofile_applied", True),
  10755. }
  10756. )
  10757. except Exception as e:
  10758. logging.getLogger(__name__).warning(
  10759. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  10760. printer_id,
  10761. ams_id,
  10762. tray_id,
  10763. e,
  10764. )
  10765. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  10766. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  10767. """Persist a mid-print tray change for completion-time attribution.
  10768. AMS filament backup switches trays without telling the slicer, so the
  10769. tray-change log is the only record of which spool fed which layers.
  10770. Keeping it only in memory meant a restart mid-print charged everything
  10771. to the tray that finished the job.
  10772. """
  10773. try:
  10774. from backend.app.services.usage_tracker import record_tray_change
  10775. async with async_session() as db:
  10776. await record_tray_change(db, printer_id, tray_global, layer_num)
  10777. except Exception as e:
  10778. logging.getLogger(__name__).warning(
  10779. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  10780. printer_id,
  10781. tray_global,
  10782. layer_num,
  10783. e,
  10784. )
  10785. printer_manager.set_tray_change_callback(on_tray_change)
  10786. # Initialize MQTT relay from settings
  10787. async with async_session() as db:
  10788. from backend.app.api.routes.settings import get_setting
  10789. mqtt_settings = {
  10790. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  10791. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  10792. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  10793. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  10794. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  10795. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  10796. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  10797. }
  10798. await mqtt_relay.configure(mqtt_settings)
  10799. # Restore MQTT smart plug subscriptions
  10800. if mqtt_settings.get("mqtt_enabled"):
  10801. from backend.app.models.smart_plug import SmartPlug
  10802. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  10803. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  10804. mqtt_plugs = result.scalars().all()
  10805. restored = 0
  10806. for plug in mqtt_plugs:
  10807. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  10808. restored += 1
  10809. if restored:
  10810. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  10811. # Connect to all active printers
  10812. async with async_session() as db:
  10813. await init_printer_connections(db)
  10814. # Auto-connect to Spoolman if enabled
  10815. async with async_session() as db:
  10816. from backend.app.api.routes.settings import get_setting
  10817. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  10818. spoolman_url = await get_setting(db, "spoolman_url")
  10819. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  10820. try:
  10821. client = await init_spoolman_client(spoolman_url)
  10822. if await client.health_check():
  10823. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  10824. # Ensure the 'tag' extra field exists for RFID/UUID storage
  10825. field_ok = await client.ensure_tag_extra_field()
  10826. if not field_ok:
  10827. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  10828. # Register the BambuStudio slicer-preset fields used by the
  10829. # spool-edit / assign flow. Spoolman rejects PATCHes with
  10830. # unknown extra keys, so these must exist before any update
  10831. # that touches them.
  10832. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  10833. if not await client.ensure_extra_field(field_name):
  10834. logging.warning(
  10835. "Spoolman extra field %r registration failed — "
  10836. "spool slicer-preset edits will return 502",
  10837. field_name,
  10838. )
  10839. else:
  10840. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  10841. except Exception as e:
  10842. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  10843. # Start the print scheduler
  10844. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  10845. # Start the smart plug scheduler for time-based on/off
  10846. smart_plug_manager.start_scheduler()
  10847. # Start the Home Assistant sensor poller (#1148)
  10848. ha_sensor_manager.start()
  10849. location_ha_sensor_manager.start()
  10850. # Resume any pending auto-offs that were interrupted by restart
  10851. await smart_plug_manager.resume_pending_auto_offs()
  10852. # Start the notification digest scheduler
  10853. notification_service.start_digest_scheduler()
  10854. notify_live_activities.start()
  10855. notify_widgets.start()
  10856. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  10857. # provider in reactions/both mode; the notification routes resync them.
  10858. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  10859. # until the next provider save, not the whole startup.
  10860. try:
  10861. await telegram_reaction_poller.start()
  10862. except Exception as e:
  10863. logging.warning("Telegram reaction poller did not start: %s", e)
  10864. # Start the GitHub backup scheduler
  10865. await github_backup_service.start_scheduler()
  10866. # Start the local backup scheduler
  10867. await local_backup_service.start_scheduler()
  10868. await obico_detection_service.start()
  10869. # Start the library trash sweeper (#1008)
  10870. await library_trash_service.start_scheduler()
  10871. # Start the archive auto-purge sweeper (#1008 follow-up)
  10872. await archive_purge_service.start_scheduler()
  10873. # Start AMS history recording
  10874. start_ams_history_recording()
  10875. # Start printer sensor (nozzle / bed / chamber) history recording
  10876. start_printer_sensor_history_recording()
  10877. # Start printer runtime tracking
  10878. start_runtime_tracking()
  10879. # Start SpoolBuddy device watchdog
  10880. start_spoolbuddy_watchdog()
  10881. # Start camera stream orphan cleanup
  10882. start_camera_cleanup()
  10883. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  10884. start_connection_watchdog()
  10885. # One-shot sweep for timelapse session directories orphaned by a crash
  10886. # or restart that happened mid-print (in-memory session tracking can't
  10887. # survive that, and nothing else reaps the leftover frames/output file)
  10888. try:
  10889. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10890. removed = cleanup_orphaned_timelapse_sessions()
  10891. if removed:
  10892. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  10893. except Exception as e:
  10894. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  10895. # Start expected-print TTL eviction (prevents memory leak when prints are
  10896. # registered but on_print_start never fires)
  10897. start_expected_prints_cleanup()
  10898. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  10899. start_auth_cleanup()
  10900. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  10901. from backend.app.services import announcements as announcements_service
  10902. announcements_service.start()
  10903. from backend.app.services.printer_media import start_printer_download_cleanup
  10904. start_printer_download_cleanup()
  10905. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  10906. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  10907. from backend.app.services.loop_watchdog import start_loop_watchdog
  10908. start_loop_watchdog()
  10909. # Initialize virtual printer manager and sync from DB
  10910. from backend.app.services.virtual_printer import virtual_printer_manager
  10911. virtual_printer_manager.set_session_factory(async_session)
  10912. virtual_printer_manager.set_printer_manager(printer_manager)
  10913. try:
  10914. await virtual_printer_manager.sync_from_db()
  10915. logging.info("Virtual printer manager synced from database")
  10916. except Exception as e:
  10917. logging.warning("Failed to sync virtual printers: %s", e)
  10918. yield
  10919. # Shutdown
  10920. print_scheduler.stop()
  10921. smart_plug_manager.stop_scheduler()
  10922. ha_sensor_manager.stop()
  10923. location_ha_sensor_manager.stop()
  10924. notification_service.stop_digest_scheduler()
  10925. await notify_live_activities.close()
  10926. await notify_widgets.close()
  10927. await telegram_reaction_poller.aclose()
  10928. github_backup_service.stop_scheduler()
  10929. local_backup_service.stop_scheduler()
  10930. library_trash_service.stop_scheduler()
  10931. archive_purge_service.stop_scheduler()
  10932. obico_detection_service.stop()
  10933. stop_ams_history_recording()
  10934. stop_printer_sensor_history_recording()
  10935. stop_runtime_tracking()
  10936. stop_spoolbuddy_watchdog()
  10937. stop_camera_cleanup()
  10938. stop_connection_watchdog()
  10939. from backend.app.services.loop_watchdog import stop_loop_watchdog
  10940. stop_loop_watchdog()
  10941. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  10942. # cleanly rather than waiting on a queue that nothing will ever fill.
  10943. try:
  10944. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  10945. await shutdown_all_broadcasters()
  10946. except Exception as e:
  10947. logging.warning("Failed to shut down camera broadcasters: %s", e)
  10948. stop_expected_prints_cleanup()
  10949. stop_auth_cleanup()
  10950. if _plate_estimates_task is not None and not _plate_estimates_task.done():
  10951. _plate_estimates_task.cancel()
  10952. from backend.app.services import announcements as announcements_service
  10953. announcements_service.stop()
  10954. from backend.app.services.printer_media import stop_printer_download_cleanup
  10955. await stop_printer_download_cleanup()
  10956. # Stops a timelapse editor's ffmpeg rather than leaving it to the OS.
  10957. from backend.app.services import timelapse_jobs
  10958. await timelapse_jobs.cancel_all()
  10959. printer_manager.disconnect_all()
  10960. slot_unlink_grace.reset()
  10961. await close_spoolman_client()
  10962. # Stop all virtual printer services
  10963. await virtual_printer_manager.stop_all()
  10964. await mqtt_smart_plug_service.disconnect(timeout=2)
  10965. await mqtt_relay.disconnect(timeout=2)
  10966. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  10967. set_shared_http_client(None)
  10968. set_shared_makerworld_http_client(None)
  10969. set_shared_orca_http_client(None)
  10970. await _shared_cloud_http_client.aclose()
  10971. # Checkpoint WAL (SQLite only) and close all database connections
  10972. from backend.app.core.db_dialect import is_sqlite
  10973. if is_sqlite():
  10974. try:
  10975. async with engine.begin() as conn:
  10976. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  10977. logging.info("WAL checkpoint completed")
  10978. except Exception as e:
  10979. logging.warning("WAL checkpoint failed: %s", e)
  10980. await engine.dispose()
  10981. app = FastAPI(
  10982. title=app_settings.app_name,
  10983. description="Archive and manage Bambu Lab 3MF files",
  10984. version=APP_VERSION,
  10985. lifespan=lifespan,
  10986. )
  10987. # Added first so it sits innermost, next to the routes: a refused header's value
  10988. # (often a stored token) masked in every JSON body. See core.response_redaction.
  10989. app.add_middleware(RefusedHeaderResponseMask)
  10990. def _json_safe(value):
  10991. """The validation errors with every non-finite number written as text."""
  10992. if isinstance(value, float) and not math.isfinite(value):
  10993. return str(value)
  10994. if isinstance(value, dict):
  10995. return {key: _json_safe(item) for key, item in value.items()}
  10996. if isinstance(value, list | tuple):
  10997. return [_json_safe(item) for item in value]
  10998. return value
  10999. @app.exception_handler(RequestValidationError)
  11000. async def _validation_error(_request, exc: RequestValidationError) -> JSONResponse:
  11001. """FastAPI's own 422, except that it survives a non-finite number.
  11002. A body may carry ``Infinity`` or ``NaN`` (Python's JSON reader accepts
  11003. them), and the default handler echoes the input back in its errors,
  11004. which JSON cannot hold: the request ended in an error instead of a 422.
  11005. """
  11006. return JSONResponse(status_code=422, content={"detail": _json_safe(jsonable_encoder(exc.errors()))})
  11007. # =============================================================================
  11008. # Authentication Middleware - Secures ALL API routes by default
  11009. # =============================================================================
  11010. # Public routes that don't require authentication even when auth is enabled
  11011. PUBLIC_API_ROUTES = {
  11012. # Auth routes needed before/during login
  11013. "/api/v1/auth/status",
  11014. "/api/v1/auth/login",
  11015. "/api/v1/auth/setup", # Needed for initial setup and recovery
  11016. # Advanced auth status needed for login page
  11017. "/api/v1/auth/advanced-auth/status",
  11018. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  11019. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  11020. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  11021. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  11022. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  11023. # OIDC routes that must be reachable without a JWT
  11024. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  11025. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  11026. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  11027. # Connected apps: the app's server swaps a code for the user's identity,
  11028. # authenticated by its client secret rather than a login token.
  11029. "/api/v1/connect/token",
  11030. # Version check for updates (no sensitive data)
  11031. "/api/v1/updates/version",
  11032. # Metrics endpoint handles its own prometheus_token authentication
  11033. "/api/v1/metrics",
  11034. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  11035. # this BEFORE a JWT is available to pick up the firstboot wizard's
  11036. # hostname / timezone / locale and the chrony NTP-gate state. The
  11037. # response contains user-set defaults and a public sync flag — no
  11038. # secrets. Without this entry the global auth middleware returns 401
  11039. # before the route handler runs, regardless of the route's own
  11040. # "no auth required" intent.
  11041. "/api/v1/system/appliance",
  11042. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  11043. # authenticates with a long-lived ``camwall``-scoped token in the query
  11044. # string — exactly like the camera streams two lists below, and for the same
  11045. # reason (no header to put a JWT in). "Public" here only means the middleware
  11046. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  11047. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  11048. # plain ``camera_stream`` token does NOT open this door.
  11049. "/api/v1/camwall/printers",
  11050. # Overlay branding: the route enforces overlay-scoped token authentication.
  11051. "/api/v1/overlay-branding/logo",
  11052. }
  11053. # Route prefixes that are public (for routes with dynamic segments)
  11054. PUBLIC_API_PREFIXES = [
  11055. # WebSocket connections handle their own auth
  11056. "/api/v1/ws",
  11057. # OIDC authorize redirects — include provider_id in path
  11058. "/api/v1/auth/oidc/authorize/",
  11059. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  11060. # a phone with no session, so no header can carry a JWT — the single-use
  11061. # capability token in the path IS the credential (same reasoning as the
  11062. # /dl/ slicer downloads below). The route grants nothing beyond writing
  11063. # good/reject on the one archive the token was minted for.
  11064. "/api/v1/archives/confirm/",
  11065. ]
  11066. # Route patterns that are public (read-only display data)
  11067. # These are checked with "in path" - needed because browsers load images/videos
  11068. # via <img src> and <video src> which don't include Authorization headers
  11069. PUBLIC_API_PATTERNS = [
  11070. # Thumbnails
  11071. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  11072. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  11073. # Images and media
  11074. "/photos/", # /archives/{id}/photos/{filename}
  11075. "/project-image/", # /archives/{id}/project-image/{path}
  11076. "/qrcode", # /archives/{id}/qrcode
  11077. "/timelapse", # /archives/{id}/timelapse (video)
  11078. "/cover", # /printers/{id}/cover
  11079. "/icon", # /external-links/{id}/icon
  11080. # Camera (streams loaded via <img> tag)
  11081. "/camera/stream", # /printers/{id}/camera/stream
  11082. "/camera/snapshot", # /printers/{id}/camera/snapshot
  11083. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  11084. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  11085. # string (same reasoning as the camera streams above — no header to carry a
  11086. # JWT). "Public" only means the middleware steps aside; the route still runs
  11087. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  11088. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  11089. "/overlay-status", # /printers/{id}/overlay-status
  11090. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  11091. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  11092. # download token in the URL path instead.
  11093. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  11094. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  11095. # and these patterns match by substring. Without its own entry the middleware
  11096. # 401s the slicer's header-less request before the route's token check runs,
  11097. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  11098. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  11099. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  11100. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  11101. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  11102. ]
  11103. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  11104. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  11105. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  11106. Format: comma-separated list of ``scheme://host[:port]`` origins.
  11107. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  11108. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  11109. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  11110. Invalid entries are dropped with a warning rather than failing startup, so
  11111. a typo in one origin doesn't take the whole deployment down.
  11112. """
  11113. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  11114. if not raw:
  11115. return ()
  11116. valid: list[str] = []
  11117. for item in raw.split(","):
  11118. candidate = item.strip()
  11119. if not candidate:
  11120. continue
  11121. try:
  11122. parsed = urlparse(candidate)
  11123. except ValueError as e:
  11124. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  11125. continue
  11126. if parsed.scheme not in ("http", "https"):
  11127. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  11128. continue
  11129. if not parsed.netloc:
  11130. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  11131. continue
  11132. if parsed.path and parsed.path != "/":
  11133. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  11134. continue
  11135. if parsed.query or parsed.fragment:
  11136. _security_headers_logger.warning(
  11137. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  11138. )
  11139. continue
  11140. if "*" in parsed.netloc:
  11141. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  11142. continue
  11143. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  11144. if valid:
  11145. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  11146. return tuple(valid)
  11147. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  11148. def _frame_ancestors(default_value: str) -> str:
  11149. """Compose the ``frame-ancestors`` CSP directive (#1191).
  11150. ``default_value`` is the strict directive used when the operator has not
  11151. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  11152. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  11153. Settings URL builder's preview). When trusted origins
  11154. are configured, ``'self'`` is always included so same-origin embedding never
  11155. breaks even if an operator forgets to add their own origin to the list.
  11156. """
  11157. if _TRUSTED_FRAME_ORIGINS:
  11158. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  11159. return f"frame-ancestors {default_value};"
  11160. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  11161. # patterns are anchored on the exact emitted name so the relaxed policies
  11162. # below can never apply to any other asset.
  11163. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  11164. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  11165. # -> /assets/pdf.worker.min-<hash>.js
  11166. # Vite also emits a one-line chunk under the second name that only exports the
  11167. # worker's URL. The page imports it as a module, and a module script is run
  11168. # under the importing document's policy, never its own response's, so it
  11169. # matching as well changes nothing.
  11170. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  11171. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  11172. @app.middleware("http")
  11173. async def security_headers_middleware(request, call_next):
  11174. """Add standard HTTP security headers to every response."""
  11175. # Per-request nonce stamped into `script-src` (#1460). On its own this
  11176. # changes nothing for Bambuddy's own pages — index.html has no inline
  11177. # scripts since the SW registration moved to /sw-register.js. The reason
  11178. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  11179. # script injected into the HTML on the edge, with a fresh hash on every
  11180. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  11181. # it clones the same nonce onto its injected <script>, and the inline
  11182. # script passes the policy without us needing 'unsafe-inline'. See
  11183. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  11184. csp_nonce = secrets.token_urlsafe(16)
  11185. # Routes that render their own HTML need it too, or their inline script is
  11186. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  11187. # one that does: it submits its own form so a verdict still costs one tap.
  11188. request.state.csp_nonce = csp_nonce
  11189. response = await call_next(request)
  11190. response.headers["X-Content-Type-Options"] = "nosniff"
  11191. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  11192. # browsers honour CSP frame-ancestors instead, and the legacy
  11193. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  11194. # When operators have explicitly allowlisted trusted frame origins (#1191
  11195. # — typically Home Assistant on a different port), drop X-Frame-Options
  11196. # and let the CSP-side frame-ancestors directive govern embedding.
  11197. if not _TRUSTED_FRAME_ORIGINS:
  11198. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  11199. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  11200. # Content-Security-Policy for the React SPA.
  11201. # Notes:
  11202. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  11203. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  11204. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  11205. # - media-src blob:: timelapse video player uses Blob URLs.
  11206. # - font-src data:: some icon fonts are embedded as data URIs.
  11207. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  11208. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  11209. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  11210. # default CSP would render a blank page.
  11211. response.headers["Content-Security-Policy"] = (
  11212. "default-src 'self'; "
  11213. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  11214. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  11215. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  11216. "connect-src 'self'; "
  11217. "font-src 'self' data: https://fonts.gstatic.com; "
  11218. "worker-src 'self' blob:; "
  11219. "object-src 'none'; "
  11220. "base-uri 'self'; " + _frame_ancestors("'none'")
  11221. )
  11222. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  11223. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  11224. # its emscripten/embind glue generates invoker functions with `new
  11225. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  11226. # worker is governed by the policy delivered with the WORKER SCRIPT's
  11227. # own response — not the document's — so relaxing it here confines
  11228. # eval to that DOM-less worker context. The document policy below
  11229. # stays nonce-strict, and this response header has no effect when the
  11230. # file is merely fetched (a fetch's CSP is enforced against the
  11231. # requesting document, not the resource's own headers).
  11232. response.headers["Content-Security-Policy"] = (
  11233. "default-src 'self'; "
  11234. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  11235. "connect-src 'self'; "
  11236. "object-src 'none'; "
  11237. "base-uri 'self'; " + _frame_ancestors("'none'")
  11238. )
  11239. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  11240. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  11241. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  11242. # rule as the STEP worker above: the policy that governs a dedicated
  11243. # worker is the one delivered with its own script, so the wasm compile
  11244. # has to be permitted here rather than on the document. Unlike the STEP
  11245. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  11246. response.headers["Content-Security-Policy"] = (
  11247. "default-src 'self'; "
  11248. "script-src 'self' 'wasm-unsafe-eval'; "
  11249. "connect-src 'self'; "
  11250. "object-src 'none'; "
  11251. "base-uri 'self'; " + _frame_ancestors("'none'")
  11252. )
  11253. else:
  11254. # The streaming overlay is embedded same-origin by the URL builder's
  11255. # preview in Settings (#1422), so this branch allows 'self'.
  11256. # Embedding from anywhere else is still refused: 'self'
  11257. # only permits a framer on this origin, which is Bambuddy's own UI, so
  11258. # a clickjacking page on another host is blocked exactly as before.
  11259. # (The overlay draws status over a camera feed and its only interactive
  11260. # element is the logo link, so there is nothing to bait a click into
  11261. # even from a same-origin framer.) Cross-origin embedding of the
  11262. # overlay — Home Assistant on another port — remains what
  11263. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  11264. # allowlist in.
  11265. #
  11266. # The connected-app consent page (/connect/authorize) gets the same
  11267. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  11268. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  11269. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  11270. # requires every ancestor to be this origin, so a foreign page -- a
  11271. # sidebar link's site included -- still cannot frame the consent
  11272. # screen to bait a click.
  11273. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  11274. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  11275. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  11276. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  11277. # the policy served with their own script, so each gets it in its own
  11278. # branch above and the document policy stays as strict as it was.
  11279. response.headers["Content-Security-Policy"] = (
  11280. "default-src 'self'; "
  11281. f"script-src 'self' 'nonce-{csp_nonce}'; "
  11282. "style-src 'self' 'unsafe-inline'; "
  11283. "img-src 'self' data: blob:; "
  11284. "media-src 'self' blob:; "
  11285. "connect-src 'self' ws: wss:; "
  11286. "font-src 'self' data:; "
  11287. "object-src 'none'; "
  11288. "base-uri 'self'; "
  11289. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  11290. )
  11291. if request.url.scheme == "https":
  11292. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  11293. return response
  11294. @app.middleware("http")
  11295. async def auth_middleware(request, call_next):
  11296. """Enforce authentication on all API routes when auth is enabled.
  11297. This middleware provides defense-in-depth by checking auth at the API gateway level,
  11298. regardless of whether individual routes have auth dependencies.
  11299. """
  11300. from starlette.responses import JSONResponse
  11301. path = request.url.path
  11302. # Only apply to API routes
  11303. if not path.startswith("/api/"):
  11304. return await call_next(request)
  11305. # Allow public routes
  11306. if path in PUBLIC_API_ROUTES:
  11307. return await call_next(request)
  11308. # Allow public prefixes
  11309. for prefix in PUBLIC_API_PREFIXES:
  11310. if path.startswith(prefix):
  11311. return await call_next(request)
  11312. # Allow public patterns (read-only display data like thumbnails)
  11313. for pattern in PUBLIC_API_PATTERNS:
  11314. if pattern in path:
  11315. return await call_next(request)
  11316. # Check if auth is enabled. Fail CLOSED on any exception during the
  11317. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  11318. # an attacker who could force a DB exception (e.g. file-descriptor
  11319. # exhaustion via login flood) bypass auth on every protected endpoint.
  11320. # Only the probe is guarded: the request itself runs outside the try, so an
  11321. # error in a route surfaces as the 500 it is rather than as an auth outage.
  11322. try:
  11323. async with async_session() as db:
  11324. from backend.app.core.auth import is_auth_enabled
  11325. auth_enabled = await is_auth_enabled(db)
  11326. except Exception:
  11327. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  11328. return JSONResponse(
  11329. status_code=503,
  11330. content={"detail": "Authentication service temporarily unavailable"},
  11331. )
  11332. if not auth_enabled:
  11333. # Auth disabled, allow all requests
  11334. return await call_next(request)
  11335. # Auth is enabled - require valid token
  11336. auth_header = request.headers.get("Authorization")
  11337. x_api_key = request.headers.get("X-API-Key")
  11338. # Check for API key auth first
  11339. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  11340. # API key authentication - let the request through to be validated by route handler
  11341. # API keys are validated per-route since they have different permission levels
  11342. return await call_next(request)
  11343. # Check for JWT auth
  11344. if not auth_header or not auth_header.startswith("Bearer "):
  11345. return JSONResponse(
  11346. status_code=401,
  11347. content={"detail": "Authentication required"},
  11348. headers={"WWW-Authenticate": "Bearer"},
  11349. )
  11350. # Validate JWT token
  11351. import jwt
  11352. try:
  11353. from backend.app.core.auth import (
  11354. ALGORITHM,
  11355. SECRET_KEY,
  11356. _is_token_fresh,
  11357. get_user_by_username,
  11358. is_jti_revoked,
  11359. )
  11360. token = auth_header.replace("Bearer ", "")
  11361. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  11362. username = payload.get("sub")
  11363. if not username:
  11364. raise ValueError("No username in token")
  11365. jti = payload.get("jti")
  11366. if not jti:
  11367. raise ValueError("No jti in token")
  11368. iat = payload.get("iat")
  11369. # Verify user exists, is active, and token is still fresh (L-R8-A).
  11370. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  11371. # this session so the gateway adds a single pooled checkout, not two (#2572).
  11372. async with async_session() as db:
  11373. if await is_jti_revoked(jti, db):
  11374. return JSONResponse(
  11375. status_code=401,
  11376. content={"detail": "Token has been revoked"},
  11377. headers={"WWW-Authenticate": "Bearer"},
  11378. )
  11379. user = await get_user_by_username(db, username)
  11380. if not user or not user.is_active:
  11381. return JSONResponse(
  11382. status_code=401,
  11383. content={"detail": "User not found or inactive"},
  11384. headers={"WWW-Authenticate": "Bearer"},
  11385. )
  11386. if not _is_token_fresh(iat, user):
  11387. return JSONResponse(
  11388. status_code=401,
  11389. content={"detail": "Token no longer valid"},
  11390. headers={"WWW-Authenticate": "Bearer"},
  11391. )
  11392. except jwt.ExpiredSignatureError:
  11393. return JSONResponse(
  11394. status_code=401,
  11395. content={"detail": "Token has expired"},
  11396. headers={"WWW-Authenticate": "Bearer"},
  11397. )
  11398. except (jwt.InvalidTokenError, ValueError):
  11399. return JSONResponse(
  11400. status_code=401,
  11401. content={"detail": "Invalid token"},
  11402. headers={"WWW-Authenticate": "Bearer"},
  11403. )
  11404. except Exception:
  11405. # Not a bad token but a failure checking it (database, pool): refuse,
  11406. # as for the probe above, rather than answer 401 -- the frontend reads
  11407. # a 401 from /auth/me as final and signs the user out.
  11408. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  11409. return JSONResponse(
  11410. status_code=503,
  11411. content={"detail": "Authentication service temporarily unavailable"},
  11412. )
  11413. return await call_next(request)
  11414. @app.middleware("http")
  11415. async def trace_id_middleware(request, call_next):
  11416. """Stamp every HTTP request with a trace ID and echo it back.
  11417. Decorated AFTER auth_middleware on purpose: Starlette stacks
  11418. @app.middleware decorators LIFO, so the last-decorated runs first
  11419. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  11420. which means auth-middleware log lines (and every line emitted on the
  11421. way down to and back from the route handler) all carry the same
  11422. trace ID. If we put it before auth, auth's logs would be stamped
  11423. with the *previous* request's ID — useless for correlation.
  11424. Honours an inbound ``X-Trace-Id`` header so callers running their
  11425. own tracing can correlate their span IDs with our log lines, but
  11426. only if the value passes the whitelist gate in
  11427. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  11428. rejected (too long, contains control chars, etc.) silently triggers
  11429. a freshly minted server-side ID rather than failing the request.
  11430. The minted (or echoed) ID is set on a ContextVar so that every log
  11431. record emitted during the request — application logs *and* uvicorn's
  11432. access log — carries it via TraceIDFilter, and is also written to
  11433. the ``X-Trace-Id`` response header so clients can pin a server-side
  11434. log search to the exact request they made.
  11435. """
  11436. from backend.app.core.trace import (
  11437. generate_trace_id,
  11438. normalise_inbound_trace_id,
  11439. trace_id_var,
  11440. )
  11441. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  11442. trace_id = inbound if inbound is not None else generate_trace_id()
  11443. token = trace_id_var.set(trace_id)
  11444. try:
  11445. response = await call_next(request)
  11446. finally:
  11447. # Reset the ContextVar so a record emitted in a totally
  11448. # unrelated background task that just happens to inherit this
  11449. # context doesn't keep referencing this request's ID forever.
  11450. # In practice ContextVar.reset is best-effort under asyncio
  11451. # task-spawn semantics, but the cost is one attribute write so
  11452. # we may as well do it.
  11453. trace_id_var.reset(token)
  11454. response.headers["X-Trace-Id"] = trace_id
  11455. return response
  11456. # API routes
  11457. app.include_router(auth.router, prefix=app_settings.api_prefix)
  11458. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  11459. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  11460. app.include_router(users.router, prefix=app_settings.api_prefix)
  11461. app.include_router(groups.router, prefix=app_settings.api_prefix)
  11462. app.include_router(printers.router, prefix=app_settings.api_prefix)
  11463. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  11464. app.include_router(archives.router, prefix=app_settings.api_prefix)
  11465. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  11466. app.include_router(finance.router, prefix=app_settings.api_prefix)
  11467. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  11468. app.include_router(labels.router, prefix=app_settings.api_prefix)
  11469. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  11470. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  11471. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  11472. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  11473. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  11474. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  11475. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  11476. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  11477. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  11478. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  11479. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  11480. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  11481. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  11482. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  11483. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  11484. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  11485. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  11486. app.include_router(updates.router, prefix=app_settings.api_prefix)
  11487. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  11488. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  11489. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  11490. app.include_router(camera.router, prefix=app_settings.api_prefix)
  11491. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  11492. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  11493. app.include_router(projects.router, prefix=app_settings.api_prefix)
  11494. app.include_router(library.router, prefix=app_settings.api_prefix)
  11495. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  11496. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  11497. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  11498. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  11499. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  11500. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  11501. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  11502. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  11503. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  11504. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  11505. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  11506. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  11507. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  11508. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  11509. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  11510. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  11511. app.include_router(system.router, prefix=app_settings.api_prefix)
  11512. app.include_router(support.router, prefix=app_settings.api_prefix)
  11513. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  11514. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  11515. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  11516. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  11517. app.include_router(bulk.router, prefix=app_settings.api_prefix)
  11518. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  11519. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  11520. app.include_router(obico.router, prefix=app_settings.api_prefix)
  11521. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  11522. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  11523. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  11524. # Serve static files (React build)
  11525. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  11526. # Compressed, and cached for good where Vite hashed the name (#3175).
  11527. app.mount(
  11528. "/assets",
  11529. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  11530. name="assets",
  11531. )
  11532. if (app_settings.static_dir / "img").exists():
  11533. app.mount(
  11534. "/img",
  11535. StaticFiles(directory=app_settings.static_dir / "img"),
  11536. name="img",
  11537. )
  11538. if (app_settings.static_dir / "icons").exists():
  11539. app.mount(
  11540. "/icons",
  11541. StaticFiles(directory=app_settings.static_dir / "icons"),
  11542. name="icons",
  11543. )
  11544. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  11545. # falls through to the SPA catch-all and returns index.html, which the
  11546. # browser's font sanitizer rejects ("downloadable font: rejected by
  11547. # sanitizer").
  11548. if (app_settings.static_dir / "fonts").exists():
  11549. app.mount(
  11550. "/fonts",
  11551. StaticFiles(directory=app_settings.static_dir / "fonts"),
  11552. name="fonts",
  11553. )
  11554. @app.get("/")
  11555. async def serve_frontend():
  11556. """Serve the React frontend."""
  11557. index_file = app_settings.static_dir / "index.html"
  11558. if index_file.exists():
  11559. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11560. return {
  11561. "message": "Bambuddy API",
  11562. "docs": "/docs",
  11563. "frontend": "Build and place React app in /static directory",
  11564. }
  11565. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  11566. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  11567. # forever, but the HTML wrapping it is the only file that knows which hash
  11568. # is current. Without explicit cache-control headers Chromium decides
  11569. # heuristically (typically 10% of the time since Last-Modified) and on
  11570. # long-running kiosks happily serves stale HTML across browser restarts.
  11571. # That stale HTML references an old bundle hash, the old bundle is also
  11572. # in the disk cache, and the user ends up running pre-update JS forever
  11573. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  11574. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  11575. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  11576. @app.get("/health")
  11577. async def health_check():
  11578. """Health check endpoint."""
  11579. return {"status": "healthy"}
  11580. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  11581. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  11582. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  11583. # in deployment debugging. One decorator per method, not api_route(methods=
  11584. # [...]): api_route gives both methods the same OpenAPI operation id.
  11585. @app.get("/manifest.json")
  11586. @app.head("/manifest.json")
  11587. async def serve_manifest():
  11588. """Serve PWA manifest."""
  11589. manifest_file = app_settings.static_dir / "manifest.json"
  11590. if manifest_file.exists():
  11591. return FileResponse(manifest_file, media_type="application/manifest+json")
  11592. return {"error": "Manifest not found"}
  11593. @app.get("/sw.js")
  11594. @app.head("/sw.js")
  11595. async def serve_service_worker():
  11596. """Serve service worker."""
  11597. sw_file = app_settings.static_dir / "sw.js"
  11598. if sw_file.exists():
  11599. return FileResponse(
  11600. sw_file,
  11601. media_type="application/javascript",
  11602. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  11603. )
  11604. return {"error": "Service worker not found"}
  11605. @app.get("/sw-register.js")
  11606. @app.head("/sw-register.js")
  11607. async def serve_sw_register():
  11608. """Serve the service-worker registration bootstrap script.
  11609. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  11610. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  11611. """
  11612. reg_file = app_settings.static_dir / "sw-register.js"
  11613. if reg_file.exists():
  11614. return FileResponse(reg_file, media_type="application/javascript")
  11615. return {"error": "sw-register.js not found"}
  11616. # ── GCode viewer static files ────────────────────────────────────────────────
  11617. # Catch-all route for React Router (must be last)
  11618. @app.get("/{full_path:path}")
  11619. async def serve_spa(full_path: str):
  11620. """Serve React app for client-side routing."""
  11621. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  11622. if full_path.startswith("api/"):
  11623. from fastapi import HTTPException
  11624. raise HTTPException(status_code=404, detail="Not found")
  11625. index_file = app_settings.static_dir / "index.html"
  11626. if index_file.exists():
  11627. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11628. return {"error": "Frontend not built"}