main.py 637 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142
  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. label_templates,
  50. labels,
  51. library,
  52. library_tags,
  53. library_trash,
  54. library_variants,
  55. local_backup,
  56. local_presets,
  57. location_ha_sensors,
  58. maintenance,
  59. makerworld,
  60. manyfold,
  61. metrics,
  62. mfa,
  63. notification_templates,
  64. notifications,
  65. obico,
  66. octoeverywhere,
  67. orca_cloud,
  68. overlay_branding,
  69. pending_uploads,
  70. pipeline_runs,
  71. print_log,
  72. print_queue,
  73. printer_locations,
  74. printer_sensor_history,
  75. printers,
  76. projects,
  77. scheduled_dryings,
  78. settings as settings_routes,
  79. slice_jobs,
  80. slicer_pipelines,
  81. slicer_presets,
  82. smart_plugs,
  83. sponsor_prompt,
  84. spoolbuddy,
  85. spoolman,
  86. spoolman_inventory,
  87. support,
  88. system,
  89. updates,
  90. user_notifications,
  91. users,
  92. virtual_printers,
  93. webhook,
  94. websocket,
  95. )
  96. from backend.app.api.routes.maintenance import (
  97. _get_printer_maintenance_internal,
  98. ensure_default_types,
  99. maintenance_alert_values,
  100. )
  101. from backend.app.api.routes.support import init_debug_logging
  102. from backend.app.core.config import APP_VERSION, settings as app_settings
  103. from backend.app.core.database import async_session, engine, init_db
  104. from backend.app.core.static_assets import AssetStaticFiles
  105. from backend.app.core.tasks import spawn_background_task
  106. from backend.app.core.websocket import ws_manager
  107. from backend.app.services import kprofile_drift, pause_eta, print_dispatch_context, slot_unlink_grace
  108. from backend.app.services.ams_assignment_lock import get_ams_assignment_lock
  109. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  110. from backend.app.services.archive_cost_estimate import (
  111. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  112. settle_archive_cost_estimate as _settle_archive_cost_estimate,
  113. )
  114. from backend.app.services.archive_purge import archive_purge_service
  115. from backend.app.services.bambu_ftp import (
  116. RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  117. FileNotOnPrinterError,
  118. cache_3mf_download,
  119. clear_3mf_cache,
  120. download_file_async,
  121. download_file_try_paths_async,
  122. ftps_handshake_blocked,
  123. get_cached_3mf,
  124. get_ftp_retry_settings,
  125. normalize_3mf_name,
  126. with_ftp_retry,
  127. )
  128. from backend.app.services.bambu_mqtt import PrinterState
  129. from backend.app.services.camera_light import camera_light
  130. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  131. from backend.app.services.github_backup import github_backup_service
  132. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  133. from backend.app.services.library_trash import library_trash_service
  134. from backend.app.services.local_backup import local_backup_service
  135. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  136. from backend.app.services.mqtt_relay import mqtt_relay
  137. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  138. from backend.app.services.notification_service import notification_service
  139. from backend.app.services.notify_live_activities import notify_live_activities
  140. from backend.app.services.notify_widgets import notify_widgets
  141. from backend.app.services.obico_detection import obico_detection_service
  142. from backend.app.services.octoeverywhere_detection import octoeverywhere_detection_service
  143. from backend.app.services.plug_energy import get_plug_energy as _get_plug_energy
  144. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  145. from backend.app.services.print_scheduler import scheduler as print_scheduler
  146. from backend.app.services.print_storage import (
  147. REASON_FTP_TRANSFER_FAILED,
  148. REASON_FTPS_COOLOFF,
  149. external_storage_present,
  150. ftp_probe_paths,
  151. print_file_reachable_over_ftp,
  152. )
  153. from backend.app.services.printer_manager import (
  154. init_printer_connections,
  155. parse_plate_id,
  156. printer_manager,
  157. printer_state_to_dict,
  158. resolve_plate_id,
  159. )
  160. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  161. from backend.app.services.slot_nozzle import (
  162. nozzle_diameter_for_extruder,
  163. nozzle_flow_for_extruder,
  164. )
  165. from backend.app.services.smart_plug_manager import smart_plug_manager
  166. from backend.app.services.spool_assignment_notifications import (
  167. notify_missing_spool_assignments_on_print_start,
  168. )
  169. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  170. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  171. from backend.app.services.spoolman_tracking import (
  172. cleanup_tracking as _cleanup_spoolman_tracking,
  173. release_archived_slot_rows as _release_archived_spoolman_slots,
  174. report_usage as _report_spoolman_usage,
  175. store_print_data as _store_spoolman_print_data,
  176. )
  177. from backend.app.services.telegram_reactions import telegram_reaction_poller
  178. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  179. from backend.app.utils.ams_humidity import ams_humidity_percent
  180. from backend.app.utils.filament_types import printer_filament_type
  181. from backend.app.utils.fts_routing import extruder_for_inlet
  182. from backend.app.utils.local_time import to_naive_utc, utcnow_naive
  183. from backend.app.utils.print_jobs import is_internal_printer_job
  184. # =============================================================================
  185. # Dependency Check - runs before other imports to give helpful error messages
  186. # =============================================================================
  187. def _start_error_server(missing_packages: list):
  188. """Start a minimal HTTP server to display dependency errors in browser."""
  189. import os
  190. import signal
  191. from http.server import BaseHTTPRequestHandler, HTTPServer
  192. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  193. html = f"""<!DOCTYPE html>
  194. <html>
  195. <head>
  196. <title>Bambuddy - Setup Required</title>
  197. <style>
  198. body {{
  199. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  200. background: #0f172a; color: #e2e8f0;
  201. display: flex; justify-content: center; align-items: center;
  202. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  203. }}
  204. .container {{
  205. background: #1e293b; border-radius: 12px; padding: 40px;
  206. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  207. }}
  208. h1 {{ color: #f87171; margin-bottom: 10px; }}
  209. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  210. .packages {{
  211. background: #0f172a; border-radius: 8px; padding: 20px;
  212. margin: 20px 0; text-align: left;
  213. }}
  214. .packages ul {{ margin: 0; padding-left: 20px; }}
  215. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  216. .command {{
  217. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  218. margin: 15px 0; font-family: monospace; color: #4ade80;
  219. text-align: left; overflow-x: auto;
  220. }}
  221. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  222. </style>
  223. </head>
  224. <body>
  225. <div class="container">
  226. <h1>Setup Required</h1>
  227. <h2>Missing Python packages</h2>
  228. <div class="packages"><ul>{packages_html}</ul></div>
  229. <p>To fix, run this command on your server:</p>
  230. <div class="command">pip install -r requirements.lock</div>
  231. <p>Or if using a virtual environment:</p>
  232. <div class="command">./venv/bin/pip install -r requirements.lock</div>
  233. <p class="note">After installing, restart Bambuddy:<br>
  234. <code>sudo systemctl restart bambuddy</code></p>
  235. </div>
  236. </body>
  237. </html>"""
  238. class ErrorHandler(BaseHTTPRequestHandler):
  239. def do_GET(self):
  240. self.send_response(503)
  241. self.send_header("Content-type", "text/html")
  242. self.end_headers()
  243. self.wfile.write(html.encode())
  244. def log_message(self, format, *args):
  245. print(f"[Error Server] {args[0]}")
  246. port = int(os.environ.get("PORT", 8000))
  247. print(f"\nStarting error server on http://0.0.0.0:{port}")
  248. print("Visit this URL in your browser to see the error details.\n")
  249. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  250. def shutdown(signum, frame):
  251. print("\nShutting down error server...")
  252. raise SystemExit(0)
  253. signal.signal(signal.SIGTERM, shutdown)
  254. signal.signal(signal.SIGINT, shutdown)
  255. server.serve_forever()
  256. def check_dependencies():
  257. """Check that all required packages are installed."""
  258. missing = []
  259. # Map of import name -> package name (for pip install)
  260. required = {
  261. "jwt": "PyJWT",
  262. "fastapi": "fastapi",
  263. "uvicorn": "uvicorn",
  264. "sqlalchemy": "sqlalchemy",
  265. "aiosqlite": "aiosqlite",
  266. "pydantic": "pydantic",
  267. "paho.mqtt": "paho-mqtt",
  268. }
  269. for module, package in required.items():
  270. try:
  271. __import__(module)
  272. except ImportError:
  273. missing.append(package)
  274. if missing:
  275. print("\n" + "=" * 60)
  276. print("ERROR: Missing required Python packages!")
  277. print("=" * 60)
  278. print(f"\nMissing packages: {', '.join(missing)}")
  279. print("\nTo fix, run:")
  280. print(" pip install -r requirements.lock")
  281. print("\nOr if using a virtual environment:")
  282. print(" ./venv/bin/pip install -r requirements.lock")
  283. print("=" * 60 + "\n")
  284. _start_error_server(missing)
  285. check_dependencies()
  286. # =============================================================================
  287. # Import settings first for logging configuration
  288. # Configure logging based on settings
  289. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  290. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  291. log_level = getattr(logging, log_level_str, logging.INFO)
  292. # Trace ID column ([-] when no request scope is active — startup, MQTT
  293. # callbacks, scheduled tasks not chained from a request — so the column
  294. # stays visually aligned and missing values are obvious in grep). See
  295. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  296. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  297. # Create root logger
  298. root_logger = logging.getLogger()
  299. root_logger.setLevel(log_level)
  300. # Trace-ID injection: this filter populates record.trace_id from the
  301. # per-request ContextVar so the format string above can reference it.
  302. # Attached to each HANDLER (not the root logger) because Python's
  303. # logging semantics only invoke a logger's filters on records that
  304. # *originated* at that logger — records propagated up from child
  305. # loggers (every named logger in the app) never trigger root's filter.
  306. # Putting it on the handlers means every record any handler emits gets
  307. # trace_id injected just before the formatter runs, regardless of which
  308. # logger created the record. Without this, the formatter raises
  309. # KeyError on every child-logger record and the record is silently
  310. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  311. # partially" bug we hit. See backend/app/core/trace.py for the
  312. # ContextVar the filter reads.
  313. from backend.app.core.logging_filters import RefusedHeaderRedactFilter
  314. from backend.app.core.response_redaction import RefusedHeaderResponseMask
  315. from backend.app.core.trace import TraceIDFilter
  316. _trace_id_filter = TraceIDFilter()
  317. # Console handler - always enabled
  318. console_handler = logging.StreamHandler()
  319. console_handler.setLevel(log_level)
  320. console_handler.setFormatter(logging.Formatter(log_format))
  321. console_handler.addFilter(_trace_id_filter)
  322. # A refused header's value (often a token) masked before the line is written.
  323. _refused_header_filter = RefusedHeaderRedactFilter()
  324. console_handler.addFilter(_refused_header_filter)
  325. root_logger.addHandler(console_handler)
  326. def _attach_file_handler_to_uvicorn(handler: logging.Handler) -> None:
  327. """Send uvicorn's own loggers to bambuddy.log as well.
  328. Neither reaches the root handler: uvicorn.access has propagate=False, and
  329. uvicorn.error propagates only to "uvicorn", which has propagate=False.
  330. uvicorn.access is the record of which endpoint changed server state;
  331. uvicorn.error is where an unhandled route error is logged with its
  332. traceback ("Exception in ASGI application").
  333. """
  334. for name in ("uvicorn.access", "uvicorn.error"):
  335. logging.getLogger(name).addHandler(handler)
  336. # File handler - only in production or if explicitly enabled
  337. if app_settings.log_to_file:
  338. log_file = app_settings.log_dir / "bambuddy.log"
  339. file_handler = RotatingFileHandler(
  340. log_file,
  341. maxBytes=app_settings.log_max_bytes,
  342. backupCount=app_settings.log_backup_count,
  343. encoding="utf-8",
  344. )
  345. file_handler.setLevel(log_level)
  346. file_handler.setFormatter(logging.Formatter(log_format))
  347. file_handler.addFilter(_trace_id_filter)
  348. file_handler.addFilter(_refused_header_filter)
  349. root_logger.addHandler(file_handler)
  350. logging.info("Logging to file: %s", log_file)
  351. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  352. # access logger with propagate=False by default, so without this attach
  353. # there is no on-disk record of which endpoint triggered a server-state
  354. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  355. # for exactly this reason. Filtered to write methods only
  356. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  357. # frontend don't churn the rotation window faster than it's useful.
  358. from backend.app.core.logging_filters import (
  359. CancelledPoolNoiseFilter,
  360. WriteRequestsOnlyFilter,
  361. )
  362. _attach_file_handler_to_uvicorn(file_handler)
  363. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  364. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  365. # Uvicorn's access logger has propagate=False (its own default), so the
  366. # root-attached TraceIDFilter never sees these records. Attach a
  367. # second instance directly so HTTP access lines carry the same trace
  368. # ID column as the application logs they correlate with.
  369. uvicorn_access_logger.addFilter(TraceIDFilter())
  370. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  371. # BaseHTTPMiddleware cancelling the inner task scope on client
  372. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  373. # underlying transaction leak; this filter only suppresses the residual
  374. # log records that pre-existing pools still emit during their cleanup.
  375. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  376. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  377. # handler (console included), whether or not file logging is on.
  378. from backend.app.core.logging_filters import ( # noqa: E402
  379. QueryTokenRedactFilter,
  380. ShutdownCancelledRequestFilter,
  381. )
  382. # First, so the traceback of a stream cancelled at shutdown is dropped before
  383. # the filters below render it.
  384. logging.getLogger("uvicorn.error").addFilter(ShutdownCancelledRequestFilter())
  385. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  386. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  387. logging.getLogger(_uvicorn_logger).addFilter(_refused_header_filter)
  388. # These stay at WARNING even in debug mode: at INFO/DEBUG httpx/httpcore log
  389. # full request URLs, and some carry credentials (bot tokens, webhook URLs, API
  390. # keys in the query). Same as the runtime log-level toggle in support.py.
  391. logging.getLogger("httpcore").setLevel(logging.WARNING)
  392. logging.getLogger("httpx").setLevel(logging.WARNING)
  393. # aiosqlite logs every statement with its parameters at DEBUG.
  394. logging.getLogger("aiosqlite").setLevel(logging.WARNING)
  395. # Reduce noise from third-party libraries in production
  396. if not app_settings.debug:
  397. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  398. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  399. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  400. # Track active prints: {(printer_id, filename): archive_id}
  401. _active_prints: dict[tuple[int, str], int] = {}
  402. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  403. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  404. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  405. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  406. # instead of running its own grab-now chain when present, so the finish photo
  407. # captures the better-framed pre-bed-drop moment without us having to force
  408. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  409. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  410. #
  411. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  412. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  413. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  414. # bank and the others are not — so the consumer can't tell them apart and
  415. # must not rotate again.
  416. _stage22_finish_frames: dict[int, bytes] = {}
  417. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  418. # `finally` block (whether it captured a frame or not). The consumer in
  419. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  420. # so the FINISH-state fallback path — where moment and completion are dispatched
  421. # back-to-back — doesn't race past the producer with an empty pop, and the
  422. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  423. # grab (Bambu printers allow only one RTSP client at a time).
  424. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  425. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  426. # layer-change and on print-progress advances (#2547) while the model is still
  427. # printing, then consumed by the FINISH-state finish-photo path when the
  428. # dispatcher recorded that it injected End G-code into this print. Bambu
  429. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  430. # plate-swap) has run, so a live grab there would capture the swapped/empty
  431. # plate.
  432. #
  433. # The load-bearing property: both drivers are print telemetry that stops before
  434. # the End G-code executes — no further layer_num increases, and mc_percent
  435. # freezes — so the last banked frame is always the finished print before the
  436. # swap. Anything added as a third driver must hold that same property.
  437. _inprint_frame_bank: dict[int, bytes] = {}
  438. # Monotonic timestamp of the last banked frame per printer — throttles banking
  439. # so tall prints don't add a camera grab on every layer.
  440. _inprint_frame_bank_ts: dict[int, float] = {}
  441. # Minimum seconds between banked frames, except the final object layer which
  442. # always refreshes for the best framing.
  443. _INPRINT_BANK_MIN_INTERVAL = 25.0
  444. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  445. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  446. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  447. # the first connected status update for that connection; transitions back
  448. # to False whenever we observe `state.connected = False` so the next
  449. # reconnect re-arms reconciliation. Keyed by printer_id.
  450. _printer_reconciled_since_connect: dict[int, bool] = {}
  451. # Same edge, same keying, for priming the printer's calibration table exactly
  452. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  453. # is otherwise filled only when someone opens the Profiles page or Configure
  454. # Slot, when a GitHub backup runs, or when the printer happens to answer
  455. # somebody else's query on the report topic. Until then the AMS slot card has
  456. # no K value to show on the printers whose trays carry none of their own
  457. # (#2854 — H2-series report cali_idx and nothing more).
  458. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  459. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  460. # {(printer_id, filename): archive_id}
  461. _expected_prints: dict[tuple[int, str], int] = {}
  462. # Archives of the running prints Bambuddy dispatched itself: adopted from an
  463. # expected print, or found with Bambuddy's dispatch marker. _active_prints holds
  464. # every print on_print_start archived, those started from Bambu Studio, Handy or
  465. # the printer's screen included, so it is no proof of ownership on its own.
  466. _owned_print_archive_ids: set[int] = set()
  467. # What a dispatch registered for its print, keyed (printer_id, archive_id):
  468. # plates of one archive print on two printers at once, each with its own.
  469. # Track AMS mapping for prints: {(printer_id, archive_id): [global_tray_id_per_slot]}
  470. # Used by usage tracker to map 3MF slots to physical AMS trays
  471. _print_ams_mappings: dict[tuple[int, int], list[int]] = {}
  472. # Track cost center selection for the current print run: {(printer_id, archive_id): cost_center_id}
  473. _print_cost_center_ids: dict[tuple[int, int], int] = {}
  474. # Track plate_id for prints from multi-plate 3MFs: {(printer_id, archive_id): plate_id}
  475. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  476. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  477. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  478. # for the queue path. Cleared on print completion or TTL eviction.
  479. _print_plate_ids: dict[tuple[int, int], int] = {}
  480. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  481. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  482. _last_progress_milestone: dict[int, int] = {}
  483. # Track whether first layer complete notification has been sent for current print
  484. _first_layer_notified: dict[int, bool] = {}
  485. # Track whether we already sent a kill-switch stop for the current unauthorized print
  486. _unauthorized_print_kill_sent: set[int] = set()
  487. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  488. # lookup briefly so an unknown active print does not query the database on
  489. # every status frame. A short TTL keeps settings changes responsive.
  490. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  491. _kill_switch_setting_cache: tuple[bool, float] | None = None
  492. # Provider notification started when the kill switch stops a print. The later
  493. # MQTT print-complete callback awaits this task and only sends its regular
  494. # provider notification when the immediate attempt failed.
  495. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  496. # HMS faults already notified, with when each was last seen:
  497. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  498. # fault that flickers beside a held notice was forgotten on every gap and
  499. # notified on every return (#3226). The window is long because the measured
  500. # gaps reach 64 s.
  501. _notified_hms_errors: dict[int, dict[str, float]] = {}
  502. _HMS_CLEAR_GRACE_SECONDS = 600.0
  503. # The print state each printer was last seen in, and the faults recorded before
  504. # it last changed, which are forgotten as soon as they are gone (see
  505. # _take_new_hms_faults).
  506. _hms_print_state: dict[int, str] = {}
  507. _hms_forget_when_gone: dict[int, set[str]] = {}
  508. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  509. # Used for snapshot-diff detection at print completion
  510. _timelapse_baselines: dict[int, set[str]] = {}
  511. # Printers whose baseline above was taken off a card that could not be read,
  512. # so it is empty without the card being empty (#3412).
  513. _timelapse_baselines_unread: set[int] = set()
  514. # Track printers waiting for bed to cool after print completion.
  515. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  516. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  517. _bed_cool_waiters: dict[int, dict] = {}
  518. # Track printers where the user explicitly stopped the print from the queue UI.
  519. # When on_print_complete fires with status "failed" for these printers we treat it
  520. # as "cancelled" (stopped by user) so the correct notification email is sent.
  521. _user_stopped_printers: set[int] = set()
  522. # Printers whose running print the kill switch stopped. Their completion is a
  523. # cancel with the reason "killSwitch", not the "failed" the printer reports.
  524. _kill_switch_stopped: set[int] = set()
  525. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  526. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  527. # holds the previous observation so we only fire on the True → False edge (a
  528. # False → False repeat doesn't notify; an initial False at startup doesn't
  529. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  530. # holds the per-printer pending asyncio task that fires the notification
  531. # after a debounce window — cancelled if the printer reconnects before the
  532. # window elapses, so transient MQTT blips don't flood the user.
  533. _printer_last_connected: dict[int, bool] = {}
  534. # Printers whose relay offline event went out, so the reconnect publishes the
  535. # matching online event and a blip shorter than the debounce publishes neither.
  536. _printer_offline_published: set[int] = set()
  537. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  538. # Debounce: a printer must stay offline this long before we notify. Sized
  539. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  540. # so a single stale-trigger cooldown isn't enough to fire — only a real
  541. # offline that survives one reconnect attempt notifies.
  542. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  543. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  544. # when status="failed" to label the print's failure_reason in archives.
  545. #
  546. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  547. # which is wrong on two counts:
  548. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  549. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  550. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  551. # the public wiki) as part of its user-cancel sequence. Matching on the module
  552. # alone caused user-cancellations to be archived as "Layer shift" failures.
  553. # We now match by full short code only — anything not in this map leaves
  554. # failure_reason=None rather than guessing.
  555. # Values are the canonical camelCase failure-reason keys, NOT display labels
  556. # (issue #2974). The vocabulary is enforced on writes by
  557. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  558. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  559. # Statistics breakdown. Storing a label here instead put a second spelling of
  560. # the same cause into one column: the Failure Analysis widget groups on the raw
  561. # value, so a print the backend classified and an identical one a user
  562. # classified counted as two different reasons, and the label form could never
  563. # be translated because there was no key for ``t()`` to resolve.
  564. _HMS_FAILURE_REASONS: dict[str, str] = {
  565. # Layer shift / step loss
  566. "0300_4057": "layerShift",
  567. "0300_4068": "layerShift",
  568. "0300_800C": "layerShift",
  569. # Filament runout (printer-side & per-AMS-slot)
  570. "0300_8004": "filamentRunout",
  571. "0700_8011": "filamentRunout",
  572. "0701_8011": "filamentRunout",
  573. "0702_8011": "filamentRunout",
  574. "0703_8011": "filamentRunout",
  575. "0704_8011": "filamentRunout",
  576. "0705_8011": "filamentRunout",
  577. "0706_8011": "filamentRunout",
  578. "0707_8011": "filamentRunout",
  579. "07FF_8011": "filamentRunout",
  580. # Clogged nozzle / extruder
  581. "0300_4006": "cloggedNozzle",
  582. "0300_8016": "cloggedNozzle",
  583. "0300_801C": "cloggedNozzle",
  584. "0700_8003": "cloggedNozzle",
  585. "0700_8007": "cloggedNozzle",
  586. "0700_8013": "cloggedNozzle",
  587. "0701_8003": "cloggedNozzle",
  588. "0701_8007": "cloggedNozzle",
  589. "0701_8013": "cloggedNozzle",
  590. "0702_8003": "cloggedNozzle",
  591. # AI print monitoring — spaghetti / the model coming off the plate.
  592. # `spaghettiDetached` is a key the archive editor already offers for this
  593. # failure mode, not a new one, so a derived reason opens the dropdown on
  594. # that option rather than blank — and survives the next save, which clears
  595. # any value the editor does not recognise.
  596. #
  597. # A module-0x0C row is safe here despite the warning above: that warning is
  598. # about matching on the module alone, and 0C00_8042 is a full short code
  599. # with a documented meaning ("The AI print monitor has detected a spaghetti
  600. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  601. # cannot collide.
  602. #
  603. # 0300_8003's own text ends "before continuing your print", but on an X2D
  604. # it arrives with the print already paused, offering only
  605. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  606. #
  607. # Two neighbours are left out on purpose, so this does not get re-derived:
  608. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  609. # reads as a warning about a print that is still running, not a halt.
  610. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  611. # the waste chute. That is not the print failing.
  612. #
  613. # That line is drawn from the text, not from `severity`, because severity
  614. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  615. # module/error word with no level in it, and bambu_mqtt.py gives every
  616. # print_error entry a flat severity=3. Matching on the short code alone is
  617. # the right shape for derive_failure_reason, not an omission.
  618. "0300_8003": "spaghettiDetached",
  619. "0C00_8042": "spaghettiDetached",
  620. }
  621. def _hms_short_code(attr: int, code: int | str) -> str:
  622. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  623. if isinstance(code, str):
  624. code_int = int(code.replace("0x", ""), 16) if code else 0
  625. else:
  626. code_int = int(code or 0)
  627. attr_int = int(attr or 0)
  628. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  629. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  630. """Derive the failure_reason key for an archived print.
  631. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  632. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  633. no HMS code matches (don't guess — null is honest). The keys are the
  634. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  635. translated at render time.
  636. """
  637. if status in ("aborted", "cancelled"):
  638. return "userCancelled"
  639. if status != "failed":
  640. return None
  641. for err in hms_errors or []:
  642. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  643. if short_code in _HMS_FAILURE_REASONS:
  644. return _HMS_FAILURE_REASONS[short_code]
  645. return None
  646. # Track created_by_id for expected prints so the user email can be sent even when
  647. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  648. # {(printer_id, filename): created_by_id}
  649. _expected_print_creators: dict[tuple[int, str], int] = {}
  650. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  651. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  652. # tag tuple changes for the slot. Cleared when the slot is reported empty
  653. # so remove + reinsert reliably re-prompts the UI.
  654. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  655. async def _broadcast_unknown_tag(
  656. *,
  657. printer_id: int,
  658. ams_id: int,
  659. tray_id: int,
  660. tag_uid: str,
  661. tray_uuid: str,
  662. tray_type: str | None = None,
  663. tray_color: str | None = None,
  664. tray_sub_brands: str | None = None,
  665. tray_count: int | None = None,
  666. ) -> None:
  667. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  668. _logger = logging.getLogger(__name__)
  669. slot_key = (ams_id, tray_id)
  670. tag_key = (tag_uid or "", tray_uuid or "")
  671. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  672. if per_printer.get(slot_key) == tag_key:
  673. _logger.debug(
  674. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  675. printer_id,
  676. ams_id,
  677. tray_id,
  678. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  679. )
  680. return
  681. _logger.info(
  682. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  683. printer_id,
  684. ams_id,
  685. tray_id,
  686. tray_type,
  687. tray_color,
  688. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  689. )
  690. # Broadcast first; only commit the dedup if the WS write succeeds.
  691. # If broadcast raises, the next MQTT push retries instead of being
  692. # permanently silenced by a poisoned dedup entry.
  693. await ws_manager.broadcast(
  694. {
  695. "type": "unknown_tag",
  696. "printer_id": printer_id,
  697. "ams_id": ams_id,
  698. "tray_id": tray_id,
  699. "tag_uid": tag_uid,
  700. "tray_uuid": tray_uuid,
  701. "tray_type": tray_type,
  702. "tray_color": tray_color,
  703. "tray_sub_brands": tray_sub_brands,
  704. "tray_count": tray_count,
  705. }
  706. )
  707. per_printer[slot_key] = tag_key
  708. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  709. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  710. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  711. if per_printer is None:
  712. return
  713. per_printer.pop((ams_id, tray_id), None)
  714. # TTL for expected-print entries: evict registrations older than this to prevent
  715. # unbounded growth when a print is registered but never starts (e.g. printer
  716. # disconnect, app restart, print started from the printer panel).
  717. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  718. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  719. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  720. # Cleanup loop interval
  721. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  722. _expected_prints_cleanup_task: asyncio.Task | None = None
  723. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  724. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  725. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  726. possible_keys: list[tuple[int, str]] = []
  727. filename = (state.gcode_file or state.current_print or "").strip()
  728. subtask_name = (state.subtask_name or "").strip()
  729. if subtask_name:
  730. possible_keys.append((printer_id, subtask_name))
  731. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  732. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  733. if filename:
  734. base_name = filename.rsplit("/", 1)[-1]
  735. if base_name.endswith(".gcode.3mf"):
  736. root_name = base_name[: -len(".gcode.3mf")]
  737. possible_keys.append((printer_id, root_name))
  738. possible_keys.append((printer_id, base_name))
  739. possible_keys.append((printer_id, f"{root_name}.gcode"))
  740. possible_keys.append((printer_id, f"{root_name}.3mf"))
  741. elif base_name.endswith(".3mf"):
  742. root_name = base_name[: -len(".3mf")]
  743. possible_keys.append((printer_id, root_name))
  744. possible_keys.append((printer_id, base_name))
  745. elif base_name.endswith(".gcode"):
  746. root_name = base_name[: -len(".gcode")]
  747. possible_keys.append((printer_id, root_name))
  748. possible_keys.append((printer_id, f"{root_name}.3mf"))
  749. possible_keys.append((printer_id, base_name))
  750. else:
  751. possible_keys.append((printer_id, base_name))
  752. possible_keys.append((printer_id, f"{base_name}.3mf"))
  753. return possible_keys
  754. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  755. """The id of who started the print, unless that user has been deleted since.
  756. Deleting a user forgets them in printer_manager, but a print that ended a
  757. moment before still holds them.
  758. """
  759. if not print_user or print_user.get("user_id") is None:
  760. return None
  761. from backend.app.models.user import User
  762. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  763. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  764. """Check the cheap, process-local print ownership signals."""
  765. if printer_manager.get_current_print_user(printer_id):
  766. return True
  767. return any(
  768. key in _expected_prints or _active_prints.get(key) in _owned_print_archive_ids
  769. for key in _build_status_print_keys(printer_id, state)
  770. )
  771. def _reported_print_names(printer_id: int, state: PrinterState) -> set[str]:
  772. """The names the printer reports for its print, as it echoes them (spaces become underscores)."""
  773. return {_normalise_subtask_name(name) for _pid, name in _build_status_print_keys(printer_id, state)} - {""}
  774. async def _printing_archive_without_job_id(
  775. db, printer_id: int, reported: set[str], *, dispatched_only: bool, live_only: bool = False
  776. ):
  777. """The newest printing archive on ``printer_id`` of a print that reported no job id, under a reported name.
  778. An archive with a real id of its own is a print that reported one: a "0"
  779. print is not it, even under the same name (one whose completion was missed
  780. would otherwise cover it). ``dispatched_only`` keeps to archives carrying
  781. Bambuddy's dispatch marker; ``live_only`` leaves out deleted ones.
  782. """
  783. from backend.app.models.archive import PrintArchive
  784. query = select(PrintArchive).where(
  785. PrintArchive.printer_id == printer_id,
  786. PrintArchive.status == "printing",
  787. or_(PrintArchive.subtask_id.is_(None), PrintArchive.subtask_id.in_(("", "0"))),
  788. )
  789. if dispatched_only:
  790. query = query.where(or_(PrintArchive.billing_run_id.is_not(None), PrintArchive.created_by_id.is_not(None)))
  791. if live_only:
  792. query = query.where(PrintArchive.deleted_at.is_(None))
  793. archives = await db.execute(query.order_by(PrintArchive.created_at.desc()))
  794. return next((a for a in archives.scalars() if _archive_name_forms(a) & reported), None)
  795. async def running_print_archive(db, printer_id: int, state: PrinterState, *, printing_only: bool, by_name: bool):
  796. """The archive of the print running on ``printer_id``, or None (#3327).
  797. By the print's subtask_id first, which the firmware mints per print; with
  798. ``printing_only`` only an archive that is still printing (a leftover row of
  799. a completion never seen must not stand in for another job). A print
  800. started outside the cloud (Bambu Studio over LAN, Handy, the printer's
  801. screen) reports subtask_id "0", which links it to nothing: the archive
  802. Bambuddy bound to the running print comes next, the one completion charges
  803. and photographs. A restart forgets that binding and rebinds only Bambuddy's
  804. own prints, so with ``by_name`` a "0" print last falls back to its printing
  805. archive under the name the printer reports. That can be an earlier run of
  806. the same name whose completion was missed while Bambuddy was down: good
  807. enough for a plate label or a cover, not for which objects skip-objects
  808. offers, so those callers leave it off. None until the archive exists, and
  809. never a deleted one.
  810. """
  811. from backend.app.models.archive import PrintArchive
  812. from backend.app.services.print_log import open_run_on_printer
  813. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  814. if subtask_id not in ("", "0"):
  815. # The run open on the printer for this job: the archive row is shared
  816. # by every plate of it, its printer and job id the latest start's.
  817. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  818. if run is not None and run.archive_id is not None:
  819. archive = await db.scalar(
  820. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  821. )
  822. if archive is not None:
  823. return archive
  824. query = select(PrintArchive).where(
  825. PrintArchive.printer_id == printer_id,
  826. PrintArchive.subtask_id == subtask_id,
  827. PrintArchive.deleted_at.is_(None),
  828. )
  829. if printing_only:
  830. query = query.where(PrintArchive.status == "printing")
  831. archive = await db.scalar(query.order_by(PrintArchive.created_at.desc()).limit(1))
  832. if archive is not None:
  833. return archive
  834. bound = next(
  835. (_active_prints[key] for key in _build_status_print_keys(printer_id, state) if key in _active_prints),
  836. None,
  837. )
  838. if bound is not None:
  839. return await db.scalar(select(PrintArchive).where(PrintArchive.id == bound, PrintArchive.deleted_at.is_(None)))
  840. if not by_name or subtask_id != "0":
  841. return None
  842. reported = _reported_print_names(printer_id, state)
  843. if not reported:
  844. return None
  845. return await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=False, live_only=True)
  846. def _bind_active_print(
  847. printer_id: int,
  848. archive_id: int,
  849. archive_filename: str | None,
  850. filename: str | None = None,
  851. subtask_name: str | None = None,
  852. ) -> None:
  853. """Track a running print under every name its completion may report.
  854. One set for every path that binds a print (new archive, expected print,
  855. restart resume, fallback): the archive's file name, the name the printer
  856. reported, and the subtask with and without ``.3mf``. Paths that registered
  857. fewer names lost the bound archive at completion, and with it the plate
  858. restore's height (#3240), whenever MQTT reported a name they had left out.
  859. """
  860. for name in {archive_filename, filename, f"{subtask_name}.3mf" if subtask_name else None, subtask_name}:
  861. if name:
  862. _active_prints[(printer_id, name)] = archive_id
  863. async def _archive_of_open_run(printer_id: int, subtask_id: str | None = None) -> int | None:
  864. """The archive of the run open on the printer, if it is still there.
  865. With ``subtask_id``, only a run of that job."""
  866. try:
  867. from backend.app.models.archive import PrintArchive
  868. from backend.app.services.print_log import open_run_on_printer
  869. async with async_session() as db:
  870. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  871. if run is None or run.archive_id is None:
  872. return None
  873. return await db.scalar(
  874. select(PrintArchive.id).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  875. )
  876. except Exception as e:
  877. logging.getLogger(__name__).warning("[RUN] Could not read the open run of printer %s: %s", printer_id, e)
  878. return None
  879. async def _announce_discarded_runs(discarded, printer_id: int) -> None:
  880. """Publish the runs ``discard_open_runs`` dropped (archive redesign):
  881. each announced by run/started, now gone without an end."""
  882. if not discarded:
  883. return
  884. try:
  885. from backend.app.models.printer import Printer
  886. async with async_session() as db:
  887. printer = (
  888. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  889. ).first()
  890. if printer is not None:
  891. for run in discarded:
  892. await mqtt_relay.on_run_discarded(run, printer.serial_number, printer.name)
  893. except Exception as e:
  894. logging.getLogger(__name__).debug("[RUN] Could not announce discarded runs on printer %s: %s", printer_id, e)
  895. async def _publish_run_completed(run_id: int | None, printer_id: int) -> None:
  896. """Publish the run a print's end just wrote on the MQTT relay (archive
  897. redesign); nothing without one. Never in the way of the completion."""
  898. if run_id is None:
  899. return
  900. try:
  901. from backend.app.models.archive import PrintArchive
  902. from backend.app.models.print_log import PrintLogEntry
  903. from backend.app.models.printer import Printer
  904. async with async_session() as db:
  905. run = await db.get(PrintLogEntry, run_id)
  906. printer = (
  907. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  908. ).first()
  909. archive = await db.get(PrintArchive, run.archive_id) if run is not None and run.archive_id else None
  910. if run is not None and printer is not None:
  911. await mqtt_relay.on_run_completed(run, archive, printer.serial_number, printer.name)
  912. except Exception as e:
  913. logging.getLogger(__name__).debug("[RUN] Could not publish the end of run %s: %s", run_id, e)
  914. async def _open_run_for(archive_id: int, printer_id: int, subtask_id: str | None = None) -> None:
  915. """Write the run of the print that just started on the archive (archive
  916. redesign). In a session of its own and never in the way of the print
  917. start: until its readers move over, the archive still carries the print.
  918. The archive's start must be committed before. ``subtask_id`` is the
  919. printer's job, which finds the run again at a resume."""
  920. try:
  921. from backend.app.models.archive import PrintArchive
  922. from backend.app.models.printer import Printer
  923. from backend.app.services.print_log import open_run, open_run_on_printer, run_snapshot
  924. async with async_session() as db:
  925. archive = await db.get(PrintArchive, archive_id)
  926. if archive is None:
  927. return
  928. printer = (
  929. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  930. ).first()
  931. printer_name = printer.name if printer is not None else None
  932. already = await open_run_on_printer(db, printer_id)
  933. before = run_snapshot(already) if already is not None else None
  934. run = await open_run(
  935. db,
  936. archive,
  937. printer_id=printer_id,
  938. printer_name=printer_name,
  939. plate_id=_print_plate_ids.get((printer_id, archive_id)),
  940. subtask_id=subtask_id,
  941. )
  942. await db.commit()
  943. # Once per print: a resume or a repeated start finds the run it opened.
  944. # A new one replaced the run still open there (open_run): that one's
  945. # print ended unseen.
  946. # Compared by start too: SQLite can give the new run the id of the one
  947. # it replaced.
  948. replaced = (
  949. run is not None and before is not None and (before.id != run.id or before.started_at != run.started_at)
  950. )
  951. if run is not None and printer is not None and (before is None or replaced):
  952. if replaced:
  953. await _announce_discarded_runs([before], printer_id)
  954. try:
  955. await mqtt_relay.on_run_started(run, archive, printer.serial_number, printer_name)
  956. except Exception:
  957. pass # Don't fail the print start if MQTT fails
  958. except Exception as e:
  959. logging.getLogger(__name__).warning("[RUN] Could not open the run of archive %s: %s", archive_id, e)
  960. async def _drop_replaced_plate_videos(
  961. db, archive_id: int, plate_id: int | None, stale_relpath: str | None, logger: logging.Logger
  962. ) -> None:
  963. """Delete the videos a reprint of a plate replaces: ``stale_relpath``, the
  964. one the archive showed (when print start judged it this plate's), and
  965. those of the archive's earlier runs of the same plate. A plate keeps one
  966. video, as when the archive held the only one; another plate's stays. The
  967. runs that held them lose them. Commits."""
  968. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, PrintLogEntry
  969. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  970. runs = select(PrintLogEntry).where(
  971. PrintLogEntry.archive_id == archive_id, PrintLogEntry.timelapse_path.is_not(None)
  972. )
  973. with_video = list(await db.scalars(runs.execution_options(**{INCLUDE_OPEN_RUNS: True})))
  974. paths = {stale_relpath} if stale_relpath else set()
  975. if plate_id is not None:
  976. paths |= {r.timelapse_path for r in with_video if r.plate_id == plate_id}
  977. # A video another plate's run holds is that plate's.
  978. paths -= {r.timelapse_path for r in with_video if r.plate_id is not None and r.plate_id != plate_id}
  979. if not paths:
  980. return
  981. for run in with_video:
  982. if run.timelapse_path in paths:
  983. run.timelapse_path = None
  984. await db.commit()
  985. for relpath in sorted(p for p in paths if p):
  986. try:
  987. stale_path = safe_join_under(app_settings.base_dir, relpath, http=False)
  988. if stale_path.is_file():
  989. stale_path.unlink()
  990. logger.info("Deleted stale timelapse %s on reprint of archive %s", relpath, archive_id)
  991. except (OSError, PathTraversalError) as e:
  992. logger.warning("Failed to delete stale timelapse %s on reprint: %s", relpath, e)
  993. def _mark_owned_if_dispatched(archive) -> None:
  994. """Remember a running print's archive as Bambuddy's when it carries a
  995. dispatch marker Bambuddy writes itself: ``billing_run_id`` (minted per
  996. dispatch in the scheduler) or ``created_by_id`` (from the queue item)."""
  997. if archive.billing_run_id is not None or archive.created_by_id is not None:
  998. _owned_print_archive_ids.add(archive.id)
  999. async def _is_printer_kill_switch_enabled_cached() -> bool:
  1000. """Return the kill-switch setting without querying on every MQTT frame."""
  1001. global _kill_switch_setting_cache
  1002. now = time.monotonic()
  1003. if _kill_switch_setting_cache is not None:
  1004. enabled, expires_at = _kill_switch_setting_cache
  1005. if now < expires_at:
  1006. return enabled
  1007. async with async_session() as db:
  1008. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  1009. enabled = await is_printer_kill_switch_enabled(db)
  1010. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  1011. return enabled
  1012. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  1013. """Resolve whether the current print was started by Bambuddy.
  1014. ``None`` means identity is not yet safe to decide. The kill switch must
  1015. defer in that case: stopping a print is irreversible, and the first status
  1016. frames after a restart may arrive before all subtask fields are populated.
  1017. """
  1018. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1019. return True
  1020. # The printer's built-in calibration runs (Bambuddy's Calibrate, the
  1021. # printer's screen) play gcode from its read-only system partition, where no
  1022. # user file can be. Only that path counts: a calibration *name* proves
  1023. # nothing, since Bambu Studio's pressure-advance print reports a user-style
  1024. # path, and any print can be given that name.
  1025. if str(getattr(state, "gcode_file", "") or "").startswith("/usr/"):
  1026. return True
  1027. # A1, A1 Mini, P1 and A2L report the same calibration as a bare file name,
  1028. # which nothing distinguishes from a user's file given that name, so it is
  1029. # not exempt: with the kill switch on, calibrate on those printers with the
  1030. # switch off.
  1031. possible_keys = _build_status_print_keys(printer_id, state)
  1032. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  1033. # is on disk. subtask_id is minted per print and pins the answer to the job
  1034. # actually running, rather than to an unrelated one that reuses a filename.
  1035. raw_subtask_id = getattr(state, "subtask_id", None)
  1036. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  1037. if subtask_id == "":
  1038. # Not reported yet: the first frames after a restart can lack it.
  1039. return None
  1040. from backend.app.models.archive import PrintArchive
  1041. if subtask_id == "0":
  1042. # A print started outside the cloud from Bambu Studio, Handy or the
  1043. # printer's screen reports "0", so there is no id to match: one of
  1044. # Bambuddy's printing archives on this printer under the name the
  1045. # printer reports, compared as the printer echoes names (spaces become
  1046. # underscores). Nothing reported to compare yet: wait.
  1047. reported = _reported_print_names(printer_id, state)
  1048. if not reported:
  1049. return None
  1050. archive = await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=True)
  1051. else:
  1052. from backend.app.services.print_log import open_run_on_printer
  1053. # This job's run open on the printer: the archive is shared by every
  1054. # plate of it, and its status, printer and job id are the latest
  1055. # start's, which may be another printer's.
  1056. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  1057. archive = await db.get(PrintArchive, run.archive_id) if run is not None and run.archive_id else None
  1058. if archive is None:
  1059. result = await db.execute(
  1060. select(PrintArchive)
  1061. .where(
  1062. PrintArchive.printer_id == printer_id,
  1063. PrintArchive.status == "printing",
  1064. PrintArchive.subtask_id == subtask_id,
  1065. )
  1066. .order_by(PrintArchive.created_at.desc())
  1067. .limit(1)
  1068. )
  1069. archive = result.scalar_one_or_none()
  1070. # An archive row on its own proves nothing: `on_print_start` archives every
  1071. # print it observes, including ones started from Bambu Studio or Handy, and
  1072. # stamps them with the same status and subtask_id. Authorizing on its mere
  1073. # existence would disable the kill switch the moment the 3MF finishes
  1074. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  1075. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  1076. # (carried over from the queue item that started it).
  1077. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  1078. # Rehydrate the fast in-memory path for subsequent status frames. Include
  1079. # both the archive filename and every normalized key reported by MQTT.
  1080. _owned_print_archive_ids.add(archive.id)
  1081. _active_prints[(printer_id, archive.filename)] = archive.id
  1082. for key in possible_keys:
  1083. _active_prints[key] = archive.id
  1084. return True
  1085. # No dispatch marker. Before calling this someone else's print, check whether
  1086. # Bambuddy has a job of its own running on this printer: a library-file
  1087. # dispatch has no archive at send time, and an archive created seconds later
  1088. # by `on_print_start` carries neither marker. The queue row, which the
  1089. # scheduler commits to status="printing" before the MQTT send, is the one
  1090. # durable record every Bambuddy print has. It cannot be tied to this
  1091. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  1092. # print is irreversible, and refusing to act costs nothing but a log line.
  1093. from backend.app.models.print_queue import PrintQueueItem
  1094. dispatched_here = await db.scalar(
  1095. select(PrintQueueItem.id)
  1096. .where(
  1097. PrintQueueItem.printer_id == printer_id,
  1098. PrintQueueItem.status == "printing",
  1099. )
  1100. .limit(1)
  1101. )
  1102. if dispatched_here is not None:
  1103. return None
  1104. return False
  1105. async def _send_kill_switch_provider_notification(
  1106. printer_id: int,
  1107. printer_name: str,
  1108. data: dict,
  1109. ) -> bool:
  1110. """Send the immediate print-stopped provider notification.
  1111. Returning a success flag lets the normal MQTT completion path retry when
  1112. this early notification could not be delivered.
  1113. """
  1114. logger = logging.getLogger(__name__)
  1115. try:
  1116. async with async_session() as db:
  1117. from backend.app.services.print_log import open_run_on_printer
  1118. # The print it stopped, for {archive_id} / {run_id}: the completion
  1119. # that would name them skips its notification after this one.
  1120. run = await open_run_on_printer(db, printer_id)
  1121. await notification_service.on_print_complete(
  1122. printer_id,
  1123. printer_name,
  1124. "stopped",
  1125. data,
  1126. db,
  1127. archive_data={"archive_id": run.archive_id, "run_id": run.id} if run is not None else None,
  1128. )
  1129. return True
  1130. except Exception as e:
  1131. logger.warning(
  1132. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  1133. printer_id,
  1134. e,
  1135. )
  1136. return False
  1137. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  1138. """Wait for an immediate kill-switch notification, if one was scheduled."""
  1139. if task is None:
  1140. return False
  1141. try:
  1142. return await task
  1143. except Exception as e:
  1144. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  1145. return False
  1146. async def _run_needs_energy_start(archive, printer_id: int, db) -> bool:
  1147. """At a resume: whether the print's run still lacks its energy start
  1148. reading. The archive's may be an earlier print's. Commits a reading
  1149. found on the archive for this run onto it."""
  1150. try:
  1151. from backend.app.services.print_log import run_needs_energy_start
  1152. needs = await run_needs_energy_start(db, archive, printer_id=printer_id)
  1153. await db.commit()
  1154. return needs
  1155. except Exception as e:
  1156. logging.getLogger(__name__).warning("[RUN] Energy start of archive %s's run not checked: %s", archive.id, e)
  1157. return archive.energy_start_kwh is None
  1158. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  1159. """Capture the smart plug lifetime counter on the archive at print start.
  1160. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  1161. tracking survives a backend restart mid-print. The print-end handler reads
  1162. this value back from the DB and computes the delta against the current
  1163. plug counter.
  1164. """
  1165. _logger = logging.getLogger(__name__)
  1166. try:
  1167. candidates = await energy_plug_candidates(db, printer_id)
  1168. if not candidates:
  1169. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  1170. return False
  1171. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  1172. if selected is None:
  1173. # Naming the plugs matters here: with several linked to one printer
  1174. # this is the difference between "the meter is offline" and "you
  1175. # linked only accessories" (#2859).
  1176. _logger.warning(
  1177. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  1178. printer_id,
  1179. archive.id,
  1180. ", ".join(plug.name for plug in candidates),
  1181. )
  1182. return False
  1183. plug, energy = selected
  1184. archive.energy_start_kwh = float(energy["total"])
  1185. # With the plug's snapshots, what lets the cost follow the price over
  1186. # the print rather than take the price at its end (#1251). A price that
  1187. # can't be had must not cost the print its energy reading.
  1188. archive.energy_start_at = utcnow_naive()
  1189. archive.energy_start_plug_id = plug.id
  1190. try:
  1191. from backend.app.services.energy_price import current_price
  1192. archive.energy_start_price = await current_price(db)
  1193. except Exception as e:
  1194. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  1195. archive.energy_start_price = None
  1196. try:
  1197. from backend.app.services.print_log import mirror_energy_start
  1198. await mirror_energy_start(db, archive, printer_id=printer_id)
  1199. except Exception as e:
  1200. _logger.warning("[RUN] Energy start not copied onto the run of archive %s: %s", archive.id, e)
  1201. await db.commit()
  1202. _logger.info(
  1203. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  1204. f" ({context})" if context else "",
  1205. archive.id,
  1206. plug.name,
  1207. energy["total"],
  1208. )
  1209. return True
  1210. except Exception as e:
  1211. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  1212. return False
  1213. def forget_print_creator(user_id: int) -> None:
  1214. """The print-start emails of a deleted user's jobs go to nobody, not to
  1215. whoever is given the id next (SQLite reuses it)."""
  1216. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  1217. del _expected_print_creators[key]
  1218. async def forget_printer(printer_id: int) -> None:
  1219. """Drop what is kept for a deleted printer's id, here and in the services.
  1220. SQLite used to give the id to the next printer created, which inherited it
  1221. all: the running print's owner (its prints passed the kill switch and were
  1222. billed to that user), the plate-clear gate, pending and suppressed
  1223. notifications, the camera feed, the plate references. Ids are no longer
  1224. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  1225. stay. Called after the delete is committed, and again by work that was in
  1226. flight and wrote state back.
  1227. Every printer-keyed map of this module is listed here or, with the reason,
  1228. in tests/unit/test_forget_printer.py.
  1229. """
  1230. from backend.app.api.routes import camera
  1231. from backend.app.services import (
  1232. bambu_ftp,
  1233. kprofile_drift,
  1234. layer_timelapse,
  1235. plate_detection,
  1236. print_dispatch_context,
  1237. usage_tracker,
  1238. )
  1239. from backend.app.services.notify_live_activities import notify_live_activities
  1240. from backend.app.services.obico_detection import obico_detection_service
  1241. from backend.app.services.printer_file_cache import printer_file_cache
  1242. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  1243. archive_ids = set()
  1244. for tracked in (_active_prints, _expected_prints):
  1245. for key in [key for key in tracked if key[0] == printer_id]:
  1246. archive_ids.add(tracked.pop(key))
  1247. for archive_id in archive_ids:
  1248. _owned_print_archive_ids.discard(archive_id)
  1249. for registered in (_print_ams_mappings, _print_cost_center_ids, _print_plate_ids):
  1250. for key in [key for key in registered if key[0] == printer_id]:
  1251. del registered[key]
  1252. for tracked in (_expected_print_creators, _expected_print_registered_at):
  1253. for key in [key for key in tracked if key[0] == printer_id]:
  1254. del tracked[key]
  1255. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  1256. _ams_index_only_logged.discard(key)
  1257. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  1258. del _ams_alarm_cooldown[key]
  1259. # Pending work that would act on the id: an offline notice, a 3MF retry.
  1260. # A kill-switch notice is about a stop that happened and is left to finish.
  1261. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  1262. task = tasks.pop(printer_id, None)
  1263. if task is not None:
  1264. task.cancel()
  1265. for keyed in (
  1266. _stage22_finish_frames,
  1267. _stage22_finish_in_flight,
  1268. _inprint_frame_bank,
  1269. _inprint_frame_bank_ts,
  1270. _printer_reconciled_since_connect,
  1271. _printer_kprofiles_primed_since_connect,
  1272. _last_progress_milestone,
  1273. _first_layer_notified,
  1274. _kill_switch_notification_tasks,
  1275. _notified_hms_errors,
  1276. _hms_print_state,
  1277. _hms_forget_when_gone,
  1278. _timelapse_baselines,
  1279. _bed_cool_waiters,
  1280. _printer_last_connected,
  1281. _unknown_tag_last_broadcast,
  1282. _last_status_broadcast,
  1283. _connection_watchdog_last_attempt,
  1284. ):
  1285. keyed.pop(printer_id, None)
  1286. for marked in (
  1287. _unauthorized_print_kill_sent,
  1288. _user_stopped_printers,
  1289. _kill_switch_stopped,
  1290. _printer_offline_published,
  1291. _nozzle_count_updated,
  1292. _runtime_seen_connected,
  1293. _timelapse_baselines_unread,
  1294. ):
  1295. marked.discard(printer_id)
  1296. printer_manager.forget_printer(printer_id)
  1297. printer_file_cache.forget_printer(printer_id)
  1298. print_dispatch_context.clear(printer_id)
  1299. kprofile_drift.forget_printer(printer_id, deleted=True)
  1300. layer_timelapse.cancel_session(printer_id)
  1301. usage_tracker.forget_printer(printer_id)
  1302. obico_detection_service.forget_printer(printer_id)
  1303. octoeverywhere_detection_service.forget_printer(printer_id)
  1304. bambu_ftp.clear_3mf_cache(printer_id)
  1305. await camera.forget_printer(printer_id)
  1306. printers.clear_cover_cache(printer_id)
  1307. print_scheduler.forget_printer(printer_id)
  1308. notify_live_activities.forget_printer(printer_id)
  1309. plate_detection.remove_printer_references(printer_id)
  1310. def register_expected_print(
  1311. printer_id: int,
  1312. filename: str,
  1313. archive_id: int,
  1314. ams_mapping: list[int] | None = None,
  1315. created_by_id: int | None = None,
  1316. cost_center_id: int | None = None,
  1317. plate_id: int | None = None,
  1318. ):
  1319. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1320. # Store with multiple filename variations to catch different naming patterns
  1321. _expected_prints[(printer_id, filename)] = archive_id
  1322. # Also store without .3mf extension if present
  1323. if filename.endswith(".3mf"):
  1324. base = filename[:-4]
  1325. _expected_prints[(printer_id, base)] = archive_id
  1326. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1327. # Store AMS mapping for usage tracking at print completion, and plate_id for
  1328. # a single-plate dispatch from a multi-plate 3MF — without it, the direct-Print
  1329. # path attributes the whole file's filament total to the spool instead of just
  1330. # the printed plate (#1697). They describe this dispatch: one that has none
  1331. # drops what an earlier dispatch of the archive left (sent, never started),
  1332. # unless a plate of the archive is printing now and still needs them.
  1333. dispatch = (printer_id, archive_id)
  1334. archive_printing = _printing_here(printer_id, archive_id)
  1335. if ams_mapping is not None:
  1336. _print_ams_mappings[dispatch] = ams_mapping
  1337. elif not archive_printing:
  1338. _print_ams_mappings.pop(dispatch, None)
  1339. if cost_center_id is not None:
  1340. _print_cost_center_ids[dispatch] = cost_center_id
  1341. elif not archive_printing:
  1342. _print_cost_center_ids.pop(dispatch, None)
  1343. if plate_id is not None:
  1344. _print_plate_ids[dispatch] = plate_id
  1345. elif not archive_printing:
  1346. _print_plate_ids.pop(dispatch, None)
  1347. # Store created_by_id so the user start email can be sent even when the archive
  1348. # itself has no created_by_id (e.g. library-file-based queue prints)
  1349. if created_by_id is not None:
  1350. _expected_print_creators[(printer_id, filename)] = created_by_id
  1351. if filename.endswith(".3mf"):
  1352. base = filename[:-4]
  1353. _expected_print_creators[(printer_id, base)] = created_by_id
  1354. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1355. # Record registration time for TTL-based eviction
  1356. _registered_at = time.monotonic()
  1357. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1358. if filename.endswith(".3mf"):
  1359. base = filename[:-4]
  1360. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1361. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1362. logging.getLogger(__name__).info(
  1363. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1364. )
  1365. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1366. """Undo :func:`register_expected_print` when the print never went out.
  1367. Registration has to happen *before* the MQTT print command, because the
  1368. printer can report the print before the line after the send executes. So
  1369. every path that registers and then fails to send — a cancel winning the
  1370. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1371. between — leaves an expectation for a print that will never arrive.
  1372. The TTL sweep evicts those after two hours, which is far longer than it
  1373. takes a user to react to a failed dispatch by pressing print again: that
  1374. reprint would be folded into the *old* archive and take the stale
  1375. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1376. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1377. ``_print_ams_mappings`` / ``_print_plate_ids`` / ``_print_cost_center_ids``
  1378. are keyed by printer and archive, not by file, so they may only be dropped
  1379. once no live key of the printer still points at that archive.
  1380. """
  1381. keys = [(printer_id, filename)]
  1382. if filename.endswith(".3mf"):
  1383. base = filename[:-4]
  1384. keys.append((printer_id, base))
  1385. keys.append((printer_id, f"{base}.gcode"))
  1386. removed = False
  1387. for key in keys:
  1388. if _expected_prints.pop(key, None) is not None:
  1389. removed = True
  1390. _expected_print_creators.pop(key, None)
  1391. _expected_print_registered_at.pop(key, None)
  1392. # Still needed by another expected print of the archive on the printer,
  1393. # or a plate of it printing there, as in the sweep.
  1394. if not _expected_or_printing_here(printer_id, archive_id):
  1395. _drop_dispatch(printer_id, archive_id)
  1396. if removed:
  1397. logging.getLogger(__name__).info(
  1398. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1399. printer_id,
  1400. filename,
  1401. archive_id,
  1402. )
  1403. def _compute_run_filament_grams(
  1404. status: str,
  1405. archive_filament_used_grams: float | None,
  1406. progress: float | int | None,
  1407. usage_results: list[dict] | None,
  1408. ) -> float | None:
  1409. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1410. Priority for every status:
  1411. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1412. weight delta — same source that drives "Total Consumed" on the
  1413. Inventory page, so Stats and Inventory totals stay aligned).
  1414. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1415. back to the canonical "this print used X" value).
  1416. 3. For partial statuses: ``estimate * progress%``.
  1417. 4. ``None`` if nothing is known.
  1418. """
  1419. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1420. if tracked_grams > 0:
  1421. return round(tracked_grams, 1)
  1422. if status == "completed":
  1423. return archive_filament_used_grams
  1424. if archive_filament_used_grams:
  1425. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1426. if scale > 0:
  1427. return round(archive_filament_used_grams * scale, 1)
  1428. return None
  1429. def _printing_here(printer_id: int, archive_id: int) -> bool:
  1430. """Whether a plate of the archive is printing on the printer."""
  1431. return any(key[0] == printer_id and bound == archive_id for key, bound in _active_prints.items())
  1432. def _expected_or_printing_here(printer_id: int, archive_id: int) -> bool:
  1433. """Whether a print of the archive is expected or printing on the printer."""
  1434. return _printing_here(printer_id, archive_id) or any(
  1435. key[0] == printer_id and expected == archive_id for key, expected in _expected_prints.items()
  1436. )
  1437. def _drop_dispatch(printer_id: int, archive_id: int) -> None:
  1438. """Forget what the dispatch of the archive to the printer registered."""
  1439. dispatch = (printer_id, archive_id)
  1440. _print_ams_mappings.pop(dispatch, None)
  1441. _print_cost_center_ids.pop(dispatch, None)
  1442. _print_plate_ids.pop(dispatch, None)
  1443. def _get_start_ams_mapping(data: dict, printer_id: int, archive_id: int | None) -> list[int] | None:
  1444. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1445. stored_ams_mapping = data.get("ams_mapping")
  1446. if not stored_ams_mapping and archive_id:
  1447. stored_ams_mapping = _print_ams_mappings.get((printer_id, archive_id))
  1448. return stored_ams_mapping
  1449. def _get_start_plate_id(printer_id: int, archive_id: int | None) -> int | None:
  1450. """Resolve plate_id for print start without consuming stored direct-Print state.
  1451. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1452. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1453. read it back at print-start without popping (the entry is popped on print
  1454. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1455. """
  1456. if archive_id is None:
  1457. return None
  1458. return _print_plate_ids.get((printer_id, archive_id))
  1459. def _run_print_time_seconds(archive, printer_id: int) -> int | None:
  1460. """The slicer's time for the plate this print prints, for its start
  1461. notification (#3375): ``archive.print_time_seconds`` adds every plate of
  1462. the file up (#1593). The plate is the dispatch's, else the archive's. The
  1463. whole file's time when its plates are not known; None for a plate not
  1464. known of several, and the notification takes the printer's remaining
  1465. time."""
  1466. from backend.app.services.print_cost_estimate import run_estimate
  1467. plate_id = _print_plate_ids.get((printer_id, archive.id), archive.plate_id)
  1468. estimate = run_estimate(archive, plate_id)
  1469. return estimate.seconds if estimate is not None else None
  1470. _plate_estimates_task: asyncio.Task | None = None
  1471. async def _fill_plate_estimates() -> None:
  1472. from backend.app.services.print_cost_estimate import fill_plate_estimates
  1473. try:
  1474. filled = await fill_plate_estimates(async_session)
  1475. except asyncio.CancelledError:
  1476. raise
  1477. except Exception as exc:
  1478. logging.getLogger(__name__).warning("[ARCHIVE] Reading plate estimates failed: %s", exc)
  1479. return
  1480. if filled:
  1481. logging.getLogger(__name__).info("[ARCHIVE] Read the plate estimates of %d archive(s)", filled)
  1482. def _partial_progress_scale(progress: int | float | None) -> float:
  1483. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1484. Used by every site that multiplies a "would-have-used" slicer estimate
  1485. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1486. so the three sites in ``_background_notifications`` (and the per-plate
  1487. override helper) can't drift apart on the coercion shape.
  1488. """
  1489. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1490. def _scope_notification_archive_data_to_plate(
  1491. archive_data: dict,
  1492. archive_file_path: str | None,
  1493. plate_id: int | None,
  1494. print_status: str,
  1495. progress: int | float | None,
  1496. base_dir: Path,
  1497. ) -> dict:
  1498. """Override summed-across-plates totals in ``archive_data`` with the values
  1499. for ``plate_id`` so the completion notification reports what was actually
  1500. printed, not the whole project (#1785).
  1501. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1502. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1503. the archive card's "whole project" headline, wrong for the completion
  1504. notification of a single-plate print. The queue UI already re-reads the
  1505. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1506. notification payload (filament grams, time estimate, per-slot breakdown).
  1507. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1508. no per-plate values — in every fail case the original ``archive_data`` is
  1509. returned unchanged so the notification still sends.
  1510. """
  1511. if plate_id is None or not archive_file_path:
  1512. return archive_data
  1513. from backend.app.utils.threemf_tools import (
  1514. extract_filament_usage_from_3mf,
  1515. extract_print_time_from_3mf,
  1516. )
  1517. archive_path = base_dir / archive_file_path
  1518. if not archive_path.exists():
  1519. return archive_data
  1520. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1521. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1522. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1523. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1524. if plate_time:
  1525. archive_data["print_time_seconds"] = plate_time
  1526. # Gate both the grams headline AND the per-slot breakdown on the same
  1527. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1528. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1529. # to the project-level grams the archive columns already provide rather
  1530. # than ship a project-level headline next to an all-zero per-plate
  1531. # breakdown.
  1532. if plate_grams > 0:
  1533. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1534. archive_data["filament_slots"] = [
  1535. {
  1536. "slot_id": s.get("slot_id"),
  1537. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1538. "type": s.get("type", ""),
  1539. "color": s.get("color", ""),
  1540. }
  1541. for s in plate_slots
  1542. ]
  1543. return archive_data
  1544. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1545. """Best-effort filament metadata from the MQTT print-start snapshot.
  1546. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1547. file during print, see #1533) so the fallback PrintArchive still has
  1548. enough filament info to support the inventory views and AMS-expansion
  1549. planning the operator opens it for. Returns a dict with optional
  1550. ``filament_type`` and ``filament_color`` keys in the same
  1551. comma-separated format the 3MF extractor produces, so the rest of the
  1552. codebase treats the fallback archive identically to a normal one.
  1553. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1554. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1555. entries). When supplied, only the slots actually consumed by this
  1556. print contribute. Without it the function falls back to every loaded
  1557. AMS slot — less accurate but still useful.
  1558. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1559. that the unit tests pass directly, AND the on_print_start callback
  1560. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1561. bambu_mqtt service hands to main.py at runtime. The original
  1562. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1563. handled the inner shape and silently returned ``{}`` for every real
  1564. print start, leaving fallback archives' filament fields NULL — the
  1565. exact regression the fix was meant to close. Reported with a log
  1566. proving the AMS state was right there at
  1567. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1568. """
  1569. result: dict[str, str] = {}
  1570. # Look at the on_print_start wrapper first, then the inner shape.
  1571. raw_data = (data or {}).get("raw_data")
  1572. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1573. if not isinstance(ams_root, dict):
  1574. ams_root = (data or {}).get("ams") or {}
  1575. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1576. if not isinstance(ams_units, list) or not ams_units:
  1577. return result
  1578. from backend.app.services.print_scheduler import _global_tray_id
  1579. # Map global tray id → (type, color), addressed as the print's ams_mapping
  1580. # is: unit * 4 + tray, or the bare unit id for an AMS-HT (from 128).
  1581. loaded: dict[int, tuple[str, str]] = {}
  1582. for unit in ams_units:
  1583. if not isinstance(unit, dict):
  1584. continue
  1585. try:
  1586. unit_id = int(unit.get("id", 0))
  1587. except (TypeError, ValueError):
  1588. continue
  1589. for tray in unit.get("tray") or []:
  1590. if not isinstance(tray, dict):
  1591. continue
  1592. try:
  1593. tray_id = int(tray.get("id", 0))
  1594. except (TypeError, ValueError):
  1595. continue
  1596. ttype = (tray.get("tray_type") or "").strip()
  1597. # RRGGBBAA from the printer, stored as the 3MF path stores it:
  1598. # "#RRGGBB" (the Archives page's swatches and colour filter).
  1599. hex_color = (tray.get("tray_color") or "").strip().upper()[:6]
  1600. tcolor = f"#{hex_color}" if re.fullmatch(r"[0-9A-F]{6}", hex_color) else ""
  1601. if not ttype:
  1602. continue # Empty / unloaded slot.
  1603. loaded[_global_tray_id(unit_id, tray_id)] = (ttype, tcolor)
  1604. if not loaded:
  1605. return result
  1606. if ams_mapping:
  1607. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1608. filaments = [loaded[g] for g in used_ids if g in loaded]
  1609. if not filaments:
  1610. return result # Mapping points entirely at slots we have no data for.
  1611. else:
  1612. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1613. types_joined = ",".join(f[0] for f in filaments)
  1614. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1615. # Column limits per backend/app/models/archive.py: filament_type=50,
  1616. # filament_color=200.
  1617. if types_joined:
  1618. result["filament_type"] = types_joined[:50]
  1619. if colors_joined:
  1620. result["filament_color"] = colors_joined[:200]
  1621. return result
  1622. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1623. """Start a layer-timelapse session for *archive_id* when the printer has
  1624. an external camera configured. Returns True if a session was started.
  1625. Three call sites in on_print_start (expected-archive promotion, fallback
  1626. archive creation, fresh-archive creation) used to inline this same
  1627. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1628. on the first pass). Centralising the conditional + call here makes the
  1629. contract testable in isolation and keeps the three sites locked in step.
  1630. """
  1631. if not (printer.external_camera_enabled and printer.external_camera_url):
  1632. return False
  1633. from backend.app.services.layer_timelapse import start_session
  1634. start_session(
  1635. printer_id,
  1636. archive_id,
  1637. printer.external_camera_url,
  1638. printer.external_camera_type or "mjpeg",
  1639. snapshot_url=printer.external_camera_snapshot_url,
  1640. rotation=getattr(printer, "camera_rotation", 0),
  1641. )
  1642. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1643. return True
  1644. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1645. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1646. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1647. — since #2926 — the description the parser already resolved, which is preferred
  1648. when present so the queue's failure reason reads the same as the status
  1649. response. The short code still produces the bracketed label, and still
  1650. resolves the sentence for a caller whose entries predate the field. An entry
  1651. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1652. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1653. label when no description is on file. Returns None for an empty list so
  1654. callers can leave error_message unset.
  1655. """
  1656. if not hms_errors:
  1657. return None
  1658. from backend.app.services.hms_errors import get_error_description
  1659. parts: list[str] = []
  1660. for err in hms_errors:
  1661. try:
  1662. # `_hms_short_code` rather than a local derivation: this one used to
  1663. # format the error without masking it to 16 bits, so an `hms[]` entry
  1664. # whose code carries an alert-level group produced a five-digit label
  1665. # like "0500_3000A" — not a code the user can look up, and never a
  1666. # catalogue key, so the sentence was lost with it.
  1667. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1668. except (TypeError, ValueError):
  1669. continue
  1670. description = err.get("description") or get_error_description(short_code)
  1671. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1672. # groups and is not a code anyone can look up; its full code in the
  1673. # printer screen's four groups is (#2728).
  1674. full_code = str(err.get("full_code") or "")
  1675. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1676. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1677. return "; ".join(parts) if parts else None
  1678. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1679. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1680. print completes successfully. Gated to status=='completed': failed, cancelled
  1681. and aborted prints do not count as usage. Caller is responsible for committing
  1682. the session. No-op when the queue item has no linked library file (e.g. reprints
  1683. from an archive). See #1008."""
  1684. if queue_status != "completed" or item.library_file_id is None:
  1685. return
  1686. from backend.app.models.library import LibraryFile
  1687. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1688. if lib_file is None:
  1689. return
  1690. lib_file.print_count = (lib_file.print_count or 0) + 1
  1691. lib_file.last_printed_at = datetime.now(timezone.utc)
  1692. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1693. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1694. When on_print_complete fires with status 'failed' for a printer in this set we
  1695. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1696. rather than a 'print failed' notification.
  1697. """
  1698. _user_stopped_printers.add(printer_id)
  1699. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1700. _last_status_broadcast: dict[int, str] = {}
  1701. # Track printers where we've updated nozzle_count
  1702. _nozzle_count_updated: set[int] = set()
  1703. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1704. """Wait the debounce window then fire `on_printer_offline` if the printer
  1705. is still offline.
  1706. Scheduled by `on_printer_status_change` on the connected → disconnected
  1707. edge (#1752). Cancelled by the same handler if the printer reconnects
  1708. before the window elapses, so a single MQTT blip + recovery doesn't
  1709. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1710. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1711. route through the same status-change callback, so this covers both.
  1712. """
  1713. logger = logging.getLogger(__name__)
  1714. try:
  1715. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1716. still_offline = not printer_manager.is_connected(printer_id)
  1717. logger.info(
  1718. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1719. printer_id,
  1720. still_offline,
  1721. )
  1722. if not still_offline:
  1723. return
  1724. async with async_session() as db:
  1725. from backend.app.models.printer import Printer
  1726. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1727. printer = result.scalar_one_or_none()
  1728. if not printer:
  1729. logger.warning(
  1730. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1731. printer_id,
  1732. )
  1733. return
  1734. # Recorded only when the relay can publish it, so the reconnect's
  1735. # online event always has an offline before it.
  1736. if mqtt_relay.enabled and mqtt_relay.connected:
  1737. _printer_offline_published.add(printer_id)
  1738. try:
  1739. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1740. except Exception as e:
  1741. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1742. logger.info(
  1743. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1744. printer_id,
  1745. printer.name,
  1746. )
  1747. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1748. except asyncio.CancelledError:
  1749. raise
  1750. except Exception as e:
  1751. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1752. finally:
  1753. _printer_offline_notify_tasks.pop(printer_id, None)
  1754. def _hms_notify_key(error) -> str:
  1755. """What identifies a fault for notification de-duplication.
  1756. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1757. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1758. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1759. and -0006 together) shared a key and only the first was ever notified. An
  1760. entry without a full code falls back to attr and code together.
  1761. """
  1762. full_code = getattr(error, "full_code", "") or ""
  1763. if full_code:
  1764. return full_code.upper()
  1765. return f"{error.attr:08X}:{error.code}"
  1766. def _hms_fault_counts(error) -> bool:
  1767. """Whether a fault counts as a problem: the same rule the frontend's
  1768. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1769. It counts when Bambu publishes text for it or it offers action buttons, and
  1770. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1771. no actions does not count: those are things like "the top cover is open" or
  1772. "the chamber is hot, fan speed increased", which a printer can hold through
  1773. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1774. it always has; those are prompts such as "unable to start drying" (#2728).
  1775. """
  1776. if error.severity < 1:
  1777. return False
  1778. has_actions = bool(getattr(error, "actions", None))
  1779. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1780. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1781. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1782. """The new faults that count (see ``_hms_fault_counts``).
  1783. These go to the MQTT relay; the caller also needs a description before it
  1784. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1785. used to read ``severity >= 2`` when severity held the part byte; on the real
  1786. level that would drop the task-stopping errors (#2728).
  1787. """
  1788. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1789. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1790. """The faults on this printer not notified yet, and record them as notified.
  1791. Tracking is updated before anything is sent, so concurrent status callbacks
  1792. cannot notify the same fault twice. A notified fault is forgotten once it
  1793. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1794. and on is notified once (#3226), while one that clears and comes back much
  1795. later is notified again.
  1796. When ``print_state`` changes (a print resumed, started or finished), every
  1797. fault recorded so far is forgotten the first time it is gone, without the
  1798. wait: a runout fixed before resuming must be notified if it happens again a
  1799. few minutes later, while the printer sits paused. Not only the faults gone
  1800. at the change itself, because the update that flips the state can still
  1801. carry the old fault (a ``print_error`` entry stays until a payload brings
  1802. ``hms``).
  1803. """
  1804. now = time.time()
  1805. current = {_hms_notify_key(e) for e in errors}
  1806. seen = _notified_hms_errors.setdefault(printer_id, {})
  1807. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1808. if print_state is not None:
  1809. print_state = print_state.upper()
  1810. if _hms_print_state.get(printer_id, print_state) != print_state:
  1811. forget_when_gone.update(seen)
  1812. _hms_print_state[printer_id] = print_state
  1813. for key, last_seen in list(seen.items()):
  1814. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1815. del seen[key]
  1816. forget_when_gone.discard(key)
  1817. new = current - seen.keys()
  1818. for key in current:
  1819. seen[key] = now
  1820. if not seen:
  1821. _notified_hms_errors.pop(printer_id, None)
  1822. if not forget_when_gone:
  1823. _hms_forget_when_gone.pop(printer_id, None)
  1824. return _hms_errors_to_notify(errors, new)
  1825. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1826. # "Printing", -1 and 255 are "no stage" (#3211).
  1827. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1828. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1829. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1830. Records it as notified. Called only for a printing state with progress above 0.
  1831. Progress before the first layer is not progress through the print (#3211).
  1832. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1833. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1834. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1835. 75% notification together with Print Started, and since 75 was then on
  1836. record, 25 and 50 could never fire. So nothing counts while the printer
  1837. reports a layer count but has not started layer 1.
  1838. Without a layer count -- a print whose first frame carried no
  1839. ``total_layer_num``, until the pushall that asks for it is answered
  1840. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1841. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1842. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1843. reports neither keeps the old behaviour rather than never notifying.
  1844. """
  1845. if (state.layer_num or 0) < 1:
  1846. if (state.total_layers or 0) > 0:
  1847. return None
  1848. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1849. return None
  1850. progress = state.progress or 0
  1851. current_milestone = 0
  1852. if progress >= 75:
  1853. current_milestone = 75
  1854. elif progress >= 50:
  1855. current_milestone = 50
  1856. elif progress >= 25:
  1857. current_milestone = 25
  1858. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1859. _last_progress_milestone[printer_id] = current_milestone
  1860. return current_milestone
  1861. return None
  1862. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1863. """Handle printer status changes - broadcast via WebSocket."""
  1864. try:
  1865. notify_live_activities.observe(printer_id, state)
  1866. except Exception:
  1867. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1868. try:
  1869. pause_eta.observe(printer_id, state)
  1870. except Exception:
  1871. logging.getLogger(__name__).exception("Pause heads-up check failed for printer %s", printer_id)
  1872. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1873. # transitions disconnected → connected — which covers both Bambuddy
  1874. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1875. # `reconcile_stale_active_prints` exactly once for this connection so
  1876. # any archive still in `status="printing"` that can't actually be
  1877. # running anymore (printer IDLE / different subtask / empty subtask)
  1878. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1879. # finished during a disconnect window + a smart-plug power cycle
  1880. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1881. # next boot. Reconciliation runs concurrently — it must not block the
  1882. # WebSocket dedup / broadcast logic below, and the connected edge is
  1883. # marked True BEFORE the await so concurrent status updates inside
  1884. # the same connection don't re-trigger reconciliation.
  1885. #
  1886. # Wait for a real push_status before reconciling (#1679): MQTT
  1887. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1888. # the connection, BEFORE `_request_push_all` round-trips. At that
  1889. # instant the `PrinterState` is still on construction defaults — most
  1890. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1891. # If reconcile spawns here, every in-flight archive falls through to
  1892. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1893. # creates a duplicate archive on the real PRINT COMPLETE and
  1894. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1895. # keeps the #1542 mechanism intact: once the first real push_status
  1896. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1897. # fires again with the flag still False — reconcile then runs against
  1898. # actual evidence.
  1899. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1900. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1901. _printer_reconciled_since_connect[printer_id] = True
  1902. spawn_background_task(
  1903. reconcile_stale_active_prints(printer_id),
  1904. name=f"reconcile-stale-prints-{printer_id}",
  1905. )
  1906. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1907. # Re-arm so the next reconnect triggers reconciliation again.
  1908. _printer_reconciled_since_connect[printer_id] = False
  1909. # Same edge, for the calibration table the AMS card reads its K values from.
  1910. #
  1911. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1912. # tables to ask for. A `state_known` gate alone is not enough: the first
  1913. # real push_status is what makes the state known, and the nozzle fields do
  1914. # not always arrive in it. Latching there would spend this connection's one
  1915. # attempt on a printer that could not yet say what was fitted.
  1916. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1917. if (
  1918. state.connected
  1919. and state_known
  1920. and nozzle_known
  1921. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1922. ):
  1923. _printer_kprofiles_primed_since_connect[printer_id] = True
  1924. spawn_background_task(
  1925. prime_kprofile_table(printer_id),
  1926. name=f"prime-kprofiles-{printer_id}",
  1927. )
  1928. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1929. _printer_kprofiles_primed_since_connect[printer_id] = False
  1930. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1931. # else in the AMS report changing -- a power cycle does it to every slot --
  1932. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1933. # while the printer is idle; needs_check is cheap and throttled per slot.
  1934. # Guarded: nothing here may stop the status broadcast below.
  1935. try:
  1936. if not state.connected:
  1937. kprofile_drift.forget_printer(printer_id)
  1938. elif kprofile_drift.needs_check(printer_id, state):
  1939. spawn_background_task(
  1940. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1941. name=f"reapply-kprofiles-{printer_id}",
  1942. )
  1943. except Exception:
  1944. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1945. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1946. # connected → disconnected. The "back online" channel is already covered
  1947. # by the print-failure notification (firmware reports gcode_state=FAILED
  1948. # on reconnect of an interrupted print), so there is no online
  1949. # notification. The MQTT relay gets both: offline after the debounce, and
  1950. # online on the reconnect that follows a published offline.
  1951. prev_connected = _printer_last_connected.get(printer_id)
  1952. _printer_last_connected[printer_id] = state.connected
  1953. if prev_connected is True and not state.connected:
  1954. existing = _printer_offline_notify_tasks.get(printer_id)
  1955. if existing is None or existing.done():
  1956. logging.getLogger(__name__).info(
  1957. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1958. printer_id,
  1959. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1960. )
  1961. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1962. _maybe_notify_printer_offline(printer_id),
  1963. name=f"printer-offline-notify-{printer_id}",
  1964. )
  1965. elif state.connected:
  1966. # Kept until the relay can actually send online: with its broker down
  1967. # now, the next status update after the reconnect sends it.
  1968. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1969. _printer_offline_published.discard(printer_id)
  1970. printer_info = printer_manager.get_printer(printer_id)
  1971. if printer_info:
  1972. try:
  1973. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1974. except Exception as e:
  1975. logging.getLogger(__name__).warning(
  1976. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1977. )
  1978. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1979. if pending is not None and not pending.done():
  1980. logging.getLogger(__name__).info(
  1981. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1982. printer_id,
  1983. )
  1984. pending.cancel()
  1985. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1986. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1987. temps = state.temperatures or {}
  1988. nozzle_temp = round(temps.get("nozzle", 0))
  1989. bed_temp = round(temps.get("bed", 0))
  1990. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1991. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1992. # Auto-detect dual-nozzle printers from MQTT temperature data
  1993. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1994. _nozzle_count_updated.add(printer_id)
  1995. # Update nozzle_count in database
  1996. async with async_session() as db:
  1997. from backend.app.models.printer import Printer
  1998. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1999. printer = result.scalar_one_or_none()
  2000. if printer and printer.nozzle_count != 2:
  2001. printer.nozzle_count = 2
  2002. await db.commit()
  2003. logging.getLogger(__name__).info(
  2004. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  2005. )
  2006. # Include target temps for heating phase detection
  2007. bed_target = round(temps.get("bed_target", 0))
  2008. nozzle_target = round(temps.get("nozzle_target", 0))
  2009. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  2010. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  2011. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  2012. #
  2013. # dry_countdown_stalled rides along because it is the one drying signal the
  2014. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  2015. # dry_time stopped moving, so on the frame that flips it every other member
  2016. # of this key is identical and the push would be deduplicated away. Mid-print
  2017. # a temperature would eventually break the tie, but a parked command on an
  2018. # idle machine changes nothing else at all — AMS temp and humidity are not in
  2019. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  2020. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  2021. ams_dry_key = (
  2022. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  2023. if state.raw_data
  2024. else ()
  2025. )
  2026. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  2027. #
  2028. # The filament identity fields are here because Configure Slot writes
  2029. # exactly those and nothing else. Re-configuring a slot from PLA to another
  2030. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  2031. # matched, this function returned before broadcasting, and the card kept
  2032. # showing the old filament until the 30s fallback poll or a page reload —
  2033. # even though the configure route asks the printer for a fresh pushall and
  2034. # that push does carry the new values. Reset always worked, because it
  2035. # clears tray_type.
  2036. #
  2037. # These fields only change when someone configures a slot or swaps a spool,
  2038. # so unlike temperature or progress they add no broadcast traffic mid-print.
  2039. ams_tray_key = (
  2040. tuple(
  2041. (
  2042. t.get("id"),
  2043. t.get("tray_type", ""),
  2044. t.get("state"),
  2045. t.get("tray_color", ""),
  2046. t.get("tray_info_idx", ""),
  2047. t.get("tray_sub_brands", ""),
  2048. t.get("cali_idx"),
  2049. )
  2050. for a in (state.raw_data.get("ams") or [])
  2051. for t in a.get("tray", [])
  2052. )
  2053. if state.raw_data
  2054. else ()
  2055. )
  2056. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  2057. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  2058. # in the AMS change-hash (tray fields only, and widening that would fire
  2059. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  2060. # screen changed no key at all and the card's inlet badges sat stale until a
  2061. # reload. Like the filament-backup flag, these only move when someone
  2062. # reconfigures the machine, so they add no mid-print broadcast traffic.
  2063. fts_key = (
  2064. state.fila_switch.installed if state.fila_switch else False,
  2065. tuple(sorted(state.ams_switch_inlet.items())),
  2066. # Which hotend holds which slot. Unlike the two above this does move
  2067. # mid-print, on every filament change — but only between discrete slots,
  2068. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  2069. # it live: it decides which hotend the Load dialog may offer and whether
  2070. # Unload has anything to act on.
  2071. tuple(
  2072. sorted(
  2073. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  2074. # Sort on the extruder id alone: the other members are nullable
  2075. # and comparing None with an int raises.
  2076. key=lambda entry: entry[0],
  2077. )
  2078. ),
  2079. )
  2080. status_key = (
  2081. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  2082. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  2083. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  2084. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  2085. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  2086. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  2087. )
  2088. # Fields that change only when the machine does (a nozzle swap, a firmware
  2089. # update, developer mode) or once per print (its AMS mapping): no traffic,
  2090. # but on an idle printer nothing else moves the key when they change.
  2091. machine_key = (
  2092. tuple((n.nozzle_type, n.nozzle_diameter) for n in (state.nozzles or [])),
  2093. state.firmware_version,
  2094. state.developer_mode,
  2095. tuple(state.print_ams_mapping) if isinstance(state.print_ams_mapping, list) else None,
  2096. # Cooling/heating, switched on the printer's screen too: on an idle
  2097. # printer nothing else moves the key (PSF-4).
  2098. state.airduct_mode,
  2099. )
  2100. status_key = f"{status_key}:{machine_key}"
  2101. is_active_print = state.state in _ACTIVE_PRINT_STATES
  2102. if not is_active_print:
  2103. _unauthorized_print_kill_sent.discard(printer_id)
  2104. elif printer_id in _unauthorized_print_kill_sent:
  2105. # stop_print() was already sent for this print; avoid all further
  2106. # ownership and settings work until the printer leaves an active state.
  2107. pass
  2108. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  2109. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  2110. _unauthorized_print_kill_sent.discard(printer_id)
  2111. else:
  2112. kill_switch_enabled = False
  2113. authorization: bool | None = None
  2114. status_logger = logging.getLogger(__name__)
  2115. try:
  2116. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  2117. if kill_switch_enabled:
  2118. async with async_session() as db:
  2119. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  2120. except Exception as e:
  2121. # Fail safe: a database/reconciliation error must never turn into an
  2122. # irreversible stop of a print whose ownership is still unknown.
  2123. authorization = None
  2124. status_logger.warning(
  2125. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  2126. )
  2127. if not kill_switch_enabled or authorization is True:
  2128. _unauthorized_print_kill_sent.discard(printer_id)
  2129. elif authorization is None:
  2130. _unauthorized_print_kill_sent.discard(printer_id)
  2131. status_logger.debug(
  2132. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  2133. printer_id,
  2134. )
  2135. else:
  2136. try:
  2137. stopped = printer_manager.stop_print(printer_id)
  2138. if stopped:
  2139. _unauthorized_print_kill_sent.add(printer_id)
  2140. _kill_switch_stopped.add(printer_id)
  2141. printer_info = printer_manager.get_printer(printer_id)
  2142. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  2143. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  2144. notification_data = {
  2145. "status": "stopped",
  2146. "filename": state.gcode_file or state.current_print or "",
  2147. "subtask_name": state.subtask_name or "",
  2148. "progress": state.progress,
  2149. "reason": "unauthorized_print",
  2150. }
  2151. status_logger.warning(
  2152. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  2153. printer_id,
  2154. state.state,
  2155. )
  2156. try:
  2157. await ws_manager.broadcast(
  2158. {
  2159. "type": "kill_switch_triggered",
  2160. "printer_id": printer_id,
  2161. "printer_name": printer_name,
  2162. "filename": filename,
  2163. "reason": "unauthorized_print",
  2164. }
  2165. )
  2166. except Exception as e:
  2167. status_logger.warning(
  2168. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  2169. )
  2170. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  2171. if previous_task is not None and not previous_task.done():
  2172. previous_task.cancel()
  2173. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  2174. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  2175. name=f"kill-switch-notification-{printer_id}",
  2176. )
  2177. else:
  2178. status_logger.warning(
  2179. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  2180. printer_id,
  2181. state.state,
  2182. )
  2183. except Exception as e:
  2184. status_logger.warning(
  2185. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  2186. )
  2187. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  2188. try:
  2189. printer_info = printer_manager.get_printer(printer_id)
  2190. if printer_info:
  2191. await mqtt_relay.on_printer_status(
  2192. printer_id,
  2193. state,
  2194. printer_info.name,
  2195. printer_info.serial_number,
  2196. printer_manager.is_awaiting_plate_clear(printer_id),
  2197. )
  2198. except Exception:
  2199. pass # Don't fail status callback if MQTT fails
  2200. if _last_status_broadcast.get(printer_id) == status_key:
  2201. return # No change, skip WebSocket broadcast
  2202. _last_status_broadcast[printer_id] = status_key
  2203. # Check for progress milestone notifications (25%, 50%, 75%)
  2204. progress = state.progress or 0
  2205. is_printing = state.state in ("RUNNING", "PRINTING")
  2206. if is_printing and progress > 0:
  2207. current_milestone = _progress_milestone_to_notify(printer_id, state)
  2208. if current_milestone is not None:
  2209. try:
  2210. from backend.app.models.printer import Printer
  2211. # Read the printer in a short session and release the connection
  2212. # BEFORE the ~15s camera snapshot below — holding it across the grab
  2213. # pinned a pooled connection per milestone, per printer (issue #2572).
  2214. async with async_session() as db:
  2215. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2216. printer = result.scalar_one_or_none()
  2217. printer_name = printer.name if printer else f"Printer {printer_id}"
  2218. filename = state.subtask_name or state.gcode_file or "Unknown"
  2219. # remaining_time is in minutes, convert to seconds for notification
  2220. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  2221. # Capture camera snapshot for notification image attachment (no DB held).
  2222. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  2223. # Notification send needs a session (provider/template lookups).
  2224. async with async_session() as db:
  2225. await notification_service.on_print_progress(
  2226. printer_id,
  2227. printer_name,
  2228. filename,
  2229. current_milestone,
  2230. db,
  2231. remaining_time_seconds,
  2232. image_data=image_data,
  2233. )
  2234. except Exception as e:
  2235. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  2236. elif progress < 5:
  2237. # Reset milestone tracking when print restarts or new print begins
  2238. _last_progress_milestone[printer_id] = 0
  2239. _first_layer_notified[printer_id] = False
  2240. # HMS error codes that should not trigger notifications even though they
  2241. # have known descriptions (e.g. user-initiated actions, not real errors).
  2242. _HMS_NOTIFICATION_SUPPRESS = {
  2243. "0500_400E", # Printing was cancelled (user action, not an error)
  2244. }
  2245. # Check for new HMS errors and send notifications
  2246. current_hms_errors = getattr(state, "hms_errors", []) or []
  2247. if current_hms_errors:
  2248. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  2249. if new_errors:
  2250. try:
  2251. from backend.app.models.printer import Printer
  2252. # Read the printer in a short session and release the connection
  2253. # BEFORE the ~15s camera snapshot below (issue #2572).
  2254. async with async_session() as db:
  2255. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2256. printer = result.scalar_one_or_none()
  2257. printer_name = printer.name if printer else f"Printer {printer_id}"
  2258. # Format error details for notification
  2259. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  2260. module_names = {
  2261. 0x03: "Print/Task",
  2262. 0x05: "Nozzle/Extruder",
  2263. 0x07: "AMS/Filament",
  2264. 0x0C: "Motion Controller",
  2265. 0x12: "Chamber",
  2266. }
  2267. # Capture camera snapshot once for all error notifications (no DB held).
  2268. error_image_data = await _capture_snapshot_for_notification(
  2269. printer_id, printer, logging.getLogger(__name__)
  2270. )
  2271. # Notification sends need a session (provider/template lookups).
  2272. async with async_session() as db:
  2273. sent_count = 0
  2274. for error in new_errors:
  2275. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  2276. # Build short code like "0700_8010"
  2277. # Mask to 16 bits to handle printers that send larger values
  2278. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  2279. error_code_masked = error_code_int & 0xFFFF
  2280. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  2281. # Only notify for errors Bambu publishes text for — printers
  2282. # send undocumented codes that aren't real errors, and Bambu
  2283. # lists some with empty text. Resolved at parse time (#2926);
  2284. # short_code is still needed for the suppression set below.
  2285. description = error.description
  2286. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  2287. continue
  2288. error_type = f"{module_name} Error"
  2289. error_detail = description
  2290. await notification_service.on_printer_error(
  2291. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  2292. )
  2293. sent_count += 1
  2294. if sent_count:
  2295. logging.getLogger(__name__).info(
  2296. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  2297. )
  2298. # Also publish to MQTT relay (no DB): every new fault that
  2299. # counts, with or without text, the same set the UI counts.
  2300. printer_info = printer_manager.get_printer(printer_id)
  2301. if printer_info:
  2302. errors_data = [
  2303. {
  2304. "code": e.code,
  2305. "attr": e.attr,
  2306. "module": e.module,
  2307. "severity": e.severity,
  2308. }
  2309. for e in new_errors
  2310. ]
  2311. await mqtt_relay.on_printer_error(
  2312. printer_id, printer_info.name, printer_info.serial_number, errors_data
  2313. )
  2314. except Exception as e:
  2315. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  2316. else:
  2317. # No HMS errors: nothing to send, but faults gone long enough (or gone
  2318. # across a print state change) are forgotten. Some codes, e.g. chamber
  2319. # temperature regulation during PETG prints, toggle every few seconds.
  2320. _take_new_hms_faults(printer_id, [], state.state)
  2321. await ws_manager.send_printer_status(
  2322. printer_id,
  2323. printer_state_to_dict(
  2324. state,
  2325. printer_id,
  2326. printer_manager.get_model(printer_id),
  2327. printer_manager.get_drying_targets(printer_id),
  2328. ),
  2329. )
  2330. def _is_bambu_uuid(tray_uuid: str) -> bool:
  2331. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  2332. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  2333. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  2334. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  2335. K-profiles are per-nozzle and the printer's calibration table is numbered
  2336. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  2337. switch's other inlet therefore silently invalidates every configured slot in
  2338. it: the index stays put and now resolves against the other nozzle's table.
  2339. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  2340. and 0.020 on the right kept the left profile after the move, and a manual
  2341. RFID re-read only re-asserted the same wrong one.
  2342. Configuring a slot is a deliberate preparation step, so this re-selects
  2343. rather than re-configures: only the calibration binding moves, and only for
  2344. slots whose spool already has a stored profile for the new nozzle. A slot
  2345. Bambuddy knows nothing about is left exactly as the operator left it.
  2346. """
  2347. logger = logging.getLogger(__name__)
  2348. target_extruder = extruder_for_inlet(inlet)
  2349. if target_extruder is None:
  2350. return
  2351. client = printer_manager.get_client(printer_id)
  2352. state = printer_manager.get_status(printer_id)
  2353. if not client or not state or not state.raw_data:
  2354. return
  2355. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  2356. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  2357. # the nozzle width, which changes both the K profile to select and the
  2358. # preset the slot should carry.
  2359. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  2360. ams_raw = state.raw_data.get("ams")
  2361. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2362. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  2363. if not unit:
  2364. return
  2365. try:
  2366. async with async_session() as db:
  2367. for tray in unit.get("tray", []):
  2368. tray_id = int(tray.get("id", -1))
  2369. if tray_id < 0 or not tray.get("tray_type"):
  2370. continue
  2371. current_idx = tray.get("cali_idx")
  2372. profile = await find_slot_kprofile_for_extruder(
  2373. db,
  2374. printer_id,
  2375. ams_id,
  2376. tray_id,
  2377. target_extruder,
  2378. nozzle_diameter,
  2379. printer_manager.get_model(printer_id),
  2380. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2381. )
  2382. if profile is None or profile.cali_idx is None:
  2383. continue
  2384. if current_idx == profile.cali_idx:
  2385. continue # Already on the right one.
  2386. logger.info(
  2387. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2388. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2389. printer_id,
  2390. ams_id,
  2391. tray_id,
  2392. inlet,
  2393. target_extruder,
  2394. profile.name,
  2395. current_idx,
  2396. profile.cali_idx,
  2397. profile.k_value,
  2398. )
  2399. client.extrusion_cali_sel(
  2400. ams_id=ams_id,
  2401. tray_id=tray_id,
  2402. cali_idx=profile.cali_idx,
  2403. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2404. nozzle_diameter=nozzle_diameter,
  2405. )
  2406. except Exception as e:
  2407. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2408. def _slot_feeds_print(printer_id: int, ams_id: int, tray_id: int) -> bool:
  2409. """Is this slot the one feeding the printer right now?
  2410. ``tray_now`` names one slot for the whole printer, so on a dual-nozzle
  2411. machine each extruder's own fed slot is asked as well. Only meaningful
  2412. while a print runs; the caller checks that.
  2413. """
  2414. status = printer_manager.get_status(printer_id)
  2415. if status is None:
  2416. return False
  2417. if ams_id == 255:
  2418. global_id = 254 + tray_id
  2419. elif ams_id >= 128:
  2420. global_id = ams_id
  2421. else:
  2422. global_id = ams_id * 4 + tray_id
  2423. if getattr(status, "tray_now", None) == global_id:
  2424. return True
  2425. slots = getattr(status, "extruder_slots", None) or {}
  2426. return any(slot.has_filament and slot.holds(ams_id, tray_id) for slot in slots.values())
  2427. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2428. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2429. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2430. from the delayed re-check -- which is why it takes the AMS data and print
  2431. state as arguments instead of reading them from the push (#3186).
  2432. """
  2433. logger = logging.getLogger(__name__)
  2434. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2435. # Auto-unlink spool assignments with stale fingerprints. Under the
  2436. # per-printer assignment lock since #3186: the held-removal re-check runs
  2437. # this outside any MQTT push, so it can now overlap one.
  2438. try:
  2439. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2440. from sqlalchemy.orm import selectinload
  2441. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2442. from backend.app.models.spool import Spool as _Spool
  2443. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2444. from backend.app.services.ams_slot_presence import spool_present
  2445. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2446. # Built-in assignments only. Since #2812 they survive a switch to
  2447. # Spoolman mode rather than being deleted by it, and this pass ends
  2448. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2449. # time as the AMS contents changed under the other mode, undoing the
  2450. # preservation more slowly but just as completely.
  2451. assignments = []
  2452. if not await spoolman_owns_assignments(db):
  2453. result = await db.execute(
  2454. select(SA)
  2455. .where(SA.printer_id == printer_id)
  2456. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2457. )
  2458. assignments = result.scalars().all()
  2459. # ``printing_now`` (top of this function) keeps a runout from
  2460. # unlinking the spool that fed the print — the next idle-time pass
  2461. # unlinks it if the user really did take it out.
  2462. stale = []
  2463. # Removals this pass is holding rather than unlinking (#3186).
  2464. held: set[tuple] = set()
  2465. for assignment in assignments:
  2466. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2467. if assignment.ams_id == 255:
  2468. ps = printer_manager.get_status(printer_id)
  2469. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2470. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  2471. current_tray = None
  2472. for vt in vt_tray_raw:
  2473. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2474. current_tray = vt
  2475. break
  2476. if not current_tray:
  2477. # vt_tray data may not have arrived yet — keep assignment
  2478. continue
  2479. else:
  2480. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2481. if not current_tray:
  2482. if printing_now:
  2483. logger.info(
  2484. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2485. assignment.spool_id,
  2486. assignment.ams_id,
  2487. assignment.tray_id,
  2488. )
  2489. continue
  2490. # A whole AMS unit can drop out of one push and come back in
  2491. # the next; only a slot that stays gone is a removal (#3186).
  2492. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2493. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2494. held.add(hold_key)
  2495. logger.info(
  2496. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2497. "unlinking if it is still gone in %ds",
  2498. assignment.spool_id,
  2499. assignment.ams_id,
  2500. assignment.tray_id,
  2501. int(slot_unlink_grace.GRACE_SECONDS),
  2502. )
  2503. continue
  2504. logger.info(
  2505. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2506. assignment.spool_id,
  2507. assignment.ams_id,
  2508. assignment.tray_id,
  2509. )
  2510. stale.append(assignment) # Slot empty
  2511. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2512. # A Bambu Lab spool is in this slot — check if it's the same spool
  2513. # that's currently assigned. If yes, keep the assignment (avoids
  2514. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2515. # the printer's filament preset on every startup).
  2516. tray_uuid = current_tray.get("tray_uuid", "")
  2517. tag_uid = current_tray.get("tag_uid", "")
  2518. spool = assignment.spool
  2519. spool_matches = False
  2520. if spool:
  2521. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2522. spool.tag_uid
  2523. and tag_uid
  2524. and tag_uid != "0000000000000000"
  2525. and spool.tag_uid.upper() == tag_uid.upper()
  2526. ):
  2527. spool_matches = True
  2528. if spool_matches:
  2529. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2530. cur_color = current_tray.get("tray_color", "")
  2531. cur_type = current_tray.get("tray_type", "")
  2532. fp_color = assignment.fingerprint_color or ""
  2533. fp_type = assignment.fingerprint_type or ""
  2534. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2535. assignment.fingerprint_color = cur_color
  2536. assignment.fingerprint_type = cur_type
  2537. logger.debug(
  2538. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2539. assignment.spool_id,
  2540. assignment.ams_id,
  2541. assignment.tray_id,
  2542. )
  2543. continue
  2544. # Different BL spool or unrecognized — unlink so auto-assign can match
  2545. logger.info(
  2546. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2547. assignment.spool_id,
  2548. assignment.ams_id,
  2549. assignment.tray_id,
  2550. tray_uuid,
  2551. )
  2552. stale.append(assignment)
  2553. else:
  2554. cur_color = current_tray.get("tray_color", "")
  2555. cur_type = current_tray.get("tray_type", "")
  2556. cur_state = current_tray.get("state")
  2557. fp_color = assignment.fingerprint_color or ""
  2558. fp_type = assignment.fingerprint_type or ""
  2559. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2560. # the slot was empty when the user pre-assigned via SpoolBuddy
  2561. # (the firmware drops ams_filament_setting on empty slots, so
  2562. # MQTT was deferred). The moment any filament gets inserted
  2563. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2564. # reconfigured spool — fire the deferred configuration.
  2565. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2566. # extruder" code) OR, on firmwares that don't use the state
  2567. # enum meaningfully, a non-empty tray_type when state is
  2568. # NOT one of the firmware's explicit empty signals (9, 10).
  2569. # state-only was wrong for firmwares that never set 11 — A1
  2570. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2571. # always report state=3 — so the replay never fired for them
  2572. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2573. # explicit "empty" signals authoritative over any stale
  2574. # tray_type that might survive the relay's auto-clearing.
  2575. #
  2576. # tray_exist_bits comes first because that guard cannot tell
  2577. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2578. # writes state=9 when the bit is 0 and leaves it there when the
  2579. # bit returns. A non-RFID spool inserted into a pre-assigned
  2580. # slot brings no tray_type with it, so the stale 9 made this
  2581. # expression false forever and the deferred config never fired
  2582. # — the deadlock #1322 removed from the assign path, still in
  2583. # place here (#3084, #3100).
  2584. loaded = spool_present(current_tray) is True or (
  2585. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2586. )
  2587. # Not into the slot feeding a running print: the printer refuses
  2588. # the setting for it (``ams_filament_setting refused``), and a
  2589. # spool swapped in after a runout sat through one refused send
  2590. # per AMS change. Held, it fires on the first change once the
  2591. # print is over (#3434).
  2592. if (
  2593. not fp_type.strip()
  2594. and loaded
  2595. and assignment.spool
  2596. and printing_now
  2597. and _slot_feeds_print(printer_id, assignment.ams_id, assignment.tray_id)
  2598. ):
  2599. logger.debug(
  2600. "Pre-config held for spool %d AMS%d-T%d: the slot is feeding the print",
  2601. assignment.spool_id,
  2602. assignment.ams_id,
  2603. assignment.tray_id,
  2604. )
  2605. continue
  2606. if not fp_type.strip() and loaded and assignment.spool:
  2607. # The fingerprint ends this replay. Not recorded when nothing
  2608. # could be sent (no MQTT client while the printer reconnects),
  2609. # so the next AMS change tries again. An attempt that raised is
  2610. # recorded as before: it may have sent part of the commands and
  2611. # would raise again on every change, remain% steps included.
  2612. configured: bool | None = False
  2613. try:
  2614. from backend.app.api.routes.inventory import (
  2615. apply_spool_to_slot_via_mqtt,
  2616. )
  2617. configured = await apply_spool_to_slot_via_mqtt(
  2618. db=db,
  2619. current_user=None,
  2620. spool=assignment.spool,
  2621. printer_id=printer_id,
  2622. ams_id=assignment.ams_id,
  2623. tray_id=assignment.tray_id,
  2624. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2625. current_tray_type=cur_type,
  2626. current_tray_sub_brands=current_tray.get("tray_sub_brands", ""),
  2627. )
  2628. except Exception:
  2629. logger.exception(
  2630. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2631. assignment.spool_id,
  2632. printer_id,
  2633. assignment.ams_id,
  2634. assignment.tray_id,
  2635. )
  2636. configured = None
  2637. if configured is False:
  2638. logger.warning(
  2639. "Pre-config not sent for spool %d on printer %d AMS%d-T%d (no MQTT client); "
  2640. "retrying on the next AMS change",
  2641. assignment.spool_id,
  2642. printer_id,
  2643. assignment.ams_id,
  2644. assignment.tray_id,
  2645. )
  2646. else:
  2647. if configured:
  2648. logger.info(
  2649. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2650. assignment.spool_id,
  2651. printer_id,
  2652. assignment.ams_id,
  2653. assignment.tray_id,
  2654. )
  2655. assignment.fingerprint_color = cur_color
  2656. assignment.fingerprint_type = cur_type
  2657. continue
  2658. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2659. # Blank tray data mid-print is a runout, not a swap: the
  2660. # firmware clears colour and type when it unloads a spool
  2661. # it just emptied. Unlinking here would erase the record
  2662. # of which spool fed the print so far.
  2663. if printing_now and not cur_color.strip() and not cur_type.strip():
  2664. logger.info(
  2665. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2666. "(runout?)",
  2667. assignment.spool_id,
  2668. assignment.ams_id,
  2669. assignment.tray_id,
  2670. )
  2671. continue
  2672. # Same reasoning off the print, on firmware's own say-so:
  2673. # a blank tray report from a slot whose tray_exist_bits
  2674. # bit is set describes a spool the AMS cannot identify —
  2675. # a non-RFID one, or one whose slot was reset — not a
  2676. # spool that was taken out. Deleting the assignment there
  2677. # threw away the identity the user had supplied, which is
  2678. # the only place it existed (#3100). A slot the bit calls
  2679. # empty, or one that carries no bit at all, still unlinks.
  2680. #
  2681. # Unless the slot was reported empty first: a removal
  2682. # already held means a spool came out and another went
  2683. # in, so the blank report keeps the hold running below
  2684. # rather than cancelling it (#3186).
  2685. if (
  2686. spool_present(current_tray) is True
  2687. and not cur_color.strip()
  2688. and not cur_type.strip()
  2689. and not slot_unlink_grace.is_held(
  2690. printer_id,
  2691. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2692. )
  2693. ):
  2694. logger.info(
  2695. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2696. "tray reports no filament data yet",
  2697. assignment.spool_id,
  2698. assignment.ams_id,
  2699. assignment.tray_id,
  2700. )
  2701. continue
  2702. # A blank report the presence bit does not vouch for is
  2703. # still only one push. An idle X1C cleared a whole AMS
  2704. # unit's bits, colour and type for a moment and lost
  2705. # four saved assignments that way (#3186); unlink only
  2706. # if the slot is still blank after the grace period.
  2707. if not cur_color.strip() and not cur_type.strip():
  2708. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2709. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2710. held.add(hold_key)
  2711. logger.info(
  2712. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2713. "unlinking if it is still blank in %ds",
  2714. assignment.spool_id,
  2715. assignment.ams_id,
  2716. assignment.tray_id,
  2717. int(slot_unlink_grace.GRACE_SECONDS),
  2718. )
  2719. continue
  2720. # Fingerprint mismatch — but check if tray now matches the
  2721. # assigned spool (e.g. auto-configure changed the tray).
  2722. # Both sides are reduced to the type the slot can carry
  2723. # before comparing: the assign path writes that rather
  2724. # than the spool's raw material (#2902), so a spool whose
  2725. # material is a product line — "PLA+", "HTPLA" — reports
  2726. # back as "PLA" and would otherwise fail this check and
  2727. # be auto-unlinked from the slot it was just assigned to.
  2728. # Reducing the printer's side too keeps slots configured
  2729. # by an older Bambuddy, still reporting "PLA+", matching.
  2730. spool = assignment.spool
  2731. if spool:
  2732. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2733. # Two ways the assign path can have arrived at the
  2734. # slot's type, so both count as "we wrote this".
  2735. # The material column is one; the spool's preset is
  2736. # the other, and it outranks the material when the
  2737. # spool has one -- a spool whose material says PLA
  2738. # and whose preset is "Bambu PLA Aero" puts
  2739. # PLA-AERO in the slot (#2902). Read from the stored
  2740. # preset name rather than resolving the preset,
  2741. # because this runs on every AMS push and a cloud
  2742. # lookup here would be both slow and unavailable on
  2743. # the unauthenticated replay path.
  2744. spool_types = {printer_filament_type(spool.material).upper()}
  2745. if spool.slicer_filament_name:
  2746. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2747. # An imported local preset stores its type outright,
  2748. # which is what the assign path used -- and the name
  2749. # above may be unset. One keyed read, and only on a
  2750. # mismatch, which is rare.
  2751. #
  2752. # slicer_filament is free text up to fifty characters,
  2753. # so the digits have to be checked against the range
  2754. # of the integer primary key they are about to be
  2755. # compared with. Postgres raises on an out-of-range
  2756. # integer rather than simply not matching, and that
  2757. # would poison this session and abandon the rest of
  2758. # the cleanup pass.
  2759. lp_ref = (spool.slicer_filament or "").strip()
  2760. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2761. from backend.app.models.local_preset import LocalPreset as _LP
  2762. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2763. if lp_type:
  2764. spool_types.add(printer_filament_type(lp_type).upper())
  2765. if (
  2766. _colors_similar(cur_color, spool_color)
  2767. and printer_filament_type(cur_type).upper() in spool_types
  2768. ):
  2769. logger.info(
  2770. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2771. assignment.spool_id,
  2772. assignment.ams_id,
  2773. assignment.tray_id,
  2774. )
  2775. assignment.fingerprint_color = cur_color
  2776. assignment.fingerprint_type = cur_type
  2777. continue
  2778. logger.info(
  2779. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2780. assignment.spool_id,
  2781. assignment.ams_id,
  2782. assignment.tray_id,
  2783. cur_color,
  2784. cur_type,
  2785. fp_color,
  2786. fp_type,
  2787. spool.rgba if spool else "?",
  2788. spool.material if spool else "?",
  2789. )
  2790. stale.append(assignment) # Spool changed
  2791. slot_unlink_grace.settle(printer_id, "inventory", held)
  2792. # Snapshot slots before delete — ORM attribute access after the
  2793. # commit would refresh against a deleted row.
  2794. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2795. for a in stale:
  2796. await db.delete(a)
  2797. if stale:
  2798. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2799. # Commit any changes (stale deletions and/or fingerprint updates)
  2800. await db.commit()
  2801. # Tell open browsers the assignment is gone (#2575). Only the manual
  2802. # REST assign/unassign endpoints broadcast this event; without it the
  2803. # frontend's spool-assignments cache keeps rendering the unlinked
  2804. # spool on the slot until an unrelated refetch — which reads exactly
  2805. # like "the fix didn't work" (reporter verified: a browser refresh
  2806. # after the swap showed the correct state all along).
  2807. for ams_id, tray_id in unlinked_slots:
  2808. await ws_manager.broadcast(
  2809. {
  2810. "type": "spool_assignment_changed",
  2811. "printer_id": printer_id,
  2812. "ams_id": ams_id,
  2813. "tray_id": tray_id,
  2814. }
  2815. )
  2816. except Exception as e:
  2817. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2818. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2819. """Delete Spoolman slot rows whose held removal has run its grace period.
  2820. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2821. talks to Spoolman for every tray; this only needs the local rows, so it
  2822. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2823. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2824. not in a slot the presence bit calls occupied -- and nothing else.
  2825. """
  2826. logger = logging.getLogger(__name__)
  2827. try:
  2828. async with async_session() as db:
  2829. from backend.app.api.routes.settings import get_setting
  2830. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2831. from backend.app.services.ams_slot_presence import spool_present
  2832. enabled = await get_setting(db, "spoolman_enabled")
  2833. if not enabled or enabled.lower() != "true":
  2834. return
  2835. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2836. if sync_mode and sync_mode != "auto":
  2837. return
  2838. trays: dict[tuple[int, int], dict] = {}
  2839. for ams_unit in ams_data or []:
  2840. if not isinstance(ams_unit, dict):
  2841. continue
  2842. for tray in ams_unit.get("tray", []):
  2843. if isinstance(tray, dict):
  2844. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2845. rows = (
  2846. (
  2847. await db.execute(
  2848. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2849. )
  2850. )
  2851. .scalars()
  2852. .all()
  2853. )
  2854. held: set[tuple] = set()
  2855. expired: list[tuple[int, int]] = []
  2856. for row in rows:
  2857. tray = trays.get((row.ams_id, row.tray_id))
  2858. if tray is None or printing_now:
  2859. continue
  2860. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2861. continue
  2862. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2863. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2864. continue
  2865. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2866. expired.append((row.ams_id, row.tray_id))
  2867. else:
  2868. held.add(hold_key)
  2869. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2870. if not expired:
  2871. return
  2872. # A statement rather than ORM deletes, like the sync pass: the two
  2873. # can overlap, and a row the other already removed must not fail
  2874. # this commit.
  2875. for ams_id, tray_id in expired:
  2876. await db.execute(
  2877. delete(SpoolmanSlotAssignment).where(
  2878. SpoolmanSlotAssignment.printer_id == printer_id,
  2879. SpoolmanSlotAssignment.ams_id == ams_id,
  2880. SpoolmanSlotAssignment.tray_id == tray_id,
  2881. )
  2882. )
  2883. await db.commit()
  2884. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2885. for ams_id, tray_id in expired:
  2886. await ws_manager.broadcast(
  2887. {
  2888. "type": "spool_assignment_changed",
  2889. "printer_id": printer_id,
  2890. "ams_id": ams_id,
  2891. "tray_id": tray_id,
  2892. }
  2893. )
  2894. except Exception as e:
  2895. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2896. async def _recheck_held_unlinks(printer_id: int) -> None:
  2897. """Re-run just the slot cleanup against the printer's current AMS state.
  2898. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2899. passes otherwise run only when the AMS hash changes, and a slot that went
  2900. empty and stayed empty may never change it again.
  2901. """
  2902. status = printer_manager.get_status(printer_id)
  2903. # A disconnected printer's state is its last report, not a new one: acting
  2904. # on it would "confirm" a removal nobody has seen for the whole grace
  2905. # period. Leave the holds; the first push after reconnecting decides.
  2906. if status is None or not status.connected:
  2907. return
  2908. ams_raw = status.raw_data.get("ams")
  2909. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2910. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2911. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2912. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2913. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2914. async def on_ams_change(printer_id: int, ams_data: list):
  2915. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2916. logger = logging.getLogger(__name__)
  2917. # Snapshot BEFORE any await: if a print is active, or a finished one is
  2918. # still being charged, skip weight sync later. on_print_complete may pop
  2919. # _active_sessions during our awaits (#880).
  2920. from backend.app.services.usage_tracker import printer_is_charging
  2921. _print_active = printer_is_charging(printer_id)
  2922. # A slot that reports empty while a print is running is a filament runout,
  2923. # not a spool swap: the spool is still physically in the AMS, just
  2924. # consumed. Dropping either inventory backend's slot link there loses the
  2925. # only record of which spool fed the print, so the completion path can't
  2926. # charge the runout segment to anything. Both cleanup passes below consult
  2927. # this; computed once, up front, so neither depends on the other having run.
  2928. _unlink_state = printer_manager.get_status(printer_id)
  2929. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2930. # The session alone is not enough: a restart that finds a stale persisted
  2931. # session registers none for the print that is running.
  2932. _print_active = _print_active or printing_now
  2933. # MQTT relay - publish AMS change
  2934. try:
  2935. printer_info = printer_manager.get_printer(printer_id)
  2936. if printer_info:
  2937. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2938. except Exception:
  2939. pass # Don't fail AMS callback if MQTT fails
  2940. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2941. # This ensures frontend gets immediate updates when AMS slots are configured
  2942. try:
  2943. state = printer_manager.get_status(printer_id)
  2944. if state:
  2945. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2946. await ws_manager.send_printer_status(
  2947. printer_id,
  2948. printer_state_to_dict(
  2949. state,
  2950. printer_id,
  2951. printer_manager.get_model(printer_id),
  2952. printer_manager.get_drying_targets(printer_id),
  2953. ),
  2954. )
  2955. except Exception as e:
  2956. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2957. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2958. # Spools whose tag this pass assigned to a slot; their other slots are
  2959. # released below, once this printer's lock is let go (#3427).
  2960. rfid_assigned: list[tuple[int, tuple[int, int, int]]] = []
  2961. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2962. # Serialised per-printer via services/ams_assignment_lock: MQTT bursts can deliver
  2963. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2964. # "no existing assignment" for the same (printer, ams, tray) and race to
  2965. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2966. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2967. # bug stayed latent there. See services/ams_assignment_lock for details.
  2968. try:
  2969. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2970. from sqlalchemy.orm import selectinload
  2971. from backend.app.api.routes.settings import get_setting
  2972. from backend.app.models.spool import Spool
  2973. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2974. from backend.app.services.spool_tag_matcher import (
  2975. auto_assign_spool,
  2976. create_spool_from_tray,
  2977. find_matching_untagged_spool,
  2978. get_spool_by_tag,
  2979. is_bambu_tag,
  2980. is_valid_tag,
  2981. link_tag_to_inventory_spool,
  2982. tag_belongs_to_archived_spool,
  2983. )
  2984. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2985. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2986. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2987. if not _spoolman_on or _spoolman_on.lower() != "true":
  2988. for ams_unit in ams_data:
  2989. if not isinstance(ams_unit, dict):
  2990. continue
  2991. ams_id = int(ams_unit.get("id", 0))
  2992. for tray in ams_unit.get("tray", []):
  2993. if not isinstance(tray, dict):
  2994. continue
  2995. tray_id = int(tray.get("id", 0))
  2996. tag_uid = tray.get("tag_uid", "")
  2997. tray_uuid = tray.get("tray_uuid", "")
  2998. tray_info_idx = tray.get("tray_info_idx", "")
  2999. if not tray.get("tray_type"):
  3000. # Slot reported empty — drop any cached unknown-tag
  3001. # broadcast so reinserting the same spool re-prompts.
  3002. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  3003. continue # Empty slot
  3004. # Check if assignment already exists for this slot
  3005. existing = await db.execute(
  3006. select(SA)
  3007. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  3008. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  3009. )
  3010. existing_assignment = existing.scalar_one_or_none()
  3011. if existing_assignment:
  3012. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  3013. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  3014. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  3015. # Skip during active prints: the usage tracker handles deduction
  3016. # precisely via 3MF data on print completion. Without this guard the
  3017. # AMS remain% SET and the usage tracker ADD both fire from the same
  3018. # MQTT message, doubling the deduction (#880).
  3019. if _print_active:
  3020. continue
  3021. remain_raw = tray.get("remain")
  3022. if (
  3023. remain_raw is not None
  3024. and existing_assignment.spool
  3025. and not existing_assignment.spool.weight_locked
  3026. ):
  3027. try:
  3028. remain_val = int(remain_raw)
  3029. except (TypeError, ValueError):
  3030. remain_val = -1
  3031. if 1 <= remain_val <= 100:
  3032. lw = existing_assignment.spool.label_weight or 1000
  3033. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  3034. current_used = existing_assignment.spool.weight_used or 0
  3035. if new_used > current_used + 1:
  3036. # Rechecked in the statement: the spool was loaded
  3037. # before this, and a weight set by hand (or weighed)
  3038. # and locked since then must stay (WL-6).
  3039. result = cast(
  3040. CursorResult,
  3041. await db.execute(
  3042. update(Spool)
  3043. .where(
  3044. Spool.id == existing_assignment.spool_id,
  3045. Spool.weight_locked.is_not(True),
  3046. func.coalesce(Spool.weight_used, 0) < new_used - 1,
  3047. )
  3048. .values(weight_used=new_used)
  3049. ),
  3050. )
  3051. await db.commit()
  3052. if result.rowcount:
  3053. logger.info(
  3054. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  3055. existing_assignment.spool_id,
  3056. current_used,
  3057. new_used,
  3058. remain_val,
  3059. )
  3060. await ws_manager.broadcast({"type": "inventory_changed"})
  3061. # A K-profile the slot lost (the default K after a reset or
  3062. # power cycle) is put back by kprofile_drift on the next idle
  3063. # push; a different real profile was picked on purpose and
  3064. # stays (#3219, item 44).
  3065. continue
  3066. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  3067. # BL spool with RFID tag: auto-match → inventory match → auto-create
  3068. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  3069. # Only a spool already known by this tag is proven to be
  3070. # here; a material/colour match or a new spool is not
  3071. # grounds to take it out of other slots (#3427).
  3072. known_by_tag = spool is not None
  3073. if not spool and await tag_belongs_to_archived_spool(db, tag_uid, tray_uuid):
  3074. # An archived spool still in the AMS: the slot
  3075. # stays free rather than adopting its tag.
  3076. continue
  3077. if not spool:
  3078. # Try matching an untagged inventory spool (same material/color)
  3079. spool = await find_matching_untagged_spool(db, tray)
  3080. if spool:
  3081. await link_tag_to_inventory_spool(db, spool, tray)
  3082. elif _auto_add_unknown:
  3083. spool = await create_spool_from_tray(db, tray)
  3084. else:
  3085. # Auto-add disabled: surface the slot so the
  3086. # user can add it manually via the UI.
  3087. await _broadcast_unknown_tag(
  3088. printer_id=printer_id,
  3089. ams_id=ams_id,
  3090. tray_id=tray_id,
  3091. tag_uid=tag_uid,
  3092. tray_uuid=tray_uuid,
  3093. tray_type=tray.get("tray_type"),
  3094. tray_color=tray.get("tray_color"),
  3095. tray_sub_brands=tray.get("tray_sub_brands"),
  3096. tray_count=len(ams_unit.get("tray", [])),
  3097. )
  3098. continue
  3099. # Slot matched (existing tag, untagged inventory
  3100. # match, or freshly auto-created spool) — drop any
  3101. # stale dedup so a future tag swap re-prompts.
  3102. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  3103. await auto_assign_spool(
  3104. printer_id,
  3105. ams_id,
  3106. tray_id,
  3107. spool,
  3108. printer_manager,
  3109. db,
  3110. tray_info_idx=tray_info_idx,
  3111. )
  3112. await db.commit()
  3113. if known_by_tag:
  3114. rfid_assigned.append((spool.id, (printer_id, ams_id, tray_id)))
  3115. await ws_manager.broadcast(
  3116. {
  3117. "type": "spool_auto_assigned",
  3118. "printer_id": printer_id,
  3119. "ams_id": ams_id,
  3120. "tray_id": tray_id,
  3121. "spool_id": spool.id,
  3122. }
  3123. )
  3124. logger.info(
  3125. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  3126. spool.id,
  3127. printer_id,
  3128. ams_id,
  3129. tray_id,
  3130. )
  3131. elif is_valid_tag(tag_uid, tray_uuid) and not await tag_belongs_to_archived_spool(
  3132. db, tag_uid, tray_uuid
  3133. ):
  3134. # Non-BL spool with some tag — let user choose (not
  3135. # an archived one's, whose slot stays free)
  3136. await _broadcast_unknown_tag(
  3137. printer_id=printer_id,
  3138. ams_id=ams_id,
  3139. tray_id=tray_id,
  3140. tag_uid=tag_uid,
  3141. tray_uuid=tray_uuid,
  3142. tray_type=tray.get("tray_type"),
  3143. tray_color=tray.get("tray_color"),
  3144. tray_sub_brands=tray.get("tray_sub_brands"),
  3145. tray_count=len(ams_unit.get("tray", [])),
  3146. )
  3147. # No-tag slots (generic non-RFID filament) are left alone:
  3148. # nothing to identify, prompting "+ Add" would just create
  3149. # ghost spools with empty tags on every confirm.
  3150. except Exception as e:
  3151. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  3152. if rfid_assigned:
  3153. from backend.app.services.spool_relocation import INTERNAL, release_other_slots
  3154. for spool_id, slot in rfid_assigned:
  3155. try:
  3156. await release_other_slots(INTERNAL, spool_id, slot)
  3157. except Exception as e:
  3158. logger.warning("Releasing spool %s from its other slots failed: %s", spool_id, e, exc_info=True)
  3159. try:
  3160. async with async_session() as db:
  3161. from backend.app.api.routes.settings import get_setting
  3162. from backend.app.models.printer import Printer
  3163. # Check if Spoolman is enabled
  3164. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  3165. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  3166. return
  3167. # Check sync mode
  3168. sync_mode = await get_setting(db, "spoolman_sync_mode")
  3169. if sync_mode and sync_mode != "auto":
  3170. return # Only sync on auto mode
  3171. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  3172. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  3173. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  3174. # always owned by per-print tracking, never by AMS auto-sync. The
  3175. # setting is still read by the settings UI for backwards compat but
  3176. # has no effect on the sync path here.
  3177. # Get Spoolman URL
  3178. spoolman_url = await get_setting(db, "spoolman_url")
  3179. if not spoolman_url:
  3180. return
  3181. # Get or create Spoolman client
  3182. client = await get_spoolman_client()
  3183. if not client:
  3184. try:
  3185. client = await init_spoolman_client(spoolman_url)
  3186. except ValueError as exc:
  3187. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  3188. return
  3189. # Check if Spoolman is reachable
  3190. if not await client.health_check():
  3191. logger.warning("Spoolman not reachable at %s", spoolman_url)
  3192. return
  3193. # Get printer name for location
  3194. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3195. printer = result.scalar_one_or_none()
  3196. printer_name = printer.name if printer else f"Printer {printer_id}"
  3197. # OPTIMIZATION: Fetch all spools once before processing trays
  3198. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  3199. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  3200. try:
  3201. cached_spools = await client.get_spools()
  3202. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  3203. except Exception as e:
  3204. logger.error(
  3205. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  3206. printer_id,
  3207. e,
  3208. )
  3209. return
  3210. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  3211. from sqlalchemy.orm import selectinload
  3212. from backend.app.models.spool_assignment import SpoolAssignment
  3213. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  3214. from backend.app.services.ams_slot_presence import spool_present
  3215. from backend.app.services.inventory_mode import spoolman_owns_assignments
  3216. # Built-in remaining weight, used by sync_ams_tray only when the
  3217. # firmware reports an unusable remain%/tray_weight for a slot.
  3218. #
  3219. # Left empty since #2812. This block runs in Spoolman mode only,
  3220. # and until then the built-in table was emptied on the switch, so
  3221. # there was never anything here to read and the fallback was inert.
  3222. # Preserving those rows makes it live again, and it is keyed by slot
  3223. # rather than by spool: after a mode switch the tray may well hold
  3224. # different filament, and ``create_spool`` writes ``remaining_weight``
  3225. # unconditionally, so a stale figure would be seeded into a brand new
  3226. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  3227. # intent survives for whoever revisits the cross-mode fallback.
  3228. inventory_weights: dict[tuple[int, int], float] = {}
  3229. if not await spoolman_owns_assignments(db):
  3230. try:
  3231. assign_result = await db.execute(
  3232. select(SpoolAssignment)
  3233. .options(selectinload(SpoolAssignment.spool))
  3234. .where(SpoolAssignment.printer_id == printer_id)
  3235. )
  3236. for assignment in assign_result.scalars().all():
  3237. spool = assignment.spool
  3238. if spool and spool.label_weight > 0:
  3239. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  3240. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  3241. except Exception as e:
  3242. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  3243. # Load existing Spoolman slot assignments for the no-RFID fallback path
  3244. spoolman_slot_map: dict[tuple[int, int], int] = {}
  3245. slot_map_read = False
  3246. try:
  3247. slot_result = await db.execute(
  3248. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  3249. )
  3250. for slot in slot_result.scalars().all():
  3251. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  3252. slot_map_read = True
  3253. except Exception as e:
  3254. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  3255. # Sync each AMS tray and collect slot changes for DB persistence
  3256. synced = 0
  3257. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  3258. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  3259. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  3260. for ams_unit in ams_data:
  3261. if not isinstance(ams_unit, dict):
  3262. continue
  3263. ams_id = int(ams_unit.get("id", 0))
  3264. trays = ams_unit.get("tray", [])
  3265. for tray_data in trays:
  3266. if not isinstance(tray_data, dict):
  3267. continue
  3268. tray_id_raw = int(tray_data.get("id", 0))
  3269. tray = client.parse_ams_tray(ams_id, tray_data)
  3270. if not tray:
  3271. # Empty tray slot — record for local assignment cleanup
  3272. # and drop any cached unknown-tag broadcast so a
  3273. # reinserted spool re-prompts.
  3274. #
  3275. # Not during a running print: a slot that empties there
  3276. # is a filament runout, and the spool is still in the
  3277. # AMS. `spoolman_slot_assignments` is how a tag-less
  3278. # spool assigned through the Bambuddy UI is resolved at
  3279. # completion (#1459), so deleting the row mid-print
  3280. # loses the runout segment's usage — the same failure
  3281. # the internal inventory's auto-unlink had.
  3282. #
  3283. # Nor when firmware's presence bit says the slot is
  3284. # occupied. parse_ams_tray calls a tray with no type or
  3285. # no colour empty, and a spool the AMS cannot read has
  3286. # neither until something configures it — so a tag-less
  3287. # spool assigned through the UI had its row deleted by
  3288. # the first idle push after it was inserted. Same
  3289. # deletion as the internal inventory's in #3100, same
  3290. # answer, so the two modes stay in step.
  3291. #
  3292. # And only once the slot has stayed empty for the grace
  3293. # period -- the internal inventory's #3186 answer, for
  3294. # the same one-push blank.
  3295. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  3296. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  3297. if not printing_now and (
  3298. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  3299. ):
  3300. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  3301. empty_slots.append((ams_id, tray_id_raw))
  3302. else:
  3303. spoolman_held.add(hold_key)
  3304. logger.info(
  3305. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  3306. "unlinking if it is still empty in %ds",
  3307. ams_id,
  3308. tray_id_raw,
  3309. linked_spool,
  3310. int(slot_unlink_grace.GRACE_SECONDS),
  3311. )
  3312. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  3313. continue
  3314. spool_tag = (
  3315. tray.tray_uuid
  3316. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  3317. else tray.tag_uid
  3318. )
  3319. # Provide the hint only when no RFID is available
  3320. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  3321. try:
  3322. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  3323. result = await client.sync_ams_tray(
  3324. tray,
  3325. printer_name,
  3326. db,
  3327. # Per-print tracking is the only weight writer (#1119).
  3328. # AMS auto-sync still maintains spool metadata / slot
  3329. # assignments but no longer touches remaining_weight.
  3330. disable_weight_sync=True,
  3331. cached_spools=cached_spools,
  3332. inventory_remaining=inv_remaining,
  3333. spoolman_spool_id_hint=hint,
  3334. auto_add_unknown_rfid=auto_add_unknown_rfid,
  3335. )
  3336. if result is None and spool_tag and not auto_add_unknown_rfid:
  3337. # Spoolman skipped auto-create per user setting — surface
  3338. # the slot so the UI can offer "+ Add to inventory".
  3339. await _broadcast_unknown_tag(
  3340. printer_id=printer_id,
  3341. ams_id=ams_id,
  3342. tray_id=tray.tray_id,
  3343. tag_uid=tray.tag_uid or "",
  3344. tray_uuid=tray.tray_uuid or "",
  3345. tray_type=tray.tray_type,
  3346. tray_color=tray.tray_color,
  3347. tray_sub_brands=tray.tray_sub_brands,
  3348. tray_count=len(trays),
  3349. )
  3350. elif result:
  3351. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  3352. if result:
  3353. synced += 1
  3354. if result.get("id"):
  3355. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  3356. # If a new spool was created, add it to the cache
  3357. # so subsequent trays can find it if they reference the same tag
  3358. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  3359. if not spool_exists:
  3360. cached_spools.append(result)
  3361. logger.debug(
  3362. "[Printer %s] Added newly created spool %s to cache",
  3363. printer_id,
  3364. result["id"],
  3365. )
  3366. # Reconcile slot_preset_mappings (the same row internal
  3367. # mode keeps in sync via inventory + spool_tag_matcher).
  3368. # Without this the slot card surfaces the previous spool's
  3369. # preset name — same bug shape, different inventory mode.
  3370. from backend.app.services.slot_preset_writer import (
  3371. upsert_slot_preset_for_spoolman_spool,
  3372. )
  3373. await upsert_slot_preset_for_spoolman_spool(
  3374. db=db,
  3375. spoolman_spool=result,
  3376. tray_info_idx=tray.tray_info_idx or "",
  3377. tray_sub_brands=tray.tray_sub_brands or "",
  3378. tray_type=tray.tray_type or "",
  3379. printer_id=printer_id,
  3380. ams_id=ams_id,
  3381. tray_id=tray.tray_id,
  3382. )
  3383. except Exception as e:
  3384. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  3385. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  3386. if synced > 0:
  3387. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  3388. # Persist slot assignment changes to the local table: only slots
  3389. # whose spool this pass changed, and only while they still hold what
  3390. # it read before awaiting Spoolman, so a spool assigned by hand in
  3391. # between stays (SSA-3). The changed slots are announced: the slot
  3392. # card reads slot_preset_mappings (rewritten above) ahead of the live
  3393. # tray, so with no event it kept the previous spool's preset name.
  3394. if slot_changes or empty_slots:
  3395. from backend.app.services.spoolman_slot_sync import write_slot_results
  3396. try:
  3397. await write_slot_results(
  3398. db,
  3399. {(printer_id, a_id, t_id): spool_id for (a_id, t_id), spool_id in spoolman_slot_map.items()}
  3400. if slot_map_read
  3401. else None,
  3402. [(printer_id, a_id, t_id, spool_id) for a_id, t_id, spool_id in slot_changes],
  3403. [(printer_id, a_id, t_id) for a_id, t_id in empty_slots],
  3404. )
  3405. except Exception as e:
  3406. await db.rollback()
  3407. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3408. except Exception as e:
  3409. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3410. # Largest finish photo attached to a notification; a bigger one is still linked.
  3411. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3412. async def _finish_photo_for_notification(
  3413. db, archive, archive_id: int, filename: str
  3414. ) -> tuple[str | None, bytes | None]:
  3415. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3416. With authentication off the link is the archive's own photo route, as it
  3417. always was: it opens without a login and doesn't expire. With
  3418. authentication on that route needs a media token, which nothing tapping a
  3419. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3420. link only ever answered 401. The photo is then saved as a notification
  3421. photo as well (utils/notification_photos.py) and the link points there: an
  3422. unguessable name that opens this one photo and nothing else, for 3 days.
  3423. The link is relative when no External URL is set. Bytes over
  3424. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3425. ``(None, None)`` when the photo can't be found.
  3426. """
  3427. from backend.app.api.routes.settings import get_setting
  3428. from backend.app.core.auth import is_auth_enabled
  3429. from backend.app.utils.archive_paths import find_archive_photo
  3430. from backend.app.utils.notification_photos import save_notification_photo
  3431. log = logging.getLogger(__name__)
  3432. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3433. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3434. photo_bytes: bytes | None = None
  3435. try:
  3436. photo_path = find_archive_photo(archive, filename)
  3437. if photo_path is not None:
  3438. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3439. except Exception as e:
  3440. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3441. try:
  3442. auth_on = await is_auth_enabled(db)
  3443. except Exception:
  3444. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3445. if auth_on:
  3446. url = None
  3447. if photo_bytes:
  3448. try:
  3449. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3450. url = f"{base}/api/v1/notifications/photos/{name}"
  3451. except Exception as e:
  3452. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3453. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3454. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3455. return url, None
  3456. if photo_bytes:
  3457. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3458. return url, photo_bytes
  3459. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3460. """Capture a camera snapshot for notification image attachment.
  3461. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3462. Uses: external camera > buffered frame > fresh capture.
  3463. Turns the chamber light on for the picture when the printer asks for it
  3464. (#1655). ``light=False`` is for callers that capture all through a print,
  3465. where the light would flash with every frame.
  3466. """
  3467. if not printer:
  3468. return None
  3469. async with camera_light(printer if light else None):
  3470. return await _capture_snapshot_frame(printer_id, printer, logger)
  3471. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3472. """The capture behind ``_capture_snapshot_for_notification``."""
  3473. try:
  3474. from backend.app.api.routes.settings import get_setting
  3475. async with async_session() as db:
  3476. capture_enabled = await get_setting(db, "capture_finish_photo")
  3477. if capture_enabled is not None and capture_enabled.lower() != "true":
  3478. return None
  3479. # Try external camera first
  3480. if printer.external_camera_enabled and printer.external_camera_url:
  3481. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3482. from backend.app.api.routes.camera import live_frame_for_capture
  3483. from backend.app.services.external_camera import capture_frame
  3484. # An external camera allows one reader, so capturing while a viewer
  3485. # is attached fails (#2707). A None here falls through to the paths
  3486. # below exactly as a failed capture did.
  3487. defer, buffered = live_frame_for_capture(printer_id)
  3488. if defer:
  3489. frame_data = buffered
  3490. else:
  3491. frame_data = await capture_frame(
  3492. printer.external_camera_url,
  3493. printer.external_camera_type or "mjpeg",
  3494. snapshot_url=printer.external_camera_snapshot_url,
  3495. )
  3496. if frame_data and len(frame_data) <= 2_500_000:
  3497. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3498. return _apply_camera_rotation(frame_data, printer, logger)
  3499. # Try buffered frame from active stream
  3500. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3501. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3502. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3503. buffered_frame = get_buffered_frame(printer_id)
  3504. if (active_for_printer or active_chamber) and buffered_frame:
  3505. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3506. if len(buffered_frame) <= 2_500_000:
  3507. return _apply_camera_rotation(buffered_frame, printer, logger)
  3508. # Fresh capture from printer camera
  3509. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3510. from backend.app.services.camera import capture_camera_frame_bytes
  3511. frame_data = await capture_camera_frame_bytes(
  3512. printer.ip_address, printer.access_code, printer.model, timeout=15
  3513. )
  3514. if frame_data and len(frame_data) <= 2_500_000:
  3515. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3516. return _apply_camera_rotation(frame_data, printer, logger)
  3517. except Exception as e:
  3518. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3519. return None
  3520. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3521. """#1867: bank a recent in-print camera frame for the finish photo.
  3522. Called on every layer change and (#2547) on every print-progress advance.
  3523. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3524. path has a pre-End-G-code image for prints that end with a plate swap.
  3525. Both drivers are print telemetry that stops the instant printing ends: no
  3526. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3527. plate swap) executes. So the last banked frame is always the finished print,
  3528. never the swapped plate — that property is what the #1867 path relies on and
  3529. it must survive any change to the throttle below.
  3530. Layer changes alone were not enough: they stop when the *final* layer
  3531. begins, which on a three-minute last layer left the bank stale by the whole
  3532. length of that layer (#2547). Progress keeps ticking through it.
  3533. Best-effort: any failure just leaves the previous banked frame.
  3534. """
  3535. logger = logging.getLogger(__name__)
  3536. client = printer_manager.get_client(printer_id)
  3537. state = client.state if client else None
  3538. if not state or state.state != "RUNNING":
  3539. return
  3540. # Only during actual extrusion — firmware ticks layer_num during the
  3541. # pre-print calibration sequence, whose sub-stages are non-zero.
  3542. if state.mc_print_sub_stage not in (None, 0):
  3543. return
  3544. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3545. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3546. # now that progress advances also drive banking, that exemption would fire a
  3547. # camera grab on every percent tick of the last layer. Bambu printers accept
  3548. # one RTSP client at a time, so each grab contends with the live view.
  3549. now = time.monotonic()
  3550. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3551. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3552. return
  3553. total = state.total_layers or 0
  3554. try:
  3555. async with async_session() as db:
  3556. from backend.app.models.printer import Printer
  3557. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3558. printer = result.scalar_one_or_none()
  3559. if not printer:
  3560. return
  3561. # Reuses the notification snapshot path, which honours the
  3562. # `capture_finish_photo` setting (returns None when disabled) so we
  3563. # don't bank frames the user never asked for. Without the chamber light
  3564. # (#1655): this runs every 25 seconds for the whole print.
  3565. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3566. if frame:
  3567. _inprint_frame_bank[printer_id] = frame
  3568. _inprint_frame_bank_ts[printer_id] = now
  3569. logger.debug(
  3570. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3571. printer_id,
  3572. layer_num,
  3573. total,
  3574. len(frame),
  3575. )
  3576. except Exception as e:
  3577. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3578. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3579. """Apply camera rotation to snapshot image if configured."""
  3580. from backend.app.services.camera import apply_camera_rotation
  3581. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3582. async def _send_print_start_notification(
  3583. printer_id: int,
  3584. data: dict,
  3585. archive_data: dict | None = None,
  3586. logger=None,
  3587. ):
  3588. """Helper to send print start notification with optional archive data."""
  3589. if logger is None:
  3590. logger = logging.getLogger(__name__)
  3591. try:
  3592. async with async_session() as db:
  3593. from backend.app.models.printer import Printer
  3594. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3595. printer = result.scalar_one_or_none()
  3596. printer_name = printer.name if printer else f"Printer {printer_id}"
  3597. # Capture camera snapshot for notification image attachment
  3598. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3599. if image_data:
  3600. if archive_data is None:
  3601. archive_data = {}
  3602. archive_data["image_data"] = image_data
  3603. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3604. # Send user-specific email notification for print start
  3605. if archive_data and archive_data.get("created_by_id"):
  3606. await notification_service.send_user_print_email(
  3607. event_type="user_print_start",
  3608. created_by_id=archive_data["created_by_id"],
  3609. printer_name=printer_name,
  3610. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3611. db=db,
  3612. )
  3613. except Exception as e:
  3614. logger.warning("Notification on_print_start failed: %s", e)
  3615. async def _dispatch_user_print_email(
  3616. status: str,
  3617. created_by_id: int | None,
  3618. printer_name: str,
  3619. filename: str,
  3620. db,
  3621. image_data: bytes | None = None,
  3622. finish_photo_url: str | None = None,
  3623. ) -> None:
  3624. """Send a user-specific print-completion email based on print status.
  3625. Maps the normalised print status to the correct event type and delegates
  3626. to :meth:`NotificationService.send_user_print_email`. A single helper
  3627. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3628. "stopped"`` dispatch block at every call site.
  3629. Does nothing if *created_by_id* is ``None``.
  3630. """
  3631. if created_by_id is None:
  3632. return
  3633. if status == "completed":
  3634. event_type = "user_print_complete"
  3635. elif status == "failed":
  3636. event_type = "user_print_failed"
  3637. elif status in ("stopped", "aborted", "cancelled"):
  3638. event_type = "user_print_stopped"
  3639. else:
  3640. return
  3641. await notification_service.send_user_print_email(
  3642. event_type=event_type,
  3643. created_by_id=created_by_id,
  3644. printer_name=printer_name,
  3645. filename=filename,
  3646. db=db,
  3647. image_data=image_data,
  3648. finish_photo_url=finish_photo_url,
  3649. )
  3650. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3651. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3652. try:
  3653. from backend.app.services.archive import extract_printable_objects_from_archive
  3654. client = printer_manager.get_client(printer_id)
  3655. if not client:
  3656. return
  3657. # Extract with positions for UI overlay, scoped to the plate that
  3658. # is printing — resolve_plate_id is the same resolver /cover uses,
  3659. # so the object list can't disagree with the thumbnail it is drawn
  3660. # over (#2522).
  3661. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3662. app_settings.base_dir / archive.file_path,
  3663. plate_number=resolve_plate_id(client.state),
  3664. )
  3665. if printable_objects:
  3666. client.state.printable_objects = printable_objects
  3667. client.state.printable_objects_bbox_all = bbox_all
  3668. client.state.skipped_objects = []
  3669. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3670. except Exception as e:
  3671. logger.debug("Failed to extract printable objects from archive: %s", e)
  3672. def _load_pauses_from_3mf(threemf_path, printer_id: int, *, warned_layers=(), passed_through_layer: int = 0) -> None:
  3673. """Read the running print's slicer pauses from its 3MF, in the background (#2984).
  3674. In a thread: a plate's G-code runs to tens of MB, and the print-start
  3675. handler must not wait for it. Kept only while the printer is still on
  3676. the print they were read for: a new print replaces the list.
  3677. ``warned_layers``: pauses this print was already warned about, kept on its
  3678. archive, so a restart does not send the heads-up again.
  3679. ``passed_through_layer``: for a print resumed after a restart, the layer it
  3680. is on. Its pauses up to there are behind it, though the printer's layer
  3681. reads 0 until it reports the next one.
  3682. """
  3683. client = printer_manager.get_client(printer_id)
  3684. if not client:
  3685. return
  3686. state = client.state
  3687. read_for = state.pause_points
  3688. try:
  3689. plate_id = resolve_plate_id(state)
  3690. except Exception:
  3691. # Never at the cost of the print-start handler this runs inside.
  3692. logging.getLogger(__name__).warning("[Printer %s] Could not tell the plate to read pauses for", printer_id)
  3693. return
  3694. async def _load() -> None:
  3695. from backend.app.utils.threemf_tools import extract_pause_points_from_3mf
  3696. points = await asyncio.to_thread(extract_pause_points_from_3mf, Path(threemf_path), plate_id)
  3697. if state.pause_points is not read_for:
  3698. return
  3699. state.pause_points = [p for p in points if p.layer > passed_through_layer]
  3700. state.pause_warned_layers = set(state.pause_warned_layers) | set(warned_layers)
  3701. if points:
  3702. logging.getLogger(__name__).info(
  3703. "Loaded %s slicer pause(s) for printer %s at layer(s) %s",
  3704. len(points),
  3705. printer_id,
  3706. [p.layer for p in points],
  3707. )
  3708. spawn_background_task(_load(), name=f"load-pauses-{printer_id}")
  3709. def _load_pauses_from_resumed_archive(archive, printer_id: int) -> None:
  3710. """Pauses for a print start taken as the resumption of a running print.
  3711. A restart while the print was paused makes its resume look like a new
  3712. print (#2984): the pauses warned about and passed are kept from before.
  3713. """
  3714. client = printer_manager.get_client(printer_id)
  3715. state = client.state if client else None
  3716. _load_pauses_from_3mf(
  3717. app_settings.base_dir / archive.file_path,
  3718. printer_id,
  3719. warned_layers=pause_eta.warned_layers_of(archive, state) if state is not None else (),
  3720. passed_through_layer=getattr(client, "layer_before_new_print", 0) if client else 0,
  3721. )
  3722. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3723. """Put the skip-objects list back after a restart mid-print.
  3724. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3725. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3726. which the #1304 guard suppresses on the first RUNNING push after startup.
  3727. Everything else this hook restores (the archive, the usage-tracking session,
  3728. the timelapse baseline) was already handled; the object list was not, so a
  3729. restart mid-print took skip-objects away for the rest of that print.
  3730. Nothing recovered it either: the printer card gates its Skip button on the
  3731. object count, and the one endpoint that can rebuild the list is reachable
  3732. only from the modal that button opens.
  3733. The archive is the running print's as ``running_print_archive`` finds it:
  3734. by subtask_id, or for a print that reports none by the archive bound to it
  3735. (#3327), never by name: a leftover ``status="printing"`` row from a
  3736. completion we never saw must not hand this print someone else's objects.
  3737. After a restart that binding exists only for Bambuddy's own prints, so a
  3738. print that reports no subtask_id loads nothing rather than a guess; the
  3739. reload path on ``GET /print/objects`` covers that case on demand.
  3740. """
  3741. client = printer_manager.get_client(printer_id)
  3742. if client is None or (client.state.printable_objects and client.state.pause_points):
  3743. return
  3744. archive = await running_print_archive(db, printer_id, state, printing_only=True, by_name=False)
  3745. if archive is not None and archive.file_path:
  3746. if not client.state.printable_objects:
  3747. _load_objects_from_archive(archive, printer_id, logger)
  3748. # The slicer's pauses are in-memory only as well (#2984).
  3749. if not client.state.pause_points:
  3750. _load_pauses_from_3mf(
  3751. app_settings.base_dir / archive.file_path,
  3752. printer_id,
  3753. warned_layers=pause_eta.warned_layers_of(archive, state),
  3754. )
  3755. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3756. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3757. # past it; the second covers a handshake that failed again on the way back and
  3758. # armed a fresh one. Module-level so tests can shrink them.
  3759. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3760. # Retry ladder for the other temporary give-up: the file service answered and
  3761. # the transfer still did not finish, which at print start is usually the printer
  3762. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3763. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3764. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3765. # two cover a printer that stays busy well into the print.
  3766. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3767. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3768. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3769. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3770. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3771. # by view, so two views race), the cool-off retry task, and print completion.
  3772. # Without this they each read file_path == "" and each run a full copy, so the row
  3773. # ends up pointing at one timestamped directory while the others sit orphaned.
  3774. #
  3775. # Keyed by printer rather than archive because a printer runs one print at a time,
  3776. # which makes the two equally strong here — and it bounds the dict by printer
  3777. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3778. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3779. # resuming, so "no waiters" is not a question this API can answer.
  3780. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3781. # How many of a printer's newest archives a touchscreen reprint is compared
  3782. # against (#3307). A repeat is usually of a recent job; the bound keeps a
  3783. # print start from reading a long history's extra_data.
  3784. _REPEAT_LOOKBACK = 200
  3785. async def _archived_3mf_for_repeat(
  3786. db, printer_id: int, subtask_name: str | None, gcode_file: str | None, total_layers: int | None
  3787. ):
  3788. """The newest archive of the job this printer is running again, with its 3MF.
  3789. A "Print again" on the printer's screen never names the file on the card:
  3790. it reports its own history copy under a generic name
  3791. (``file:///userdata/project_file.gcode.3mf``), the 3MF's internal title as
  3792. ``subtask_name`` and the plate as ``gcode_file`` -- and the title is often
  3793. not the card file's name, so every lookup built from it misses (#3307).
  3794. An earlier run that was archived recorded that same title and plate in its
  3795. ``_print_data``, and holds the 3MF.
  3796. Same printer, same title, same plate, a 3MF still on disk. A layer count
  3797. known on both sides must agree: the same title and plate re-sliced is
  3798. another job. None when nothing matches.
  3799. """
  3800. from backend.app.models.archive import PrintArchive
  3801. if not subtask_name or not gcode_file:
  3802. return None
  3803. rows = (
  3804. (
  3805. await db.execute(
  3806. select(PrintArchive)
  3807. .where(
  3808. PrintArchive.printer_id == printer_id,
  3809. PrintArchive.deleted_at.is_(None),
  3810. PrintArchive.file_path.isnot(None),
  3811. PrintArchive.file_path != "",
  3812. )
  3813. .order_by(PrintArchive.created_at.desc(), PrintArchive.id.desc())
  3814. .limit(_REPEAT_LOOKBACK)
  3815. )
  3816. )
  3817. .scalars()
  3818. .all()
  3819. )
  3820. for archive in rows:
  3821. extra = archive.extra_data if isinstance(archive.extra_data, dict) else {}
  3822. run = extra.get("_print_data")
  3823. if not isinstance(run, dict):
  3824. continue
  3825. if run.get("subtask_name") != subtask_name or run.get("filename") != gcode_file:
  3826. continue
  3827. if total_layers and archive.total_layers and archive.total_layers != total_layers:
  3828. continue
  3829. if not (app_settings.base_dir / archive.file_path).is_file():
  3830. continue
  3831. return archive
  3832. return None
  3833. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True) -> bool:
  3834. """Fill in a no-3MF archive from a 3MF that turned up later.
  3835. Returns True when the row was upgraded. Safe to call speculatively: it
  3836. verifies the archive still exists, is still a fallback, and that the file
  3837. is a readable 3MF before touching anything.
  3838. Serialised per printer — see ``_fallback_recovery_locks``.
  3839. """
  3840. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3841. async with lock:
  3842. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id, price=price)
  3843. async def _recover_fallback_archive_locked(
  3844. archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True
  3845. ) -> bool:
  3846. """The body of :func:`_recover_fallback_archive`, under its per-printer lock.
  3847. ``price`` is False when the print's end is being handled: the archive
  3848. still reads "printing" then, and its end prices it.
  3849. """
  3850. import zipfile
  3851. from backend.app.models.archive import PrintArchive
  3852. from backend.app.services.archive import ArchiveService
  3853. logger = logging.getLogger(__name__)
  3854. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3855. return False
  3856. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3857. # A truncated or half-written download is worse than no download: it
  3858. # would replace an honest empty archive with wrong metadata.
  3859. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3860. return False
  3861. async with async_session() as db:
  3862. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3863. if archive is None or archive.deleted_at is not None:
  3864. return False
  3865. if archive.file_path:
  3866. # Already recovered, or never was a fallback. Either way there is a
  3867. # real 3MF attached and overwriting it is not this function's job.
  3868. return False
  3869. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3870. service = ArchiveService(db)
  3871. recovered = await service.archive_print(
  3872. printer_id=printer_id,
  3873. source_file=source_3mf,
  3874. print_data={**print_data, "status": archive.status or "printing"},
  3875. subtask_id=archive.subtask_id,
  3876. update_archive_id=archive.id,
  3877. )
  3878. if recovered is None:
  3879. return False
  3880. logger.info(
  3881. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3882. archive_id,
  3883. source_3mf,
  3884. recovered.file_size,
  3885. )
  3886. # Spoolman's tracking stored no 3MF usage at print start and would
  3887. # charge the AMS remain% change; the built-in tracker reads the archive
  3888. # at completion and needs nothing. Also at the print's end (``price``
  3889. # False): that recovery runs inside the close-out, before the charge.
  3890. try:
  3891. from backend.app.services.spoolman_tracking import attach_recovered_3mf
  3892. from backend.app.services.usage_tracker import is_completing
  3893. await attach_recovered_3mf(
  3894. printer_id,
  3895. recovered.id,
  3896. recovered.file_path,
  3897. db,
  3898. printer_manager,
  3899. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3900. may_start=not price or (recovered.status == "printing" and not is_completing(printer_id)),
  3901. )
  3902. except Exception:
  3903. logger.warning(
  3904. "[RECOVER] Archive %s: could not add the 3MF to Spoolman's usage tracking", archive_id, exc_info=True
  3905. )
  3906. if price and recovered.status == "printing" and recovered.file_path:
  3907. # Print start had no 3MF to read the slicer's pauses from (#2984).
  3908. _load_pauses_from_3mf(app_settings.base_dir / recovered.file_path, printer_id)
  3909. if price and recovered.status == "printing":
  3910. # Print start priced it from the default rate, having no 3MF to
  3911. # estimate from; now it has one. An ended print is left alone: its
  3912. # end prices it. A print Bambuddy didn't dispatch has no start
  3913. # plate; the one the archive just read from the 3MF stands in.
  3914. _schedule_archive_cost_estimate(
  3915. printer_id,
  3916. recovered.id,
  3917. printer_manager,
  3918. ams_mapping=_get_start_ams_mapping(print_data, printer_id, recovered.id),
  3919. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3920. session_factory=async_session,
  3921. )
  3922. # `archive_updated`, not `archive_created` — the row was already on the
  3923. # Archives page as an empty card and is now filled in, not new.
  3924. await ws_manager.send_archive_updated(
  3925. {
  3926. "id": recovered.id,
  3927. "printer_id": recovered.printer_id,
  3928. "filename": recovered.filename,
  3929. "print_name": recovered.print_name,
  3930. "status": recovered.status,
  3931. }
  3932. )
  3933. return True
  3934. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path, *, price: bool = True) -> bool:
  3935. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3936. Called from the paths that pull a 3MF for a print that is already under way
  3937. — chiefly the cover endpoint, which downloads the very file the archive flow
  3938. could not get and, before #2957, used it for a thumbnail and nothing else.
  3939. The bytes are already local, so this costs a parse and a row update.
  3940. No-op when the running print has a real archive, which is the common case.
  3941. """
  3942. from backend.app.models.archive import PrintArchive
  3943. logger = logging.getLogger(__name__)
  3944. # `_active_prints` is keyed on the raw names seen at print start — the
  3945. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3946. # Callers here arrive with whichever variant their own path produced, so
  3947. # match on the same normalization the download cache uses rather than on an
  3948. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3949. # endpoint find an archive registered under "Desktop_Goose".
  3950. wanted = normalize_3mf_name(name)
  3951. archive_id = None
  3952. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3953. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3954. archive_id = value
  3955. break
  3956. if archive_id is None:
  3957. return False
  3958. async with async_session() as db:
  3959. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3960. # Cheap pre-check so the common case (a normal archive) does no work.
  3961. if archive is None or archive.file_path or archive.deleted_at is not None:
  3962. return False
  3963. try:
  3964. return await _recover_fallback_archive(archive_id, path, printer_id, price=price)
  3965. except Exception as e:
  3966. # Recovery is opportunistic. A failure here must never take down the
  3967. # caller, which is usually just trying to render a thumbnail.
  3968. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3969. return False
  3970. def _schedule_fallback_3mf_retry(
  3971. printer_id: int,
  3972. archive_id: int,
  3973. filenames: list[str],
  3974. delays: tuple[float, ...] | None = None,
  3975. reason: str = REASON_FTPS_COOLOFF,
  3976. ) -> None:
  3977. """Re-attempt the 3MF download after a temporary give-up.
  3978. ``reason`` says which give-up this is, and picks the default ladder: an
  3979. FTPS cool-off has to be waited out, while a transfer that timed out under
  3980. contention is worth asking about again straight away (#3063). It is only
  3981. read for the ladder and the log line -- the retry itself is identical, since
  3982. in both cases the file is on the printer and the last attempt at it failed
  3983. for a reason that does not last.
  3984. """
  3985. logger = logging.getLogger(__name__)
  3986. if delays is None:
  3987. delays = (
  3988. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3989. if reason == REASON_FTP_TRANSFER_FAILED
  3990. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3991. )
  3992. async def _retry() -> None:
  3993. from backend.app.models.archive import PrintArchive
  3994. from backend.app.models.printer import Printer
  3995. for delay in delays:
  3996. await asyncio.sleep(delay)
  3997. async with async_session() as db:
  3998. archive = (
  3999. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  4000. ).scalar_one_or_none()
  4001. if archive is None or archive.deleted_at is not None or archive.file_path:
  4002. return
  4003. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  4004. if printer is None:
  4005. return
  4006. # Read the fields while the session is open rather than touching
  4007. # a detached instance minutes later, mid-download.
  4008. printer_ip = printer.ip_address
  4009. printer_code = printer.access_code
  4010. printer_model = printer.model
  4011. # Someone else may have fetched it in the meantime — the cover
  4012. # endpoint routinely does, and its copy is the same bytes.
  4013. for name in filenames:
  4014. cached = get_cached_3mf(printer_id, name)
  4015. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  4016. return
  4017. if ftps_handshake_blocked(printer_ip):
  4018. logger.info(
  4019. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  4020. printer_id,
  4021. archive_id,
  4022. )
  4023. continue
  4024. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  4025. for candidate in filenames:
  4026. # Bare name only. These come from the print-start flow, which
  4027. # already strips the path, but the local temp write must not
  4028. # depend on that holding for every future caller — a name that
  4029. # is absolute or contains ".." would otherwise escape the data
  4030. # volume via the `/` operator.
  4031. name = Path(candidate).name
  4032. if not name or name in (".", ".."):
  4033. continue
  4034. if not name.endswith(".3mf"):
  4035. name = f"{name}.3mf"
  4036. temp_path = app_settings.archive_dir / "temp" / name
  4037. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4038. try:
  4039. hit = await download_file_try_paths_async(
  4040. printer_ip,
  4041. printer_code,
  4042. ftp_probe_paths(name),
  4043. temp_path,
  4044. socket_timeout=ftp_timeout,
  4045. printer_model=printer_model,
  4046. max_total_timeout=RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  4047. )
  4048. except Exception as e:
  4049. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  4050. continue
  4051. if not hit:
  4052. continue
  4053. cache_3mf_download(printer_id, name, temp_path)
  4054. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  4055. return
  4056. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  4057. async def _guarded() -> None:
  4058. try:
  4059. await _retry()
  4060. except asyncio.CancelledError:
  4061. raise
  4062. except Exception as e:
  4063. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  4064. finally:
  4065. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  4066. _fallback_3mf_retry_tasks.pop(printer_id, None)
  4067. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  4068. if existing and not existing.done():
  4069. existing.cancel()
  4070. task = asyncio.create_task(_guarded())
  4071. _fallback_3mf_retry_tasks[printer_id] = task
  4072. logger.info(
  4073. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  4074. archive_id,
  4075. reason,
  4076. printer_id,
  4077. ", ".join(f"{d:g}s" for d in delays),
  4078. )
  4079. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  4080. """Whether an archive created here should ask for the print's outcome (#1898).
  4081. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  4082. branches below: a queued job already has its archive and takes the
  4083. expected-print branch, where the queue item's own ``confirm_outcome``
  4084. decides. The queue is still consulted, because a restart mid-print empties
  4085. ``_expected_prints`` — without the check the setting could override a queue
  4086. item that deliberately has the flag off. Any failure answers "don't ask":
  4087. an unwanted prompt is worse than a missing one, and this must never be the
  4088. reason a print goes unarchived.
  4089. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  4090. leaves one behind when a completion cannot be matched to it
  4091. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  4092. only takes it back once the printer has sat connected and terminal for
  4093. minutes. Until then every screen-started print on that printer would
  4094. silently lose its prompt, so the row is held against ``observed_name`` by
  4095. the same comparison a completion uses: a positive disagreement means the row
  4096. is about some other run and this print is external after all.
  4097. """
  4098. logger = logging.getLogger(__name__)
  4099. try:
  4100. # A savepoint rather than a rollback of the caller's transaction on
  4101. # failure: a failed statement leaves the transaction unusable, but a
  4102. # full rollback also expires every object the caller has loaded (the
  4103. # printer, the archive it just created), and on an async session the
  4104. # next attribute read then raises instead of reloading. Everything here
  4105. # is a read, so undoing the savepoint loses nothing.
  4106. async with db.begin_nested():
  4107. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  4108. except Exception as e:
  4109. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  4110. return False
  4111. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  4112. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  4113. from backend.app.api.routes.settings import get_setting, setting_is_true
  4114. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  4115. return False
  4116. from backend.app.models.print_queue import PrintQueueItem
  4117. dispatched_here = await db.scalar(
  4118. select(PrintQueueItem)
  4119. .where(
  4120. PrintQueueItem.printer_id == printer_id,
  4121. PrintQueueItem.status == "printing",
  4122. )
  4123. .limit(1)
  4124. )
  4125. if dispatched_here is None:
  4126. return True
  4127. expected = await _queue_item_dispatched_name(db, dispatched_here)
  4128. observed = (observed_name or "").strip()
  4129. if not expected or not observed or _subtask_names_match(expected, observed):
  4130. logger.info(
  4131. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  4132. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  4133. printer_id,
  4134. dispatched_here.id,
  4135. )
  4136. return False
  4137. logger.info(
  4138. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  4139. "%r; treating this as an externally started print.",
  4140. dispatched_here.id,
  4141. printer_id,
  4142. expected,
  4143. observed,
  4144. )
  4145. return True
  4146. async def _dispatch_outcome_confirmation_safely(
  4147. db,
  4148. printer_id: int,
  4149. printer_name: str,
  4150. data: dict,
  4151. archive_id: int,
  4152. archive_data: dict | None = None,
  4153. run_id: int | None = None,
  4154. ) -> None:
  4155. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  4156. The completion task sends the per-user print email on the same session
  4157. right after the prompt. A failed statement in the prompt leaves that
  4158. session needing a rollback, and without one the email step fails with
  4159. PendingRollbackError; the prompt is the optional part, so it must not be
  4160. the reason the email never goes out.
  4161. """
  4162. try:
  4163. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data, run_id=run_id)
  4164. except Exception as e:
  4165. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  4166. try:
  4167. await db.rollback()
  4168. except Exception:
  4169. pass
  4170. async def _outcome_answerers(db, owner_id: int | None) -> set[int] | None:
  4171. """Who may answer a print's outcome prompt in the app: its owner and anyone
  4172. who may change everyone's archives. None (everyone on the printer) with auth
  4173. off, or for a print nobody owns."""
  4174. from sqlalchemy.orm import selectinload
  4175. from backend.app.core.auth import is_auth_enabled
  4176. from backend.app.core.permissions import Permission
  4177. from backend.app.models.user import User
  4178. if owner_id is None or not await is_auth_enabled(db):
  4179. return None
  4180. users = (await db.execute(select(User).options(selectinload(User.groups)).where(User.is_active))).scalars().all()
  4181. return {owner_id} | {u.id for u in users if u.has_permission(Permission.ARCHIVES_UPDATE_ALL.value)}
  4182. async def dispatch_outcome_confirmation(
  4183. db,
  4184. printer_id: int,
  4185. printer_name: str,
  4186. data: dict,
  4187. archive_id: int,
  4188. archive_data: dict | None = None,
  4189. *,
  4190. run_id: int | None = None,
  4191. ) -> bool:
  4192. """Emit the post-print outcome prompt for a completed print (#1898).
  4193. Gated on the run that ended (``run_id``): ``confirm_requested`` is the
  4194. opt-in (from the queue item, or from ``confirm_outcome_external_prints``
  4195. for a print Bambuddy did not start, copied onto the run at its start) and
  4196. ``user_verdict`` being unset is what makes the question still open. Mints
  4197. the run's capability token the one-tap verdict links carry: plates of one
  4198. archive each have their own question. Without a run, the archive's, as
  4199. before runs.
  4200. Lives here rather than inline in ``on_print_complete``'s notification task
  4201. because that task swallows every exception: extracted, the gate and the two
  4202. emissions can be driven by a test, which is the only thing standing between
  4203. a regression here and a farm that quietly stops asking.
  4204. Returns whether a prompt was sent.
  4205. """
  4206. logger = logging.getLogger(__name__)
  4207. from backend.app.models.archive import PrintArchive
  4208. from backend.app.models.print_log import PrintLogEntry
  4209. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  4210. if confirm_archive is None:
  4211. return False
  4212. run = await db.get(PrintLogEntry, run_id) if run_id is not None else None
  4213. if run is not None and run.archive_id != archive_id:
  4214. run = None
  4215. # The run carries the opt-in from its start; one logged before it did
  4216. # (None) asks as its archive does.
  4217. asks = confirm_archive if run is None or run.confirm_requested is None else run
  4218. holder = run if run is not None else confirm_archive
  4219. if not (asks.confirm_requested and holder.user_verdict is None):
  4220. return False
  4221. import secrets as _secrets
  4222. # A spent token stays on the row so the one-tap route can recognise it, so
  4223. # "has a token" no longer means "answerable". A prompt going out now needs a
  4224. # live one: mint a new token whenever the stored one is already spent, or
  4225. # every button in the new message would land on the already-answered page.
  4226. if not holder.confirm_token or holder.confirm_token_used_at is not None:
  4227. holder.confirm_token = _secrets.token_urlsafe(32)
  4228. holder.confirm_token_used_at = None
  4229. await db.commit()
  4230. from backend.app.api.routes.settings import get_external_base_url, get_setting
  4231. base = await get_external_base_url(db)
  4232. if not await get_setting(db, "external_url"):
  4233. # Both the Telegram inline keyboard and the ntfy action buttons need an
  4234. # absolute URL, so an unconfigured install used to get a message body
  4235. # with two unusable relative paths and no buttons at all. The shared
  4236. # fallback at least produces tappable links; say which setting makes
  4237. # them resolve from a phone.
  4238. logger.warning(
  4239. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  4240. "Set Settings → External URL so they resolve away from this host.",
  4241. base,
  4242. )
  4243. token = holder.confirm_token
  4244. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  4245. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  4246. confirm_url = f"{base}/archives?confirm={archive_id}" + (f"&run={run.id}" if run is not None else "")
  4247. await ws_manager.send_print_confirm_request(
  4248. printer_id,
  4249. {
  4250. "archive_id": archive_id,
  4251. "run_id": run.id if run is not None else None,
  4252. "print_name": confirm_archive.print_name or confirm_archive.filename,
  4253. },
  4254. user_ids=await _outcome_answerers(db, confirm_archive.created_by_id),
  4255. )
  4256. await notification_service.on_print_confirm_request(
  4257. printer_id,
  4258. printer_name,
  4259. data,
  4260. db,
  4261. archive_data=archive_data,
  4262. good_url=good_url,
  4263. reject_url=reject_url,
  4264. confirm_url=confirm_url,
  4265. archive_id=archive_id,
  4266. run_id=run.id if run is not None else None,
  4267. )
  4268. return True
  4269. async def _printer_gone(db, printer_id: int) -> bool:
  4270. """Whether the printer was deleted. A column read: the session's loaded
  4271. Printer would otherwise answer for the database."""
  4272. from backend.app.models.printer import Printer
  4273. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  4274. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  4275. """Remove the archive just written if its printer was deleted meanwhile.
  4276. The delete route sweeps the printer's archives before it commits, so a row
  4277. committed after that sweep (the check before writing passed while the
  4278. delete was still uncommitted) is left for a printer that will never report
  4279. the print's end. A row the sweep reached is the route's: deleted with the
  4280. printer's archives, or detached (printer_id NULL) when the user kept them,
  4281. and then left as it is. Either way nothing is registered for it. Run after
  4282. the archive's commit, before anything is registered for it.
  4283. """
  4284. from backend.app.models.archive import PrintArchive
  4285. if not await _printer_gone(db, printer_id):
  4286. return False
  4287. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  4288. if owner == printer_id:
  4289. logging.getLogger(__name__).info(
  4290. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  4291. )
  4292. await ArchiveService(db).delete_archive(archive_id)
  4293. await forget_printer(printer_id)
  4294. return True
  4295. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  4296. """After an IntegrityError on a print start's archive write: whether it was
  4297. the printer being deleted, forgotten then (the caller returns).
  4298. PostgreSQL: the delete route locks the printer from its archive sweep to its
  4299. commit, so an archive written or adopted for it meanwhile (one that sets
  4300. printer_id) waits and the printer's foreign key then refuses it. That is
  4301. the printer being deleted, not an error; anything else is re-raised by the
  4302. caller.
  4303. """
  4304. await db.rollback()
  4305. if not await _printer_gone(db, printer_id):
  4306. return False
  4307. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  4308. await forget_printer(printer_id)
  4309. return True
  4310. async def _forget_if_printer_gone(printer_id: int) -> None:
  4311. """At the end of a print start: the slow steps after the last check (smart
  4312. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  4313. printer's delete and its forget_printer, and then wrote state back.
  4314. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  4315. SQLite; PostgreSQL refuses it.)
  4316. Its own session: those steps can leave the handler's needing a rollback (a
  4317. write to the archive the delete removed). Never raises: it runs inside the
  4318. fallback branch's try, whose except reports the archive as failed.
  4319. """
  4320. try:
  4321. async with async_session() as db:
  4322. gone = await _printer_gone(db, printer_id)
  4323. if gone:
  4324. await forget_printer(printer_id)
  4325. except Exception:
  4326. logging.getLogger(__name__).warning(
  4327. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  4328. )
  4329. async def _announce_plate_check_failed(printer_id: int, printer_name: str, reason: str) -> None:
  4330. """Tell the UI a plate check could not run. It does not block the print,
  4331. but an unchecked plate is not an empty one."""
  4332. try:
  4333. await ws_manager.broadcast(
  4334. {"type": "plate_check_failed", "printer_id": printer_id, "printer_name": printer_name, "reason": reason}
  4335. )
  4336. except Exception as e:
  4337. logging.getLogger(__name__).warning("[PLATE CHECK] Could not announce the failed check: %s", e)
  4338. def _expected_print_keys(printer_id: int, filename: str | None, subtask_name: str | None) -> list[tuple[int, str]]:
  4339. """The ``_expected_prints`` keys a print start may be registered under."""
  4340. keys: list[tuple[int, str]] = []
  4341. if subtask_name:
  4342. keys.append((printer_id, subtask_name))
  4343. keys.append((printer_id, f"{subtask_name}.3mf"))
  4344. keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  4345. if filename:
  4346. fname = filename.split("/")[-1] if "/" in filename else filename
  4347. keys.append((printer_id, fname))
  4348. # Strip extensions to match
  4349. base = fname.replace(".gcode", "").replace(".3mf", "")
  4350. keys.append((printer_id, base))
  4351. keys.append((printer_id, f"{base}.3mf"))
  4352. return keys
  4353. async def _dispatched_by_bambuddy(db, printer_id: int, filename: str | None, subtask_name: str | None) -> bool:
  4354. """Whether this print start is one Bambuddy sent to the printer."""
  4355. if any(key in _expected_prints for key in _expected_print_keys(printer_id, filename, subtask_name)):
  4356. return True
  4357. from backend.app.models.archive import PrintArchive
  4358. from backend.app.models.print_queue import PrintQueueItem
  4359. # The queue row the scheduler sets to printing before it sends -- but only
  4360. # when it was sent as this print: a row left printing by a run whose end
  4361. # was missed names another file.
  4362. dispatched_names = (
  4363. await db.execute(
  4364. select(PrintArchive.filename)
  4365. .join(PrintQueueItem, PrintQueueItem.archive_id == PrintArchive.id)
  4366. .where(PrintQueueItem.printer_id == printer_id, PrintQueueItem.status == "printing")
  4367. )
  4368. ).scalars()
  4369. observed = [name for name in (subtask_name, (filename or "").rsplit("/", 1)[-1]) if name]
  4370. return any(
  4371. _subtask_names_match(_subtask_name_from_filename(dispatched), _subtask_name_from_filename(seen))
  4372. for dispatched in dispatched_names
  4373. if dispatched
  4374. for seen in observed
  4375. )
  4376. async def on_print_start(printer_id: int, data: dict):
  4377. """Handle print start - archive the 3MF file immediately."""
  4378. logger = logging.getLogger(__name__)
  4379. # The print's start, before the 3MF download that the archive waits for
  4380. # (#3327): a minute of it would otherwise be missing from the print time.
  4381. detected_at = datetime.now(timezone.utc)
  4382. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  4383. octoeverywhere_detection_service.reset_printer(printer_id)
  4384. try:
  4385. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  4386. except Exception:
  4387. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  4388. # Clear any stale user-stopped flag from previous print cycles
  4389. _user_stopped_printers.discard(printer_id)
  4390. _kill_switch_stopped.discard(printer_id)
  4391. # A new print starts its milestones from zero (#3211). The status path only
  4392. # resets on progress below 5 while not printing, which a printer that goes
  4393. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  4394. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  4395. # or on resume from pause, so it cannot repeat a milestone mid-print.
  4396. _last_progress_milestone[printer_id] = 0
  4397. _kill_switch_notification_tasks.pop(printer_id, None)
  4398. # #1721: drop any leftover pre-captured finish frame from a prior print
  4399. # so a never-consumed cache entry can't bleed into the new print's photo.
  4400. _stage22_finish_frames.pop(printer_id, None)
  4401. # #1867: same for the in-print frame bank — a queued print must not reuse
  4402. # the previous job's banked frame.
  4403. _inprint_frame_bank.pop(printer_id, None)
  4404. _inprint_frame_bank_ts.pop(printer_id, None)
  4405. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  4406. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  4407. # print's flag instead of inheriting it.
  4408. print_dispatch_context.adopt(printer_id)
  4409. # Cancel any active bed cooldown waiter for this printer
  4410. if _bed_cool_waiters.pop(printer_id, None):
  4411. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  4412. # Clear cached cover images so the new print's thumbnail is fetched fresh
  4413. from backend.app.api.routes.printers import clear_cover_cache
  4414. clear_cover_cache(printer_id)
  4415. await ws_manager.send_print_start(printer_id, data)
  4416. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  4417. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  4418. # MQTT relay - publish print start
  4419. try:
  4420. printer_info = printer_manager.get_printer(printer_id)
  4421. if printer_info:
  4422. await mqtt_relay.on_print_start(
  4423. printer_id,
  4424. printer_info.name,
  4425. printer_info.serial_number,
  4426. data.get("filename", ""),
  4427. data.get("subtask_name", ""),
  4428. )
  4429. except Exception:
  4430. pass # Don't fail print start callback if MQTT fails
  4431. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  4432. # and mapping, and the seeded tray-change log.
  4433. #
  4434. # Unconditional, for both inventory backends. This only *captures* — the
  4435. # writing is still split, with the internal tracker skipped at completion
  4436. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  4437. # carries its plate-scoped 3MF figures and stored mapping, but not the
  4438. # tray-change log, and that log is the only record of which spool fed
  4439. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  4440. # it on one side only would leave Spoolman users with the mid-print
  4441. # restart bug this fixes for everyone else.
  4442. try:
  4443. async with async_session() as db:
  4444. from backend.app.api.routes.settings import get_setting
  4445. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  4446. _spoolman_on = await get_setting(db, "spoolman_enabled")
  4447. await usage_on_print_start(
  4448. printer_id,
  4449. data,
  4450. printer_manager,
  4451. db=db,
  4452. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  4453. )
  4454. except Exception as e:
  4455. logger.warning("Usage tracker on_print_start failed: %s", e)
  4456. # Track if notification was sent (to avoid sending twice)
  4457. notification_sent = False
  4458. # Smart plug automation: turn on plug when print starts
  4459. try:
  4460. async with async_session() as db:
  4461. await smart_plug_manager.on_print_start(printer_id, db)
  4462. except Exception as e:
  4463. logger.warning("Smart plug on_print_start failed: %s", e)
  4464. async with async_session() as db:
  4465. from backend.app.models.printer import Printer
  4466. from backend.app.services.bambu_ftp import list_files_async
  4467. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4468. printer = result.scalar_one_or_none()
  4469. # Plate detection check - pause if objects detected on build plate
  4470. logger.info(
  4471. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  4472. )
  4473. if printer and printer.plate_detection_enabled:
  4474. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  4475. # Release the pooled DB connection before the plate-detection camera
  4476. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  4477. # printer SELECT has run so far — nothing to persist — so this commit
  4478. # is a data-noop that ends the read transaction and returns the
  4479. # connection to the pool during the I/O (issue #2572). expire_on_commit
  4480. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  4481. # archive lookups below re-acquire a fresh connection on next execute.
  4482. await db.commit()
  4483. try:
  4484. from backend.app.services.plate_detection import check_plate_empty
  4485. # Build ROI tuple from printer settings if available
  4486. roi = None
  4487. if all(
  4488. [
  4489. printer.plate_detection_roi_x is not None,
  4490. printer.plate_detection_roi_y is not None,
  4491. printer.plate_detection_roi_w is not None,
  4492. printer.plate_detection_roi_h is not None,
  4493. ]
  4494. ):
  4495. roi = (
  4496. printer.plate_detection_roi_x,
  4497. printer.plate_detection_roi_y,
  4498. printer.plate_detection_roi_w,
  4499. printer.plate_detection_roi_h,
  4500. )
  4501. # The light is held, not switched, so a live view opened
  4502. # meanwhile keeps it when the check lets go (SP-C11). Every
  4503. # printer, whatever the camera light mode: detection needs it.
  4504. plate_photo_data = None
  4505. objects_detected = False
  4506. check_failure: str | None = None
  4507. async with camera_light(printer, any_mode=True, settle=2.5):
  4508. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  4509. plate_result = await check_plate_empty(
  4510. printer_id=printer_id,
  4511. ip_address=printer.ip_address,
  4512. access_code=printer.access_code,
  4513. model=printer.model,
  4514. include_debug_image=False,
  4515. external_camera_url=printer.external_camera_url,
  4516. external_camera_type=printer.external_camera_type,
  4517. use_external=printer.external_camera_enabled,
  4518. roi=roi,
  4519. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  4520. )
  4521. # No reference to compare against is a check that did not
  4522. # run either: say so rather than call the plate empty.
  4523. check_failure = getattr(plate_result, "failure_reason", None) or (
  4524. "not_calibrated" if plate_result.needs_calibration else None
  4525. )
  4526. objects_detected = not check_failure and not plate_result.is_empty
  4527. if objects_detected:
  4528. # Objects detected - pause the print!
  4529. logger.warning(
  4530. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  4531. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  4532. )
  4533. pause_client = printer_manager.get_client(printer_id)
  4534. if pause_client:
  4535. pause_client.pause_print()
  4536. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  4537. # Snapshot while the light's still on — restoring it first
  4538. # would leave the notification with a dark photo.
  4539. try:
  4540. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  4541. except Exception as snap_err:
  4542. logger.warning(
  4543. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  4544. )
  4545. if objects_detected:
  4546. # Send notification about plate not empty
  4547. await ws_manager.broadcast(
  4548. {
  4549. "type": "plate_not_empty",
  4550. "printer_id": printer_id,
  4551. "printer_name": printer.name,
  4552. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  4553. }
  4554. )
  4555. # Also send push notification
  4556. try:
  4557. await notification_service.on_plate_not_empty(
  4558. printer_id=printer_id,
  4559. printer_name=printer.name,
  4560. db=db,
  4561. difference_percent=plate_result.difference_percent,
  4562. image_data=plate_photo_data,
  4563. )
  4564. except Exception as notif_err:
  4565. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  4566. elif check_failure:
  4567. logger.warning(
  4568. "[PLATE CHECK] Plate check could not run for printer %s (%s): %s; proceeding with print",
  4569. printer_id,
  4570. check_failure,
  4571. plate_result.message,
  4572. )
  4573. await _announce_plate_check_failed(printer_id, printer.name, check_failure)
  4574. else:
  4575. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  4576. except Exception as plate_err:
  4577. # Don't block print on plate detection errors
  4578. logger.warning(
  4579. "[PLATE CHECK] Plate check could not run for printer %s: %s; proceeding with print",
  4580. printer_id,
  4581. plate_err,
  4582. )
  4583. await _announce_plate_check_failed(printer_id, printer.name, "error")
  4584. if not printer:
  4585. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  4586. if not notification_sent:
  4587. await _send_print_start_notification(printer_id, data, logger=logger)
  4588. return
  4589. # Skip the printer's own jobs — a calibration run is not a user's print.
  4590. # See is_internal_printer_job for what counts and why both fields are
  4591. # tested; the pressure-advance line reports as a subtask name with no
  4592. # /usr/ path, which the old prefix-only test here missed entirely.
  4593. #
  4594. # No notification either. The event describes the printer calibrating
  4595. # itself, so "Print started" is as wrong as the archive was, and the
  4596. # matching completion is suppressed in on_print_complete for the same
  4597. # reason. Checked before the auto-archive switches, whose "off" path
  4598. # still notifies.
  4599. # A /usr/ path is the printer's own file. A name alone is not proof: a
  4600. # print Bambuddy dispatched is never one, whatever it is called.
  4601. # Dispatched = an expected print, or, after a restart that lost those,
  4602. # a queue job printing on the printer.
  4603. if is_internal_printer_job(data.get("filename", ""), data.get("subtask_name", "")) and (
  4604. (data.get("filename") or "").startswith("/usr/")
  4605. or not await _dispatched_by_bambuddy(db, printer_id, data.get("filename", ""), data.get("subtask_name", ""))
  4606. ):
  4607. logger.info(
  4608. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4609. data.get("filename", ""),
  4610. data.get("subtask_name", ""),
  4611. )
  4612. return
  4613. # The global switch is the master: off, no printer archives prints
  4614. # started outside Bambuddy; on, each printer's own switch decides.
  4615. from backend.app.api.routes.settings import get_setting
  4616. _global_auto_archive = await get_setting(db, "auto_archive")
  4617. archives_prints = printer.auto_archive and (
  4618. _global_auto_archive is None or _global_auto_archive.lower() == "true"
  4619. )
  4620. if not archives_prints:
  4621. # auto-archive disabled — check if there's an expected print (dispatched
  4622. # by BamBuddy via queue/reprint) that already has an archive to promote.
  4623. # If so, fall through to the expected-print handling below so the archive
  4624. # is tracked in _active_prints and usage tracking works at completion.
  4625. _fn = data.get("filename", "")
  4626. _sn = data.get("subtask_name", "")
  4627. _check_keys: list[tuple[int, str]] = []
  4628. if _sn:
  4629. _check_keys += [
  4630. (printer_id, _sn),
  4631. (printer_id, f"{_sn}.3mf"),
  4632. (printer_id, f"{_sn}.gcode.3mf"),
  4633. ]
  4634. if _fn:
  4635. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4636. _check_keys.append((printer_id, _base_fn))
  4637. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4638. _check_keys += [
  4639. (printer_id, _no_archive_base),
  4640. (printer_id, f"{_no_archive_base}.3mf"),
  4641. ]
  4642. _has_expected = any(k in _expected_prints for k in _check_keys)
  4643. if not _has_expected:
  4644. # No expected print — truly external print (started from slicer/touchscreen)
  4645. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  4646. if not notification_sent:
  4647. _no_archive_creator: int | None = None
  4648. for _key in _check_keys:
  4649. _expected_prints.pop(_key, None)
  4650. _expected_print_registered_at.pop(_key, None)
  4651. popped_creator = _expected_print_creators.pop(_key, None)
  4652. if _no_archive_creator is None:
  4653. _no_archive_creator = popped_creator
  4654. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4655. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4656. return
  4657. else:
  4658. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4659. # Get the filename and subtask_name
  4660. filename = data.get("filename", "")
  4661. subtask_name = data.get("subtask_name", "")
  4662. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4663. # present, it lets us match an archive across a backend restart (#972):
  4664. # same id → same print → resume the existing row instead of cancelling
  4665. # it and recreating from scratch (which loses started_at). Treat "0"
  4666. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4667. raw_mqtt = data.get("raw_data") or {}
  4668. subtask_id = raw_mqtt.get("subtask_id")
  4669. if subtask_id is not None:
  4670. subtask_id = str(subtask_id).strip()
  4671. if subtask_id in ("", "0"):
  4672. subtask_id = None
  4673. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4674. if not filename and not subtask_name:
  4675. # Send notification without archive data (no filename)
  4676. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4677. if not notification_sent:
  4678. await _send_print_start_notification(printer_id, data, logger=logger)
  4679. return
  4680. # Check if this is an expected print from reprint/scheduled
  4681. expected_keys = _expected_print_keys(printer_id, filename, subtask_name)
  4682. expected_archive_id = None
  4683. # Who queued it, taken with the entries it was registered beside: left
  4684. # behind once those are gone (the archive deleted mid-dispatch, or the
  4685. # start notification already sent), the expiry never saw it, and an
  4686. # unrelated later print of that name was attributed to that user (EP-2).
  4687. fallback_creator = None
  4688. for key in expected_keys:
  4689. expected_archive_id = _expected_prints.pop(key, None)
  4690. _expected_print_registered_at.pop(key, None)
  4691. if expected_archive_id:
  4692. # Clean up other possible keys for this print
  4693. for other_key in expected_keys:
  4694. _expected_prints.pop(other_key, None)
  4695. _expected_print_registered_at.pop(other_key, None)
  4696. creator = _expected_print_creators.pop(other_key, None)
  4697. if fallback_creator is None:
  4698. fallback_creator = creator
  4699. break
  4700. if expected_archive_id:
  4701. # This is a reprint/scheduled print - use existing archive, don't create new one
  4702. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4703. # Bambuddy dispatched it: the kill switch's fast path keeps it as
  4704. # Bambuddy's once the expected entry is consumed here.
  4705. _owned_print_archive_ids.add(expected_archive_id)
  4706. from backend.app.models.archive import PrintArchive
  4707. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4708. archive = result.scalar_one_or_none()
  4709. # Deleted after this handler loaded it (the plate check waits
  4710. # seconds) but before the route forgot the expected print: the
  4711. # archive the route kept or deleted is left as the route left it.
  4712. if archive and await _printer_gone(db, printer_id):
  4713. logger.info(
  4714. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4715. )
  4716. await forget_printer(printer_id)
  4717. return
  4718. if archive:
  4719. # As it was before this adoption: put back if the printer turns
  4720. # out to have been deleted while it was adopted (below).
  4721. before_adoption = {
  4722. attr.columns[0].name: getattr(archive, attr.key)
  4723. for attr in sa_inspect(PrintArchive).column_attrs
  4724. if attr.key != "id"
  4725. }
  4726. # Update archive status to printing
  4727. archive.status = "printing"
  4728. archive.started_at = datetime.now(timezone.utc)
  4729. # The previous run's outcome is not this one's: a reprint that
  4730. # completes must not keep showing why the last one failed.
  4731. archive.failure_reason = None
  4732. archive.completed_at = None
  4733. # The previous run's answer is still on this row and the
  4734. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4735. # so without a reset the second run inherits the first run's
  4736. # verdict: no prompt at all, and a green "good" badge on a run
  4737. # nobody ever judged.
  4738. if archive.confirm_requested:
  4739. archive.user_verdict = None
  4740. archive.user_verdict_source = None
  4741. archive.user_verdict_at = None
  4742. archive.confirm_token = None
  4743. archive.confirm_token_used_at = None
  4744. # Reprint of an archive reuses the source row. Without resetting
  4745. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4746. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4747. # extracts the *original* print's last frame, which then ships in
  4748. # the completion notification (#1707). Clear the path so the
  4749. # scanner runs fresh; also unlink the old video file so reprints
  4750. # don't accumulate orphans in the archive directory. Photos list
  4751. # is left alone — accumulating one finish photo per run is fine.
  4752. # The print-start baseline (#2704) is stale for the same reason:
  4753. # it describes the printer before the previous run. The capture
  4754. # below overwrites it, but clear it here too so an early failure
  4755. # can't leave the scan diffing against the wrong snapshot.
  4756. #
  4757. # Unlinked only when it is the same plate printing again. Every
  4758. # plate of a Send All shares this archive, and the video on it
  4759. # can be the only copy of another plate's run -- the printer's
  4760. # was deleted once it attached (#3275). That one is left in the
  4761. # archive directory, which goes with the archive. A video whose
  4762. # plate is not on record (attached by hand, or before the
  4763. # column existed) is kept too where the 3MF has other plates,
  4764. # or cannot be read: nothing tells it apart from another plate's,
  4765. # and keeping costs one file where deleting can cost the only
  4766. # copy. On an archive with exactly one plate it is that plate's.
  4767. archive.timelapse_baseline = None
  4768. stale_timelapse_relpath = archive.timelapse_path
  4769. stale_timelapse_plate_id = archive.timelapse_plate_id
  4770. starting_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4771. if stale_timelapse_relpath:
  4772. archive.timelapse_path = None
  4773. archive.timelapse_plate_id = None
  4774. stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
  4775. if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
  4776. from backend.app.services.archive import plate_indexes_in_3mf
  4777. plates = await asyncio.to_thread(
  4778. plate_indexes_in_3mf,
  4779. app_settings.base_dir / archive.file_path, # SEC-PATH-OK: stored relative archive path
  4780. )
  4781. stale_is_this_plates = len(plates) == 1
  4782. if stale_timelapse_relpath and not stale_is_this_plates:
  4783. logger.info(
  4784. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4785. stale_timelapse_relpath,
  4786. stale_timelapse_plate_id,
  4787. expected_archive_id,
  4788. starting_plate_id,
  4789. )
  4790. # The video is deleted once the adoption stands (below).
  4791. delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
  4792. # Persist a restart-stable id so a later restart resumes this
  4793. # archive by subtask_id instead of name-matching + duplicating
  4794. # it (#1485). The printer often hasn't echoed subtask_id back
  4795. # this soon after dispatch, so fall back to the id Bambuddy
  4796. # minted when it sent the print command. Scoped to this
  4797. # expected-print branch on purpose: an expected match means
  4798. # Bambuddy dispatched this exact print in this process, so the
  4799. # client's last-dispatch id genuinely belongs to it — using it
  4800. # for an externally-started print could mis-tag the archive.
  4801. effective_subtask_id = subtask_id
  4802. if not effective_subtask_id:
  4803. _client = printer_manager.get_client(printer_id)
  4804. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4805. if _dispatched:
  4806. effective_subtask_id = str(_dispatched).strip() or None
  4807. # Update on first-set OR on reprint (the queue dispatcher mints
  4808. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4809. # the rewrite for reprints leaves the archive holding the FIRST
  4810. # run's id; if MQTT then reconnects mid-print, the reconciler
  4811. # (#1542) compares the stale stored id against the printer's
  4812. # live id, sees a mismatch, and synthesises a bogus PRINT
  4813. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4814. # in #1807. Inequality check preserves the noop-on-stable-push
  4815. # behaviour the earlier `not archive.subtask_id` guard provided.
  4816. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4817. archive.subtask_id = effective_subtask_id
  4818. # #1403 follow-up: VP-queue archives are created with
  4819. # printer_id=None at queue-add time (we don't know which
  4820. # printer will run the job yet). When the print actually
  4821. # starts on a specific printer the expected-archive lookup
  4822. # used to skip this assignment, leaving printer_id=None
  4823. # forever — which then disables the "Scan for timelapse"
  4824. # button in ArchivesPage (gated on !archive.printer_id).
  4825. if archive.printer_id != printer_id:
  4826. archive.printer_id = printer_id
  4827. adopting_id = archive.id # a rollback expires the object
  4828. try:
  4829. await db.commit()
  4830. except (IntegrityError, StaleDataError):
  4831. # The archive stays unchanged, or is gone: "delete archives"
  4832. # removed the row under the adoption, which then matched no
  4833. # row (StaleDataError) rather than being refused.
  4834. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4835. return
  4836. raise
  4837. # The printer can be deleted between the check above and this
  4838. # commit (the route's transaction lasts seconds), and the commit
  4839. # then adopted the archive anyway: status, verdict and timelapse
  4840. # changed, and the deleted printer's id written on a row the
  4841. # route had detached or never touched. Undo the adoption.
  4842. if await _printer_gone(db, printer_id):
  4843. logger.info(
  4844. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4845. printer_id,
  4846. archive.id,
  4847. )
  4848. # Everything as before this adoption. The printer it had
  4849. # then stays, unless it was the deleted one: the route
  4850. # detached that row (kept) or deleted it (no row matches).
  4851. previous_printer = before_adoption["printer_id"]
  4852. await db.execute(
  4853. update(PrintArchive)
  4854. .where(PrintArchive.id == archive.id)
  4855. .values(
  4856. {
  4857. **before_adoption,
  4858. "printer_id": None if previous_printer == printer_id else previous_printer,
  4859. }
  4860. )
  4861. )
  4862. await db.commit()
  4863. await forget_printer(printer_id)
  4864. return
  4865. await _drop_replaced_plate_videos(
  4866. db,
  4867. archive.id,
  4868. starting_plate_id,
  4869. stale_timelapse_relpath if delete_stale_video else None,
  4870. logger,
  4871. )
  4872. # Track as active print
  4873. _bind_active_print(printer_id, archive.id, archive.filename, filename, subtask_name)
  4874. await _open_run_for(archive.id, printer_id, subtask_id)
  4875. # Start timelapse session if external camera is enabled (#1353).
  4876. # Queue / VP-dispatched prints land here in the expected-archive
  4877. # branch and used to skip start_session entirely — frames were
  4878. # never captured and the post-print stitch silently returned None.
  4879. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4880. # Inject ams_mapping into usage tracker session — the session was created
  4881. # before expected-print promotion, so it may have ams_mapping=None when
  4882. # the MQTT request topic subscription failed (common on P1S/A1).
  4883. _stored_map = _print_ams_mappings.get((printer_id, expected_archive_id))
  4884. _stored_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4885. if _stored_map or _stored_plate_id is not None:
  4886. try:
  4887. from backend.app.services.usage_tracker import _active_sessions
  4888. _ut_session = _active_sessions.get(printer_id)
  4889. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4890. _ut_session.ams_mapping = _stored_map
  4891. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4892. # plate_id injection covers direct-Print of plate N of a multi-plate
  4893. # 3MF — queue prints already capture it via the on_print_start queue
  4894. # lookup, but direct-Print never goes through the queue (#1697).
  4895. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4896. _ut_session.plate_id = _stored_plate_id
  4897. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4898. except Exception:
  4899. pass
  4900. # Set up energy tracking (#941: persist start on archive row)
  4901. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4902. await ws_manager.send_archive_updated(
  4903. {
  4904. "id": archive.id,
  4905. "status": "printing",
  4906. }
  4907. )
  4908. # Send notification with archive data (reprint/scheduled)
  4909. if not notification_sent:
  4910. # Use archive's created_by_id; fall back to the creator registered via
  4911. # register_expected_print (handles library-file-based queue items where
  4912. # the freshly-created archive has no created_by_id yet), taken above.
  4913. archive_data = {
  4914. "print_time_seconds": _run_print_time_seconds(archive, printer_id),
  4915. "created_by_id": archive.created_by_id or fallback_creator,
  4916. }
  4917. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4918. # Extract printable objects from the archived 3MF file
  4919. _load_objects_from_archive(archive, printer_id, logger)
  4920. if archive.file_path:
  4921. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  4922. # Store Spoolman tracking data for per-filament usage reporting
  4923. try:
  4924. await _store_spoolman_print_data(
  4925. printer_id,
  4926. archive.id,
  4927. archive.file_path,
  4928. db,
  4929. printer_manager,
  4930. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4931. plate_id=_get_start_plate_id(printer_id, archive.id),
  4932. )
  4933. except Exception as e:
  4934. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4935. # Price the print from its spools now rather than only at completion (#3261)
  4936. _schedule_archive_cost_estimate(
  4937. printer_id,
  4938. archive.id,
  4939. printer_manager,
  4940. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4941. plate_id=_get_start_plate_id(printer_id, archive.id),
  4942. session_factory=async_session,
  4943. )
  4944. # Capture timelapse file baseline for snapshot-diff on completion
  4945. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4946. # hit this branch — without the baseline the completion-time scan
  4947. # falls into its "take baseline now" fallback, which snapshots
  4948. # AFTER the new MP4 already exists and never matches a diff
  4949. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4950. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4951. await _forget_if_printer_gone(printer_id)
  4952. return # Skip creating a new archive
  4953. # The archive was deleted after the job was queued.
  4954. if not archives_prints:
  4955. # Only the expected print brought a printer that does not
  4956. # archive this far; with it gone, nothing is archived.
  4957. return
  4958. # Otherwise archive the print anew rather than drop it, so it still
  4959. # gets its notification, usage tracking and history.
  4960. logger.warning(
  4961. "Expected archive %s for printer %s no longer exists; archiving the print anew",
  4962. expected_archive_id,
  4963. printer_id,
  4964. )
  4965. # Check if there's already a "printing" archive for this printer/file
  4966. # This prevents duplicates when backend restarts during an active print
  4967. from backend.app.models.archive import PrintArchive
  4968. existing_archive: PrintArchive | None = None
  4969. resumed_by_run = False
  4970. # Best match: this job's run, open on the printer since the print
  4971. # started. The archive row is shared by every plate of it, and its
  4972. # printer, job id and status are the latest start's, which may be
  4973. # another printer's.
  4974. if subtask_id:
  4975. from backend.app.services.print_log import open_run_on_printer
  4976. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  4977. if run is not None and run.archive_id is not None:
  4978. existing_archive = await db.scalar(
  4979. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  4980. )
  4981. resumed_by_run = existing_archive is not None
  4982. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4983. # across a backend restart for the same print, so this is the most
  4984. # reliable way to reattach. Only a row still printing: a cancelled one
  4985. # has been through completion (usage, history, notifications) already,
  4986. # and reopening it would count the print twice.
  4987. if subtask_id and existing_archive is None:
  4988. by_id = await db.execute(
  4989. select(PrintArchive)
  4990. .where(PrintArchive.printer_id == printer_id)
  4991. .where(PrintArchive.subtask_id == subtask_id)
  4992. .where(PrintArchive.status == "printing")
  4993. .order_by(PrintArchive.created_at.desc())
  4994. .limit(1)
  4995. )
  4996. existing_archive = by_id.scalar_one_or_none()
  4997. # Fallback match: name-based lookup. Kept as-is for prints whose
  4998. # subtask_id is missing ("0" / local / non-cloud prints).
  4999. if existing_archive is None:
  5000. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  5001. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  5002. # A print started from the printer's screen names its file in full,
  5003. # so the forms above double its extension. The file itself is the
  5004. # one exact match, and nothing looser is added (#3009).
  5005. if _subtask_is_the_file(subtask_name, filename):
  5006. archive_filenames.append(subtask_name)
  5007. existing = await db.execute(
  5008. select(PrintArchive)
  5009. .where(PrintArchive.printer_id == printer_id)
  5010. .where(PrintArchive.status == "printing")
  5011. .where(
  5012. or_(
  5013. PrintArchive.print_name == check_name,
  5014. PrintArchive.filename.in_(archive_filenames),
  5015. )
  5016. )
  5017. .order_by(PrintArchive.created_at.desc())
  5018. .limit(1)
  5019. )
  5020. existing_archive = existing.scalar_one_or_none()
  5021. if existing_archive:
  5022. # subtask_id match → always resume, regardless of age. Same print,
  5023. # just a backend restart.
  5024. subtask_match = resumed_by_run or bool(subtask_id and existing_archive.subtask_id == subtask_id)
  5025. if subtask_match:
  5026. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  5027. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  5028. await _open_run_for(existing_archive.id, printer_id, subtask_id)
  5029. _mark_owned_if_dispatched(existing_archive)
  5030. if await _run_needs_energy_start(existing_archive, printer_id, db):
  5031. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  5032. if not notification_sent:
  5033. archive_data = {
  5034. "print_time_seconds": _run_print_time_seconds(existing_archive, printer_id),
  5035. "created_by_id": existing_archive.created_by_id,
  5036. }
  5037. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5038. _load_objects_from_archive(existing_archive, printer_id, logger)
  5039. if existing_archive.file_path:
  5040. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  5041. return
  5042. # Name-match only (no subtask_id to anchor on): decide resume vs.
  5043. # stale from the printer's *current* progress, not wall-clock age.
  5044. # A genuinely long print used to trip a blind 4h cutoff and have its
  5045. # live archive cancelled + duplicated on every backend restart
  5046. # (#1485). If the printer reports real progress, this name-matched
  5047. # 'printing' archive IS that ongoing print — resume it whatever its
  5048. # age. Only treat it as a stale leftover when the printer clearly
  5049. # shows a different, freshly-started print: near-0% progress on an
  5050. # archive far too old to still be at 0%. Unknown progress (printer
  5051. # not connected) never cancels — resuming is the safe default.
  5052. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  5053. live_status = printer_manager.get_status(printer_id)
  5054. live_progress = getattr(live_status, "progress", None) if live_status else None
  5055. looks_stale = (
  5056. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  5057. )
  5058. # Two subtask ids are two prints, however young the archive: one
  5059. # whose completion was missed must not swallow the next print of
  5060. # the same file. Except Bambuddy's own reprint, which reuses the
  5061. # row and mints a fresh id (#1807): the id it last sent says so,
  5062. # and after a restart, which forgets it, this printer's queue job
  5063. # running the archive.
  5064. if (
  5065. not looks_stale
  5066. and subtask_id
  5067. and existing_archive.subtask_id
  5068. and existing_archive.subtask_id != subtask_id
  5069. ):
  5070. _client = printer_manager.get_client(printer_id)
  5071. _dispatched = str(getattr(_client, "last_dispatch_subtask_id", None) or "").strip()
  5072. if _dispatched:
  5073. looks_stale = _dispatched != subtask_id
  5074. else:
  5075. from backend.app.models.print_queue import PrintQueueItem as _PQI
  5076. queue_run = await db.scalar(
  5077. select(_PQI.id)
  5078. .where(_PQI.archive_id == existing_archive.id)
  5079. .where(_PQI.printer_id == printer_id)
  5080. .where(_PQI.status == "printing")
  5081. .limit(1)
  5082. )
  5083. looks_stale = queue_run is None
  5084. if looks_stale:
  5085. logger.warning(
  5086. "Found stale 'printing' archive %s (age: %s, printer progress %s%%, subtask %s, printer reports %s)"
  5087. " — marking cancelled and creating new archive",
  5088. existing_archive.id,
  5089. archive_age,
  5090. live_progress,
  5091. existing_archive.subtask_id,
  5092. subtask_id,
  5093. )
  5094. existing_archive.status = "cancelled"
  5095. # Canonical key, not a sentence (issue #2974). "No status update
  5096. # received" is what both stale paths actually observed; which of
  5097. # the two it was is already carried by ``status`` -- cancelled
  5098. # here, the reconciled outcome at the reconnect site -- so one
  5099. # key loses no information and gives the Statistics breakdown a
  5100. # single bucket instead of two untranslatable prose strings.
  5101. existing_archive.failure_reason = "noStatusUpdate"
  5102. # And its run, as before runs were opened at the start: a new
  5103. # print starts on the printer, so whatever is open there ended
  5104. # unseen. Left open, the next reconnect would close it again.
  5105. from backend.app.services.print_log import discard_open_runs
  5106. discarded = await discard_open_runs(db, printer_id)
  5107. await db.commit()
  5108. await _announce_discarded_runs(discarded, printer_id)
  5109. # Its print keys go with it; the new archive registers its own.
  5110. for _key in [k for k, v in _active_prints.items() if v == existing_archive.id and k[0] == printer_id]:
  5111. del _active_prints[_key]
  5112. # Fall through to create new archive (don't return)
  5113. else:
  5114. logger.info(
  5115. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  5116. )
  5117. # Track this as the active print
  5118. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  5119. _mark_owned_if_dispatched(existing_archive)
  5120. # Attach subtask_id retroactively so future restarts can resume.
  5121. # Compare for inequality (not "is empty") to also pick up reprint
  5122. # dispatches that mint a fresh id — see #1807 for the bogus
  5123. # "Print Stopped" the strict-empty guard caused on reconnect.
  5124. if subtask_id and existing_archive.subtask_id != subtask_id:
  5125. existing_archive.subtask_id = subtask_id
  5126. await db.commit()
  5127. await _open_run_for(existing_archive.id, printer_id, subtask_id)
  5128. # Also set up energy tracking if not already tracked (#941: persisted column)
  5129. if await _run_needs_energy_start(existing_archive, printer_id, db):
  5130. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  5131. # Send notification with archive data (existing archive)
  5132. if not notification_sent:
  5133. archive_data = {
  5134. "print_time_seconds": _run_print_time_seconds(existing_archive, printer_id),
  5135. "created_by_id": existing_archive.created_by_id,
  5136. }
  5137. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5138. # Extract printable objects from the archived 3MF file
  5139. _load_objects_from_archive(existing_archive, printer_id, logger)
  5140. if existing_archive.file_path:
  5141. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  5142. return
  5143. # Build list of possible 3MF filenames to try
  5144. possible_names = []
  5145. # Bambu printers typically store files as "Name.gcode.3mf"
  5146. # The subtask_name is usually the best source for the filename
  5147. if subtask_name:
  5148. if _subtask_is_the_file(subtask_name, filename):
  5149. # A print started from the printer's own screen reports the
  5150. # file's full name, extension included. That is the file, so
  5151. # no extension is appended to it (#3009).
  5152. possible_names.append(subtask_name)
  5153. else:
  5154. # Try common Bambu naming patterns
  5155. possible_names.append(f"{subtask_name}.gcode.3mf")
  5156. possible_names.append(f"{subtask_name}.3mf")
  5157. # Try original filename with .3mf extension
  5158. if filename:
  5159. # Extract just the filename part, not the full path
  5160. fname = filename.split("/")[-1] if "/" in filename else filename
  5161. if fname.endswith(".3mf"):
  5162. possible_names.append(fname)
  5163. elif fname.endswith(".gcode"):
  5164. base = fname.rsplit(".", 1)[0]
  5165. possible_names.append(f"{base}.gcode.3mf")
  5166. possible_names.append(f"{base}.3mf")
  5167. else:
  5168. possible_names.append(f"{fname}.gcode.3mf")
  5169. possible_names.append(f"{fname}.3mf")
  5170. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  5171. space_variants = []
  5172. for name in possible_names:
  5173. if " " in name:
  5174. space_variants.append(name.replace(" ", "_"))
  5175. possible_names.extend(space_variants)
  5176. # Remove duplicates while preserving order
  5177. seen = set()
  5178. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  5179. logger.info("Trying filenames: %s", possible_names)
  5180. # Release the pooled DB connection before the 3MF FTP download. Reaching
  5181. # here means none of the expected-/existing-archive write branches ran
  5182. # (they all return earlier) — only SELECTs have executed on this path, so
  5183. # this commit persists nothing; it ends the read transaction so the
  5184. # connection returns to the pool during the download. That download tries
  5185. # up to five remote paths per candidate filename with retry/backoff and
  5186. # can run for minutes under FTP contention; holding the session across it
  5187. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  5188. # work runs during the download — the new-archive writes below re-acquire
  5189. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  5190. await db.commit()
  5191. # Try to find and download the 3MF file
  5192. temp_path = None
  5193. downloaded_filename = None
  5194. # Cache check: cover endpoint may have already pulled this 3MF during
  5195. # the print (frontend opens the card and shows the thumbnail) — reuse
  5196. # that file instead of re-downloading 36MB over the same FTP link that
  5197. # just served it (#972). The cache keys on a normalized filename so
  5198. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  5199. for try_filename in possible_names:
  5200. if not try_filename.endswith(".3mf"):
  5201. continue
  5202. cached = get_cached_3mf(printer_id, try_filename)
  5203. if cached:
  5204. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  5205. temp_path = cached
  5206. downloaded_filename = try_filename
  5207. break
  5208. # Does this printer keep the sliced file somewhere FTPS can reach? On
  5209. # H2-series and P2S the answer is routinely no — the file stays on
  5210. # internal eMMC and port 990 only ever serves external storage — and
  5211. # then the whole sweep below (six filenames x five directories x four
  5212. # retries, then the directory walk) is ~110 connections that cannot
  5213. # succeed. Skip it and say why (#2780).
  5214. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  5215. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  5216. # running rather than because the file is somewhere unreachable. The
  5217. # distinction is the whole of #2957: one is permanent, the other clears
  5218. # in minutes with the file still sitting on the printer.
  5219. blocked_by_ftps_cooloff = False
  5220. # Set when a probe reached the printer and still came back without the
  5221. # file -- a timeout mid-transfer, a refused connection, anything that is
  5222. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  5223. # caught by name below, so a file that genuinely is not on the card
  5224. # leaves this False and schedules nothing. Anything else means the
  5225. # transfer, not the file, is what failed, and that does not last (#3063).
  5226. ftp_transfer_failed = False
  5227. # The narrower case of the above: the directory walk *listed* a file
  5228. # for this print and could not fetch it, so the file is on the card
  5229. # under a name that matches. The only failure that rules out an
  5230. # earlier run's 3MF standing in for it (#3307).
  5231. walk_transfer_failed = False
  5232. # Paths the sweep reached and could not transfer -- a timeout, not a
  5233. # 550. The directory walk lists the same folders and would download
  5234. # the same file again: on a slow A1 that was a second 300 s on the
  5235. # printer's one FTPS slot, at print start, for a file the recovery
  5236. # retry fetches with a deadline twice as long (#3308).
  5237. sweep_failed_paths: set[str] = set()
  5238. # The print's name, for a fallback archive whose `subtask_name` the
  5239. # plate guard below had to disown. Display only, and deliberately kept
  5240. # apart from `subtask_name`: that variable is what every file lookup
  5241. # here is built from, and once a name has been shown to fetch another
  5242. # plate's 3MF it must not key `_active_prints` either, or the cover
  5243. # endpoint hands the same contradicted file to
  5244. # `_recover_fallback_archive` and fills the row in with it (#3126).
  5245. display_name_after_plate_reject: str | None = None
  5246. # Get FTP retry settings
  5247. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  5248. # ...but "the printer put it on eMMC" is where it went, not whether we
  5249. # can read it. An H2D with a card in mirrors the job to /cache and
  5250. # serves it happily, and skipping on the URL alone cost that reporter
  5251. # every archive for two days (#2856). So ask the printer instead of
  5252. # guessing: the dispatch named the exact file, which is one connection
  5253. # walking five paths rather than the sweep's ~110. Only when the probe
  5254. # comes back empty does the verdict's reason stand.
  5255. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  5256. if ftps_handshake_blocked(printer.ip_address):
  5257. # Deliberately NOT recorded as a cool-off give-up. This branch
  5258. # only runs on an unreachable verdict, and that verdict is the
  5259. # honest, permanent reason the archive is empty — the probe was
  5260. # a long shot on top of it. Blaming the cool-off here would
  5261. # schedule a retry for a file sitting on internal eMMC, which is
  5262. # the sweep #2780 removed (#2957).
  5263. logger.debug(
  5264. "Not probing for %s on printer %s: its file service is not answering over TLS",
  5265. storage.probe_filename,
  5266. printer_id,
  5267. )
  5268. else:
  5269. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  5270. probe_path.parent.mkdir(parents=True, exist_ok=True)
  5271. try:
  5272. probe_hit = await download_file_try_paths_async(
  5273. printer.ip_address,
  5274. printer.access_code,
  5275. ftp_probe_paths(storage.probe_filename),
  5276. probe_path,
  5277. socket_timeout=ftp_timeout,
  5278. printer_model=printer.model,
  5279. )
  5280. except Exception as e:
  5281. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  5282. probe_hit = False
  5283. if probe_hit:
  5284. downloaded_filename = storage.probe_filename
  5285. temp_path = probe_path
  5286. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  5287. # Naming the path, not just the file: a printer that keeps
  5288. # uploads around for weeks can serve a same-named copy of an
  5289. # earlier slice, and without the directory in the log that
  5290. # mismatch is invisible rather than merely rare (#1820).
  5291. logger.info(
  5292. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  5293. downloaded_filename,
  5294. probe_hit,
  5295. printer_id,
  5296. storage.reason,
  5297. )
  5298. if not storage.reachable and not downloaded_filename:
  5299. # Same opening words whether or not a probe ran, because that is
  5300. # the phrase support asks people to grep for — only the tail says
  5301. # which of the two happened.
  5302. logger.info(
  5303. "Skipping the 3MF lookup for printer %s: %s — %s",
  5304. printer_id,
  5305. storage.reason,
  5306. "no copy of it on external storage either"
  5307. if storage.probe_filename
  5308. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  5309. )
  5310. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  5311. if not try_filename.endswith(".3mf"):
  5312. continue
  5313. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  5314. # printers, so try it first — deferring it to last cost #972's reporter
  5315. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  5316. # landing on the path that actually had the file.
  5317. remote_paths = [
  5318. f"/{try_filename}",
  5319. f"/cache/{try_filename}",
  5320. f"/model/{try_filename}",
  5321. f"/data/{try_filename}",
  5322. f"/data/Metadata/{try_filename}",
  5323. ]
  5324. temp_path = app_settings.archive_dir / "temp" / try_filename
  5325. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5326. for remote_path in remote_paths:
  5327. if ftps_handshake_blocked(printer.ip_address):
  5328. # The printer's FTPS service is not completing a TLS
  5329. # handshake, so it has no path we could reach — walking the
  5330. # remaining candidates only re-runs the same failure
  5331. # (#2780). Fall through to the no-3MF archive now.
  5332. #
  5333. # Remember *why*, though. This is the one give-up that is
  5334. # temporary: the cool-off clears in minutes and the file was
  5335. # on the printer the whole time. The fallback archive is
  5336. # stamped with it so a retry can be scheduled, and so the
  5337. # Archives banner stops blaming storage (#2957).
  5338. blocked_by_ftps_cooloff = True
  5339. logger.warning(
  5340. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  5341. printer_id,
  5342. )
  5343. break
  5344. logger.debug("Trying FTP download: %s", remote_path)
  5345. try:
  5346. if ftp_retry_enabled:
  5347. downloaded = await with_ftp_retry(
  5348. download_file_async,
  5349. printer.ip_address,
  5350. printer.access_code,
  5351. remote_path,
  5352. temp_path,
  5353. timeout=ftp_timeout,
  5354. socket_timeout=ftp_timeout,
  5355. printer_model=printer.model,
  5356. max_retries=ftp_retry_count,
  5357. retry_delay=ftp_retry_delay,
  5358. operation_name=f"Download 3MF from {remote_path}",
  5359. cooloff_ip=printer.ip_address,
  5360. non_retry_exceptions=(FileNotOnPrinterError,),
  5361. )
  5362. else:
  5363. downloaded = await download_file_async(
  5364. printer.ip_address,
  5365. printer.access_code,
  5366. remote_path,
  5367. temp_path,
  5368. timeout=ftp_timeout,
  5369. socket_timeout=ftp_timeout,
  5370. printer_model=printer.model,
  5371. )
  5372. if downloaded:
  5373. downloaded_filename = try_filename
  5374. logger.info("Downloaded: %s", remote_path)
  5375. # Populate shared cache so the cover endpoint (if it
  5376. # runs next) doesn't refetch the same 36MB over FTP.
  5377. cache_3mf_download(printer_id, try_filename, temp_path)
  5378. break
  5379. # with_ftp_retry returns None once it has spent its budget,
  5380. # and download_file_async returns False on a timeout, so an
  5381. # exhausted transfer arrives here rather than as an
  5382. # exception (#3063).
  5383. ftp_transfer_failed = True
  5384. sweep_failed_paths.add(remote_path)
  5385. except FileNotOnPrinterError:
  5386. # 550 — file isn't at this path. Advance to next candidate
  5387. # without burning the retry budget.
  5388. logger.debug("3MF not at %s (550), trying next path", remote_path)
  5389. except Exception as e:
  5390. ftp_transfer_failed = True
  5391. sweep_failed_paths.add(remote_path)
  5392. logger.debug("FTP download failed for %s: %s", remote_path, e)
  5393. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  5394. break
  5395. # If still not found, try listing directories to find matching file
  5396. # Different printer models use different directory structures. Skipped
  5397. # when the printer's FTPS handshake is failing — the directory walk is
  5398. # five more connections that cannot get further than the download did.
  5399. if (
  5400. not downloaded_filename
  5401. and storage.reachable
  5402. and (filename or subtask_name)
  5403. and not ftps_handshake_blocked(printer.ip_address)
  5404. ):
  5405. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  5406. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  5407. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  5408. # Every folder is listed before one file is picked, so a file named
  5409. # for the print in a later folder wins over one that merely
  5410. # contains the name in an earlier folder.
  5411. listed_paths: list[str] = []
  5412. for search_dir in search_dirs:
  5413. try:
  5414. dir_files = await list_files_async(
  5415. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  5416. )
  5417. except Exception as e:
  5418. logger.debug("Failed to list %s: %s", search_dir, e)
  5419. continue
  5420. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  5421. if threemf_files:
  5422. logger.info(
  5423. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  5424. )
  5425. listed_paths += [
  5426. posixpath.join(search_dir, f.get("name", "")) for f in dir_files if not f.get("is_directory")
  5427. ]
  5428. for remote_full_path in _3mf_files_for_print(listed_paths, search_term):
  5429. if remote_full_path in sweep_failed_paths:
  5430. # Listed for this print, and its transfer already failed:
  5431. # the same as a failed walk download, without spending a
  5432. # second deadline on it. Skipping it cannot hand the walk a
  5433. # look-alike: while a file of the print's own name is
  5434. # listed, files that merely contain the name are not.
  5435. logger.info(
  5436. "Not downloading %s again: its transfer already failed; the recovery retry will fetch it",
  5437. remote_full_path,
  5438. )
  5439. walk_transfer_failed = True
  5440. continue
  5441. fname = posixpath.basename(remote_full_path)
  5442. logger.info("Found matching file: %s", remote_full_path)
  5443. temp_path = app_settings.archive_dir / "temp" / fname
  5444. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5445. try:
  5446. if ftp_retry_enabled:
  5447. downloaded = await with_ftp_retry(
  5448. download_file_async,
  5449. printer.ip_address,
  5450. printer.access_code,
  5451. remote_full_path,
  5452. temp_path,
  5453. timeout=ftp_timeout,
  5454. socket_timeout=ftp_timeout,
  5455. printer_model=printer.model,
  5456. max_retries=ftp_retry_count,
  5457. retry_delay=ftp_retry_delay,
  5458. operation_name=f"Download 3MF from {remote_full_path}",
  5459. cooloff_ip=printer.ip_address,
  5460. )
  5461. else:
  5462. downloaded = await download_file_async(
  5463. printer.ip_address,
  5464. printer.access_code,
  5465. remote_full_path,
  5466. temp_path,
  5467. timeout=ftp_timeout,
  5468. socket_timeout=ftp_timeout,
  5469. printer_model=printer.model,
  5470. )
  5471. except Exception as e:
  5472. logger.debug("Failed to download %s: %s", remote_full_path, e)
  5473. continue
  5474. if downloaded:
  5475. downloaded_filename = fname
  5476. logger.info("Found and downloaded: %s", remote_full_path)
  5477. cache_3mf_download(printer_id, fname, temp_path)
  5478. break
  5479. # The listing named the file, so it is on the card;
  5480. # only the transfer failed (#3063).
  5481. ftp_transfer_failed = True
  5482. walk_transfer_failed = True
  5483. # A "Print again" on the printer's screen names no file Bambuddy can
  5484. # find: only its history copy under a generic name, and the 3MF's
  5485. # internal title (#3307). When an earlier run of the same job was
  5486. # archived, its 3MF is the one being printed again. Not when the
  5487. # directory walk listed a file for this print and only its transfer
  5488. # failed: that file is on the card, and the retry fetches it. A
  5489. # cool-off or a failed sweep path is no such evidence -- the retry
  5490. # tries the same names, which this print's file never had.
  5491. reused_3mf_from: int | None = None
  5492. if not downloaded_filename and not walk_transfer_failed:
  5493. reported_layers = raw_mqtt.get("total_layer_num")
  5494. earlier = await _archived_3mf_for_repeat(
  5495. db,
  5496. printer_id,
  5497. subtask_name,
  5498. filename,
  5499. reported_layers if isinstance(reported_layers, int) and reported_layers > 0 else None,
  5500. )
  5501. if earlier is not None:
  5502. reuse_name = Path(earlier.filename or "").name or f"archive_{earlier.id}.3mf"
  5503. # Per printer: two printers reprinting the same job at once
  5504. # must not write one temp file (archive_print names the
  5505. # archive after original_filename, not this path).
  5506. reuse_path = app_settings.archive_dir / "temp" / f"reprint_{printer_id}_{reuse_name}"
  5507. try:
  5508. reuse_path.parent.mkdir(parents=True, exist_ok=True)
  5509. await asyncio.to_thread(shutil.copyfile, app_settings.base_dir / earlier.file_path, reuse_path)
  5510. except OSError as e:
  5511. # A copy that fails leaves the print the fallback archive
  5512. # it would have had, not no archive at all.
  5513. logger.warning("Could not copy the 3MF of archive %s for printer %s: %s", earlier.id, printer_id, e)
  5514. else:
  5515. temp_path = reuse_path
  5516. downloaded_filename = reuse_name
  5517. reused_3mf_from = earlier.id
  5518. cache_3mf_download(printer_id, reuse_name, temp_path)
  5519. logger.info(
  5520. "No 3MF on printer %s for %s (%s); using the 3MF of archive %s, an earlier run of the same job",
  5521. printer_id,
  5522. subtask_name,
  5523. filename,
  5524. earlier.id,
  5525. )
  5526. # Validate the downloaded 3MF actually matches the plate that's running
  5527. # (#1204): subtask_name lags across consecutive plates of the same model,
  5528. # so the first FTP candidate (built from subtask_name) can land on the
  5529. # previous plate's still-resident upload. Cross-check the slice_info
  5530. # plate index against the plate parsed from gcode_file (always fresh —
  5531. # it's the field whose change triggered this callback).
  5532. if downloaded_filename and temp_path:
  5533. expected_plate = parse_plate_id(filename)
  5534. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  5535. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  5536. logger.warning(
  5537. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  5538. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  5539. downloaded_filename,
  5540. actual_plate,
  5541. expected_plate,
  5542. subtask_name,
  5543. )
  5544. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  5545. retry_succeeded = False
  5546. if corrected_subtask and corrected_subtask != subtask_name:
  5547. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  5548. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  5549. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  5550. for remote_path in (
  5551. f"/{try_filename}",
  5552. f"/cache/{try_filename}",
  5553. f"/model/{try_filename}",
  5554. f"/data/{try_filename}",
  5555. f"/data/Metadata/{try_filename}",
  5556. ):
  5557. try:
  5558. if ftp_retry_enabled:
  5559. downloaded = await with_ftp_retry(
  5560. download_file_async,
  5561. printer.ip_address,
  5562. printer.access_code,
  5563. remote_path,
  5564. retry_temp_path,
  5565. timeout=ftp_timeout,
  5566. socket_timeout=ftp_timeout,
  5567. printer_model=printer.model,
  5568. max_retries=ftp_retry_count,
  5569. retry_delay=ftp_retry_delay,
  5570. operation_name=f"Re-download 3MF from {remote_path}",
  5571. cooloff_ip=printer.ip_address,
  5572. non_retry_exceptions=(FileNotOnPrinterError,),
  5573. )
  5574. else:
  5575. downloaded = await download_file_async(
  5576. printer.ip_address,
  5577. printer.access_code,
  5578. remote_path,
  5579. retry_temp_path,
  5580. timeout=ftp_timeout,
  5581. socket_timeout=ftp_timeout,
  5582. printer_model=printer.model,
  5583. )
  5584. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  5585. logger.info(
  5586. "[CALLBACK] Re-download succeeded with corrected name %s "
  5587. "(plate %s) — replacing wrong file",
  5588. try_filename,
  5589. expected_plate,
  5590. )
  5591. try:
  5592. temp_path.unlink(missing_ok=True)
  5593. except OSError:
  5594. pass
  5595. temp_path = retry_temp_path
  5596. downloaded_filename = try_filename
  5597. subtask_name = corrected_subtask
  5598. cache_3mf_download(printer_id, try_filename, temp_path)
  5599. retry_succeeded = True
  5600. break
  5601. elif downloaded:
  5602. # Wrong plate again — discard and keep trying
  5603. try:
  5604. retry_temp_path.unlink(missing_ok=True)
  5605. except OSError:
  5606. pass
  5607. except FileNotOnPrinterError:
  5608. continue
  5609. except Exception as e:
  5610. logger.debug("Re-download failed for %s: %s", remote_path, e)
  5611. if retry_succeeded:
  5612. break
  5613. # If the retry didn't find a matching file, drop the wrong 3MF
  5614. # so the no-3MF fallback below creates an archive whose name
  5615. # at least reflects the right plate.
  5616. if not retry_succeeded:
  5617. logger.warning(
  5618. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  5619. expected_plate,
  5620. )
  5621. try:
  5622. temp_path.unlink(missing_ok=True)
  5623. except OSError:
  5624. pass
  5625. temp_path = None
  5626. downloaded_filename = None
  5627. # Whatever the sweep's transport did earlier, it is not why
  5628. # this archive ends up empty: a 3MF downloaded fine, it was
  5629. # just the wrong plate. Retrying would re-fetch that same
  5630. # contradicted file under the same stale names and hand it
  5631. # to _recover_fallback_archive, which checks that a
  5632. # candidate is a readable 3MF but not which plate it is --
  5633. # so the row would be filled in with another plate's
  5634. # filament and cost, the exact swap #2957 removed (#3063).
  5635. ftp_transfer_failed = False
  5636. # Disown the name for *lookups*: it has just been shown to
  5637. # fetch another plate's 3MF, and it keys `_active_prints`
  5638. # below, where the cover endpoint's own download of that
  5639. # same name would find this archive and fill it in with the
  5640. # file we are discarding here.
  5641. #
  5642. # Keep it for the *title*, which is a separate question.
  5643. # ``swap_plate_suffix`` returns None both for a name that
  5644. # carries no "- Plate N" / "_plate_N" suffix and for no
  5645. # name at all, and those are not the same situation: a name
  5646. # without a suffix holds no stale plate number to be wrong
  5647. # about. Blanking both uses at once dropped the project
  5648. # name too, and the row fell through to the gcode_file path
  5649. # titled "plate_1" though the real name was in hand.
  5650. # #1204's own premise is consecutive plates *of the same
  5651. # model*, so the project part is right either way (#3126).
  5652. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  5653. subtask_name = corrected_subtask or ""
  5654. # Deleted while the 3MF was being fetched (that can take minutes): no
  5655. # archive, timelapse or tracking for a printer that will never report
  5656. # the print's end. forget_printer again: the download registered its
  5657. # 3MF cache entry after the delete cleared the id. (A delete committing
  5658. # while the archive is written is caught after its commit.)
  5659. if await _printer_gone(db, printer_id):
  5660. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  5661. await forget_printer(printer_id)
  5662. return
  5663. if not downloaded_filename or not temp_path:
  5664. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  5665. # Create a fallback archive without 3MF data so the print is still tracked
  5666. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  5667. try:
  5668. from backend.app.models.archive import PrintArchive
  5669. # Why the card is empty. The two temporary causes outrank the
  5670. # storage verdict because they say the sweep never got a fair
  5671. # answer: a cool-off skipped it at the transport, and a failed
  5672. # transfer reached the printer but never finished. Either way
  5673. # the file is still on the card, so reporting where the printer
  5674. # files its jobs would describe a setting that is not the
  5675. # problem (#2957, #3063).
  5676. if blocked_by_ftps_cooloff:
  5677. no_3mf_reason = REASON_FTPS_COOLOFF
  5678. elif storage.reachable and ftp_transfer_failed:
  5679. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  5680. else:
  5681. no_3mf_reason = storage.reason
  5682. # Derive print name from subtask_name or filename. The
  5683. # plate guard's disowned name comes second: it is a real name
  5684. # for a real print, and only the gcode_file path is left
  5685. # otherwise -- which titles the row "plate_1" (#3126).
  5686. print_name = subtask_name or display_name_after_plate_reject or filename
  5687. if print_name:
  5688. # Clean up the name (remove extensions, path parts)
  5689. print_name = print_name.split("/")[-1]
  5690. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  5691. else:
  5692. print_name = "Unknown Print"
  5693. # Recover estimated print time from MQTT (best-effort for notifications)
  5694. fallback_print_time = None
  5695. mqtt_remaining = data.get("remaining_time")
  5696. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5697. fallback_print_time = int(mqtt_remaining)
  5698. if fallback_print_time is None:
  5699. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  5700. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  5701. fallback_print_time = int(mc_remaining * 60)
  5702. # Best-effort filament metadata from MQTT — see
  5703. # _extract_filament_data_from_mqtt. Without this the fallback
  5704. # archive's filament fields stayed NULL even though the AMS
  5705. # state at print start was sitting right there in `data`.
  5706. # The slicer's ams_mapping (when present) narrows the result
  5707. # to slots actually used by the print (#1533).
  5708. mqtt_filament_meta = _extract_filament_data_from_mqtt(
  5709. data, _get_start_ams_mapping(data, printer_id, None)
  5710. )
  5711. # Create minimal archive entry
  5712. fallback_archive = PrintArchive(
  5713. printer_id=printer_id,
  5714. filename=filename or f"{print_name}.3mf",
  5715. file_path="", # Empty - no 3MF file available
  5716. file_size=0,
  5717. print_name=print_name,
  5718. print_time_seconds=fallback_print_time,
  5719. status="printing",
  5720. started_at=detected_at,
  5721. subtask_id=subtask_id,
  5722. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  5723. filament_type=mqtt_filament_meta.get("filament_type"),
  5724. filament_color=mqtt_filament_meta.get("filament_color"),
  5725. extra_data={
  5726. "no_3mf_available": True,
  5727. # Why the card is empty, when we know -- see above. The
  5728. # banner reads this to stop telling H2/P2 owners to
  5729. # switch on a setting that is already on and would not
  5730. # have helped (#2780).
  5731. "no_3mf_reason": no_3mf_reason,
  5732. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  5733. "_print_data": data,
  5734. },
  5735. )
  5736. db.add(fallback_archive)
  5737. try:
  5738. await db.commit()
  5739. except IntegrityError:
  5740. # Not "Failed to create fallback archive" below, and no
  5741. # start notification for a printer that is gone.
  5742. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  5743. return
  5744. raise
  5745. await db.refresh(fallback_archive)
  5746. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5747. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5748. return
  5749. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5750. # Track as active print
  5751. _bind_active_print(printer_id, fallback_archive.id, fallback_archive.filename, filename, subtask_name)
  5752. await _open_run_for(fallback_archive.id, printer_id, subtask_id)
  5753. # Record starting energy if smart plug available (#941: persisted column)
  5754. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5755. # Send WebSocket notification
  5756. await ws_manager.send_archive_created(
  5757. {
  5758. "id": fallback_archive.id,
  5759. "printer_id": fallback_archive.printer_id,
  5760. "filename": fallback_archive.filename,
  5761. "print_name": fallback_archive.print_name,
  5762. "status": fallback_archive.status,
  5763. }
  5764. )
  5765. # MQTT relay - publish archive created
  5766. try:
  5767. await mqtt_relay.on_archive_created(
  5768. archive_id=fallback_archive.id,
  5769. print_name=fallback_archive.print_name,
  5770. printer_name=printer.name,
  5771. status=fallback_archive.status,
  5772. )
  5773. except Exception:
  5774. pass # Don't fail if MQTT fails
  5775. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5776. try:
  5777. await _store_spoolman_print_data(
  5778. printer_id,
  5779. fallback_archive.id,
  5780. fallback_archive.file_path,
  5781. db,
  5782. printer_manager,
  5783. ams_mapping=_get_start_ams_mapping(data, printer_id, fallback_archive.id),
  5784. plate_id=_get_start_plate_id(printer_id, fallback_archive.id),
  5785. )
  5786. except Exception as e:
  5787. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5788. # Both temporary give-ups are worth coming back for, and for
  5789. # the same reason: the file is on the printer and the last look
  5790. # failed at the transport rather than finding nothing. One waits
  5791. # out the handshake block (#2957), the other waits for the
  5792. # printer to stop being busy (#3063). Deliberately not scheduled
  5793. # for a storage verdict: a file on internal eMMC will not appear
  5794. # at any FTPS path however long we wait, and retrying it is
  5795. # exactly the sweep #2780 removed.
  5796. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5797. # `possible_names`, not the raw MQTT strings: it is the exact
  5798. # list this flow just tried, already stripped of any path
  5799. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5800. # some firmware) and deduped.
  5801. _schedule_fallback_3mf_retry(
  5802. printer_id=printer_id,
  5803. archive_id=fallback_archive.id,
  5804. filenames=list(possible_names),
  5805. reason=no_3mf_reason,
  5806. )
  5807. # Send notification without archive data (file not found)
  5808. if not notification_sent:
  5809. await _send_print_start_notification(printer_id, data, logger=logger)
  5810. # The same baseline the other two on_print_start branches take
  5811. # (#2704), and last for the same reason they are: it lists the
  5812. # printer's timelapse directory, so a slow card must not delay
  5813. # the _active_prints registration, the energy reading, the
  5814. # archive-created event or the start notification above it.
  5815. #
  5816. # This branch never took one, so every no-3MF archive reached
  5817. # completion with no baseline in memory and none on the row, and
  5818. # the completion scan fell into its "snapshot now" fallback --
  5819. # which runs after the printer has written the video, so the new
  5820. # file landed inside the baseline and no diff ever matched
  5821. # (#2957 follow-up).
  5822. #
  5823. # Skipped when the FTPS cool-off is what produced this fallback:
  5824. # the listing needs the same connection that just failed, so it
  5825. # could only record that the card was unreadable. The scan
  5826. # handles that case by refusing to choose between candidates.
  5827. if not blocked_by_ftps_cooloff:
  5828. await _capture_timelapse_baseline_at_start(
  5829. printer, printer_id, logger, archive_id=fallback_archive.id
  5830. )
  5831. await _forget_if_printer_gone(printer_id)
  5832. return
  5833. except Exception as e:
  5834. logger.error("Failed to create fallback archive: %s", e)
  5835. # Send notification without archive data (file not found)
  5836. if not notification_sent:
  5837. await _send_print_start_notification(printer_id, data, logger=logger)
  5838. return
  5839. try:
  5840. # Archive the file with status "printing"
  5841. service = ArchiveService(db)
  5842. try:
  5843. archive = await service.archive_print(
  5844. printer_id=printer_id,
  5845. source_file=temp_path,
  5846. print_data={
  5847. **data,
  5848. "status": "printing",
  5849. # Where the 3MF came from when the printer had none to
  5850. # give (#3307), for whoever reads this archive later.
  5851. **({"_3mf_from_archive": reused_3mf_from} if reused_3mf_from is not None else {}),
  5852. },
  5853. subtask_id=subtask_id,
  5854. started_at=detected_at,
  5855. # The reused copy's temp name carries the printer id; a
  5856. # download's is the file's own name, as before.
  5857. original_filename=downloaded_filename if reused_3mf_from is not None else None,
  5858. )
  5859. except IntegrityError:
  5860. # archive_print removed the folder it had copied the 3MF into.
  5861. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5862. return
  5863. raise
  5864. if archive:
  5865. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5866. # Set on the row rather than passed to archive_print, which also
  5867. # serves the queue dispatcher — there the queue item decides.
  5868. # Guarded because this branch has no ``except``: an unhandled
  5869. # write error would take the _active_prints registration, the
  5870. # start notification, the energy reading and the timelapse
  5871. # baseline below it with it, and a missing prompt is by far the
  5872. # cheaper failure.
  5873. archive_id = archive.id
  5874. try:
  5875. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5876. archive.confirm_requested = True
  5877. await db.commit()
  5878. except Exception as e:
  5879. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5880. # The rollback expires every loaded object, and on an async
  5881. # session reading one afterwards raises instead of
  5882. # reloading, so the two this branch goes on to use are
  5883. # fetched again. The archive itself was committed by
  5884. # archive_print; only the flag is lost.
  5885. try:
  5886. await db.rollback()
  5887. archive = await db.get(PrintArchive, archive_id)
  5888. printer = await db.get(Printer, printer_id)
  5889. except Exception as reload_error:
  5890. logger.warning(
  5891. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5892. )
  5893. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5894. return
  5895. # Track this active print (use both original filename and downloaded filename)
  5896. _bind_active_print(printer_id, archive_id, downloaded_filename, filename, subtask_name)
  5897. await _open_run_for(archive_id, printer_id, subtask_id)
  5898. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5899. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5900. # Record starting energy from smart plug if available (#941: persisted column)
  5901. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5902. await ws_manager.send_archive_created(
  5903. {
  5904. "id": archive.id,
  5905. "printer_id": archive.printer_id,
  5906. "filename": archive.filename,
  5907. "print_name": archive.print_name,
  5908. "status": archive.status,
  5909. }
  5910. )
  5911. # MQTT relay - publish archive created
  5912. try:
  5913. await mqtt_relay.on_archive_created(
  5914. archive_id=archive.id,
  5915. print_name=archive.print_name,
  5916. printer_name=printer.name,
  5917. status=archive.status,
  5918. )
  5919. except Exception:
  5920. pass # Don't fail if MQTT fails
  5921. # Send notification with archive data (new archive created)
  5922. if not notification_sent:
  5923. archive_data = {
  5924. "print_time_seconds": _run_print_time_seconds(archive, printer_id),
  5925. "created_by_id": archive.created_by_id,
  5926. }
  5927. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5928. # Extract printable objects for skip object functionality
  5929. try:
  5930. from backend.app.services.archive import extract_printable_objects_from_3mf
  5931. client = printer_manager.get_client(printer_id)
  5932. if client:
  5933. with open(temp_path, "rb") as f:
  5934. threemf_data = f.read()
  5935. # Extract with positions for UI overlay, scoped to the
  5936. # plate that is printing — an all-plates 3MF carries
  5937. # every plate's objects (#2522).
  5938. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5939. threemf_data,
  5940. plate_number=resolve_plate_id(client.state),
  5941. include_positions=True,
  5942. )
  5943. if printable_objects:
  5944. # Store objects in printer state
  5945. client.state.printable_objects = printable_objects
  5946. client.state.printable_objects_bbox_all = bbox_all
  5947. client.state.skipped_objects = [] # Reset skipped objects for new print
  5948. logger.info(
  5949. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5950. )
  5951. except Exception as e:
  5952. logger.debug("Failed to extract printable objects: %s", e)
  5953. # From the archived copy: the downloaded one may be removed
  5954. # below while the pauses are still being read.
  5955. if archive is not None and archive.file_path:
  5956. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  5957. # Store Spoolman tracking data for per-filament usage reporting
  5958. try:
  5959. await _store_spoolman_print_data(
  5960. printer_id,
  5961. archive.id,
  5962. archive.file_path,
  5963. db,
  5964. printer_manager,
  5965. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  5966. plate_id=_get_start_plate_id(printer_id, archive_id),
  5967. )
  5968. except Exception as e:
  5969. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  5970. # Price the print from its spools now rather than only at completion (#3261)
  5971. _schedule_archive_cost_estimate(
  5972. printer_id,
  5973. archive.id,
  5974. printer_manager,
  5975. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  5976. plate_id=_get_start_plate_id(printer_id, archive_id),
  5977. session_factory=async_session,
  5978. )
  5979. # Capture timelapse file baseline for snapshot-diff on completion
  5980. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  5981. await _forget_if_printer_gone(printer_id)
  5982. finally:
  5983. # Keep temp_path around until print completes so the cover endpoint
  5984. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5985. # the file. If the cache entry was evicted early (file vanished),
  5986. # clean up any stragglers here to avoid leaking disk on retries.
  5987. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5988. if temp_path and temp_path.exists() and cached_now != temp_path:
  5989. temp_path.unlink()
  5990. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5991. _TIMELAPSE_DIRECTORIES = ("/timelapse", "/timelapse/video", "/record", "/recording")
  5992. # A baseline that could not be read at print start is read again on this
  5993. # schedule while the print runs (#3412). The printer writes the video only once
  5994. # the print has ended, so a reading taken mid-print is as good as one taken at
  5995. # the start. The interval is shorter than the FTPS handshake cool-off (300 s),
  5996. # which is what usually makes the card unreadable, so the first reading after
  5997. # it ends is not long behind; while the cool-off runs a round costs nothing, as
  5998. # no connection is opened. The cap bounds a print that never reports an end.
  5999. _TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS = 120.0
  6000. _TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS = 720
  6001. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  6002. # tests can shrink them without waiting out real delays.
  6003. #
  6004. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  6005. # looking. Across 247 support bundles the attempt that found the video was #1
  6006. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  6007. # decaying one, which is the signature of a budget that expires while files are
  6008. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  6009. # prints make big videos and the printer writes them after the print ends, so
  6010. # the poll now runs for minutes and costs one FTP LIST per round.
  6011. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  6012. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  6013. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  6014. def _timelapse_scan_max_attempts() -> int:
  6015. """Round cap for the poll, derived from the wall-clock budget.
  6016. The deadline alone is not a sufficient bound: it assumes each round really
  6017. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  6018. and an FTP list that fails immediately would otherwise spin against the
  6019. printer at full speed for the whole window. Whichever bound is reached
  6020. first ends the poll.
  6021. """
  6022. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  6023. # A zero interval makes the wall-clock budget meaningless; fall back to
  6024. # the round count the production interval would have given.
  6025. return 32
  6026. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  6027. async def _read_timelapse_baseline(printer) -> tuple[set[str], bool]:
  6028. """The video names on *printer*'s card, and whether the card was read.
  6029. ``_list_timelapse_videos`` answers ``[]`` when its connect fails rather
  6030. than raising, so a card behind the FTPS handshake cool-off, or one whose
  6031. listing timed out, is indistinguishable from one holding no videos.
  6032. Everywhere that only wants to know "is there a video yet" the difference
  6033. does not matter -- both mean "not yet, retry".
  6034. It matters where an empty listing is recorded as a *baseline*. Recording
  6035. "the card held nothing" for a card that was never read means every video on
  6036. it counts as new, and the completion scan then attaches a stale video to
  6037. this print and deletes it from the printer (#2957 follow-up, #3412). So an
  6038. empty listing is asked again here in a way that tells the two apart: the
  6039. card counts as read only when every directory walked answered, with a
  6040. listing or with "no such directory". One that failed may be the one
  6041. holding the videos.
  6042. """
  6043. from backend.app.services.bambu_ftp import ftps_handshake_blocked, list_files_result_async
  6044. files, _ = await _list_timelapse_videos(printer)
  6045. if files:
  6046. return {f.get("name", "") for f in files}, True
  6047. ip_address = getattr(printer, "ip_address", None)
  6048. printer_id = getattr(printer, "id", None)
  6049. if not ip_address:
  6050. return set(), True
  6051. # No card in the slot: nothing to read, and nothing a video could land on.
  6052. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  6053. return set(), True
  6054. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  6055. if ftps_handshake_blocked(ip_address):
  6056. # Below any path: every remaining one would fail the same way.
  6057. return set(), False
  6058. listing = await list_files_result_async(
  6059. ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  6060. )
  6061. if not (listing.available or listing.missing):
  6062. return set(), False
  6063. videos = [
  6064. f
  6065. for f in listing.files
  6066. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  6067. ]
  6068. if videos:
  6069. return {f.get("name", "") for f in videos}, True
  6070. return set(), True
  6071. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  6072. """List video files from printer's timelapse directory.
  6073. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  6074. Returns (video_files, found_path) where video_files is a list of file dicts
  6075. and found_path is the directory where they were found, or ([], None).
  6076. An empty return does not distinguish "no videos" from "could not read the
  6077. card" — see :func:`_read_timelapse_baseline`, which the two baseline
  6078. callers use instead.
  6079. """
  6080. from backend.app.services.bambu_ftp import list_files_async
  6081. logger = logging.getLogger(__name__)
  6082. # No card in the slot means no /timelapse to walk — four connections that
  6083. # can only fail, on a path whose failures are swallowed and so would go on
  6084. # costing time silently forever (#2780).
  6085. #
  6086. # ``getattr`` rather than ``printer.id``: every dereference below happens
  6087. # inside the loop's own try/except, so a caller that passed something
  6088. # unexpected used to get an empty listing rather than an exception. Keep
  6089. # that, instead of making this gate the first thing that can raise here.
  6090. printer_id = getattr(printer, "id", None)
  6091. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  6092. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  6093. return [], None
  6094. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  6095. try:
  6096. found_files = await list_files_async(
  6097. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  6098. )
  6099. if found_files:
  6100. video_files = [
  6101. f
  6102. for f in found_files
  6103. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  6104. ]
  6105. if video_files:
  6106. return video_files, timelapse_path
  6107. except Exception as e:
  6108. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  6109. continue
  6110. return [], None
  6111. async def _capture_timelapse_baseline_at_start(
  6112. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  6113. ) -> None:
  6114. """Snapshot the printer's timelapse directory at print start so the
  6115. completion-time scan can pick the new file by set-difference.
  6116. Must be called from every on_print_start path that proceeds to a real
  6117. print — both the new-archive branch and the expected-archive branch (which
  6118. queue / VP-dispatched prints take). Without a baseline,
  6119. _scan_for_timelapse_with_retries falls into its "take baseline now"
  6120. fallback that runs AFTER the new MP4 has already landed on the SD card,
  6121. so the new file ends up in the "baseline" set and no diff ever matches.
  6122. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  6123. unreliable — the snapshot-diff approach sidesteps that entirely.
  6124. When ``archive_id`` is known the baseline is also written to the archive
  6125. row, so it survives a restart and the manual "Scan for Timelapse" button
  6126. can run the same diff instead of falling back to clock-based matching
  6127. (#2704). Only baselines taken at print start are persisted — one taken at
  6128. completion already contains the new video and would poison a later scan.
  6129. """
  6130. names: set[str] | None = None
  6131. unread = False
  6132. _timelapse_baselines_unread.discard(printer_id)
  6133. try:
  6134. names, read = await _read_timelapse_baseline(printer)
  6135. unread = not read
  6136. _timelapse_baselines[printer_id] = names
  6137. if unread:
  6138. # Recorded anyway, deliberately, and marked. An empty baseline taken
  6139. # off a card we could not read is not evidence, but it is still the
  6140. # right *default*: Bambuddy deletes each video from the printer once
  6141. # it is attached, so the usual card holds exactly one video at
  6142. # completion and an empty baseline resolves it. Persisting NULL
  6143. # instead would send completion to take its own snapshot, by which
  6144. # point this print's video is on the card and would be swallowed by
  6145. # it. The mark keeps the scan from choosing between several videos
  6146. # (#3412), and the card is read again while the print runs.
  6147. _timelapse_baselines_unread.add(printer_id)
  6148. logger.warning(
  6149. "[TIMELAPSE] Baseline for printer %s taken while its card could not be read — "
  6150. "treating it as empty for now and reading it again during the print",
  6151. printer_id,
  6152. )
  6153. logger.info(
  6154. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  6155. len(names),
  6156. printer_id,
  6157. )
  6158. except Exception as e:
  6159. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  6160. run_started_at: datetime | None = None
  6161. run_id: int | None = None
  6162. if archive_id is not None:
  6163. try:
  6164. async with async_session() as db:
  6165. from backend.app.models.archive import PrintArchive
  6166. from backend.app.services.print_log import open_run_on_printer
  6167. archive = await db.get(PrintArchive, archive_id)
  6168. if archive is not None:
  6169. # Written even when the listing failed, and then as NULL. A
  6170. # reprint reuses the archive row, so leaving the previous
  6171. # run's baseline in place would have the scan diff this print
  6172. # against the state of the printer before the *last* one —
  6173. # and a stale baseline reads as authoritative, where NULL
  6174. # correctly falls back to a fresh snapshot.
  6175. baseline = sorted(names) if names is not None else None
  6176. archive.timelapse_baseline = baseline
  6177. archive.timelapse_baseline_unread = unread
  6178. run_started_at = archive.started_at
  6179. # And on the run this print opened, whose scan reads it:
  6180. # the archive's is its latest start's, which another plate
  6181. # of it on another printer can take over.
  6182. run = await open_run_on_printer(db, printer_id)
  6183. if run is not None and run.archive_id == archive_id:
  6184. run.timelapse_baseline = baseline
  6185. run.timelapse_baseline_unread = unread
  6186. run_id = run.id
  6187. await db.commit()
  6188. except Exception as e:
  6189. # In-memory baseline still covers the normal completion path.
  6190. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  6191. if unread and names is not None:
  6192. spawn_background_task(
  6193. _reread_unread_timelapse_baseline(printer_id, names, archive_id, run_started_at, run_id),
  6194. name=f"reread-timelapse-baseline-{printer_id}",
  6195. )
  6196. # Before the print has ended there is no video yet: a long PREPARE (heating,
  6197. # levelling) counts as much as the print itself.
  6198. _BASELINE_REREAD_STATES = _ACTIVE_PRINT_STATES | {"PREPARE", "SLICING"}
  6199. def _schedule_timelapse_scan(
  6200. archive_id: int, printer_id: int, *, plate_id: int | None, run_id: int | None = None
  6201. ) -> None:
  6202. """Start the completion scan with the print-start baseline: the names, and
  6203. whether they were taken off a card that could not be read. Taking them
  6204. ends any re-read still running for it. ``run_id`` is the print that
  6205. ended, whose video it looks for."""
  6206. unread = printer_id in _timelapse_baselines_unread
  6207. _timelapse_baselines_unread.discard(printer_id)
  6208. baseline = _timelapse_baselines.pop(printer_id, None)
  6209. from backend.app.services import archive_work
  6210. # Held while it looks: it finds its print by the archive's id, which a
  6211. # merge would move away (archive redesign P2).
  6212. spawn_background_task(
  6213. archive_work.held_while(
  6214. archive_id,
  6215. _scan_for_timelapse_with_retries(
  6216. archive_id, baseline, plate_id=plate_id, baseline_unread=unread, run_id=run_id
  6217. ),
  6218. ),
  6219. name=f"scan-timelapse-{archive_id}",
  6220. )
  6221. def _unread_baseline_round(printer_id: int, names: set[str]) -> bool | None:
  6222. """Whether to read an unread baseline again now: True to read, None to
  6223. skip this round, False once it is over -- the print it was taken for is
  6224. no longer the one on the printer, has stopped printing, or the baseline
  6225. has been read.
  6226. ``names`` is the very set object recorded at print start: completion pops
  6227. it and the next print records a new one, so identity marks the run. A
  6228. printer that is momentarily disconnected says nothing about its print, so
  6229. that only skips the round.
  6230. """
  6231. if _timelapse_baselines.get(printer_id) is not names or printer_id not in _timelapse_baselines_unread:
  6232. return False
  6233. state = printer_manager.get_status(printer_id)
  6234. if state is None or not state.connected:
  6235. return None
  6236. return state.state in _BASELINE_REREAD_STATES
  6237. async def _reread_unread_timelapse_baseline(
  6238. printer_id: int,
  6239. names: set[str],
  6240. archive_id: int | None,
  6241. run_started_at: datetime | None,
  6242. run_id: int | None = None,
  6243. ) -> None:
  6244. """Read again a print-start baseline the card could not give (#3412).
  6245. The printer writes the video only once the print has ended, so the card
  6246. read at any point during the print holds exactly what it held at the
  6247. start. Each round stops once the print is no longer the one the baseline
  6248. was taken for or has stopped printing, and checks that again after the
  6249. listing returns, before anything is recorded.
  6250. """
  6251. from backend.app.models.archive import PrintArchive
  6252. from backend.app.models.printer import Printer
  6253. from backend.app.services.print_log import run_of
  6254. logger = logging.getLogger(__name__)
  6255. for _ in range(_TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS):
  6256. await asyncio.sleep(_TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS)
  6257. now = _unread_baseline_round(printer_id, names)
  6258. if now is False:
  6259. return
  6260. if now is None:
  6261. continue
  6262. try:
  6263. async with async_session() as db:
  6264. printer = await db.get(Printer, printer_id)
  6265. if printer is None:
  6266. return
  6267. fresh, read = await _read_timelapse_baseline(printer)
  6268. except Exception as e:
  6269. logger.debug("[TIMELAPSE] Re-reading the baseline for printer %s failed: %s", printer_id, e)
  6270. continue
  6271. if not read:
  6272. continue
  6273. now = _unread_baseline_round(printer_id, names)
  6274. if now is False:
  6275. return
  6276. if now is None:
  6277. # The printer dropped off while the listing was out, so nothing
  6278. # says it did not end meanwhile: keep the reading for a round that
  6279. # can vouch for it.
  6280. continue
  6281. names.update(fresh)
  6282. _timelapse_baselines_unread.discard(printer_id)
  6283. logger.info(
  6284. "[TIMELAPSE] Baseline for printer %s read during the print: %s video files",
  6285. printer_id,
  6286. len(fresh),
  6287. )
  6288. if archive_id is None:
  6289. return
  6290. try:
  6291. async with async_session() as db:
  6292. archive = await db.get(PrintArchive, archive_id)
  6293. # Only the run it was taken for: by now the row can belong to a
  6294. # reprint, whose baseline is its own.
  6295. if archive is not None and archive.started_at == run_started_at and archive.timelapse_baseline_unread:
  6296. archive.timelapse_baseline = sorted(names)
  6297. archive.timelapse_baseline_unread = False
  6298. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6299. if run is not None and run.timelapse_baseline_unread:
  6300. run.timelapse_baseline = sorted(names)
  6301. run.timelapse_baseline_unread = False
  6302. await db.commit()
  6303. except Exception as e:
  6304. # The in-memory baseline is read now, which covers completion
  6305. # unless Bambuddy restarts first.
  6306. logger.warning("[TIMELAPSE] Failed to persist the re-read baseline for archive %s: %s", archive_id, e)
  6307. return
  6308. async def _timelapse_still_wanted(db, archive, run_id: int | None, run_started_at: datetime | None) -> bool:
  6309. """Whether the print a timelapse is for still has none: its run, by id,
  6310. exists without a video and no later print took over (``superseded``).
  6311. Without a run, the archive is still on that print's start (a newer run's
  6312. video is its own) and has none."""
  6313. from backend.app.services.print_log import run_of, superseded
  6314. if run_id is not None:
  6315. run = await run_of(db, archive.id, run_id)
  6316. return run is not None and run.timelapse_path is None and not await superseded(db, run)
  6317. return archive.timelapse_path is None and archive.started_at == run_started_at
  6318. async def _scan_for_timelapse_with_retries(
  6319. archive_id: int,
  6320. baseline_names: set[str] | None = None,
  6321. *,
  6322. plate_id: int | None = None,
  6323. baseline_unread: bool = False,
  6324. run_id: int | None = None,
  6325. ):
  6326. """Poll the printer for this print's timelapse and attach it.
  6327. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  6328. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  6329. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  6330. (#2704). Comparing the current listing against the set of filenames that
  6331. existed when the print started needs no clock at all, because the printer
  6332. writes the video only once the print has ended.
  6333. Baseline precedence: the caller's in-memory set, then the one persisted on
  6334. the archive at print start, then a snapshot taken now. The last of those is
  6335. a poor substitute — by completion the new video may already be on the card,
  6336. in which case it lands in the "baseline" and no diff can ever match — but it
  6337. is all that is available for a print that began before Bambuddy started.
  6338. On success the video is deleted from the printer, which keeps ``/timelapse``
  6339. down to the unclaimed files and makes the next diff unambiguous.
  6340. ``baseline_unread`` marks the caller's baseline as taken off a card that
  6341. could not be read; a stored one carries the same mark on the archive.
  6342. ``run_id`` is the print that ended (archive redesign): the video is that
  6343. run's, the stored baseline is the run's own, and the poll ends once the
  6344. run has a video or is gone. Without it (no run was written), the run is
  6345. whichever the archive is on when the scan starts.
  6346. """
  6347. from backend.app.services.print_log import run_of
  6348. logger = logging.getLogger(__name__)
  6349. # Cleared when the baseline was taken off a card we could not read, so the
  6350. # attach step refuses to choose between several candidates (#2957, #3412).
  6351. baseline_trusted = True
  6352. # --- Phase 1: establish the baseline -------------------------------------
  6353. try:
  6354. async with async_session() as db:
  6355. from backend.app.models.printer import Printer
  6356. service = ArchiveService(db)
  6357. archive = await service.get_archive(archive_id)
  6358. if not archive:
  6359. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  6360. return
  6361. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6362. if run_id is not None and run is None:
  6363. logger.info("[TIMELAPSE] Run %s of archive %s is gone, aborting", run_id, archive_id)
  6364. return
  6365. if run.timelapse_path if run is not None else archive.timelapse_path:
  6366. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  6367. return
  6368. # The printer the print ran on: plates of one archive can print on
  6369. # two printers, and the archive's is the one that started last.
  6370. scan_printer_id = run.printer_id if run is not None and run.printer_id else archive.printer_id
  6371. if not scan_printer_id:
  6372. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  6373. return
  6374. # The run this scan is for. The archive row passes to a newer run
  6375. # when it prints again (the next plate, a reprint), and that run's
  6376. # video is its own.
  6377. run_started_at = run.started_at if run is not None else archive.started_at
  6378. # The baseline stored for it: the run's own, else the archive's
  6379. # while that is still this run's start's.
  6380. stored_baseline, stored_unread = None, False
  6381. if run is not None and run.timelapse_baseline is not None:
  6382. stored_baseline, stored_unread = run.timelapse_baseline, bool(run.timelapse_baseline_unread)
  6383. elif archive.started_at == run_started_at:
  6384. stored_baseline, stored_unread = archive.timelapse_baseline, archive.timelapse_baseline_unread
  6385. if baseline_names is not None and baseline_unread and stored_baseline is not None and not stored_unread:
  6386. # The card was read at print start, and the in-memory copy is
  6387. # one Bambuddy took after a restart off a card it could not
  6388. # read: the stored one is this run's and is evidence.
  6389. baseline_names = set(stored_baseline)
  6390. logger.info(
  6391. "[TIMELAPSE] Using stored baseline over an unread one: %s existing video files for archive %s",
  6392. len(baseline_names),
  6393. archive_id,
  6394. )
  6395. elif baseline_names is not None:
  6396. baseline_trusted = not baseline_unread
  6397. logger.info(
  6398. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  6399. len(baseline_names),
  6400. archive_id,
  6401. )
  6402. elif stored_baseline is not None:
  6403. # Persisted at print start — survives a restart mid-print.
  6404. baseline_names = set(stored_baseline)
  6405. baseline_trusted = not stored_unread
  6406. logger.info(
  6407. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  6408. len(baseline_names),
  6409. archive_id,
  6410. )
  6411. else:
  6412. result = await db.execute(select(Printer).where(Printer.id == scan_printer_id))
  6413. printer = result.scalar_one_or_none()
  6414. if not printer:
  6415. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  6416. return
  6417. baseline_names, baseline_trusted = await _read_timelapse_baseline(printer)
  6418. if not baseline_trusted:
  6419. # The card is unreadable at the one moment a baseline has to
  6420. # be taken, so the empty listing means "we never looked",
  6421. # not "these are all new". Carry on with it anyway — the
  6422. # usual card holds exactly one video, which resolves
  6423. # correctly — but stop the poll from *choosing* between
  6424. # several, which is how a stale video got attached to this
  6425. # print and then deleted off the printer (#2957 follow-up).
  6426. logger.warning(
  6427. "[TIMELAPSE] Baseline for archive %s taken while printer %s's card could not be "
  6428. "read. A single new video still resolves; several will not be guessed between — "
  6429. "use Scan for Timelapse to pick one by hand",
  6430. archive_id,
  6431. scan_printer_id,
  6432. )
  6433. logger.info(
  6434. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  6435. len(baseline_names),
  6436. archive_id,
  6437. )
  6438. except Exception as e:
  6439. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  6440. return
  6441. # --- Phase 2: poll for a file that was not there when the print began -----
  6442. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  6443. max_attempts = _timelapse_scan_max_attempts()
  6444. seen_names: set[str] = set()
  6445. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  6446. attempt = 0
  6447. while True:
  6448. await asyncio.sleep(delay)
  6449. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  6450. attempt += 1
  6451. try:
  6452. from backend.app.models.printer import Printer
  6453. # Read phase: fetch archive + printer in a short session and release
  6454. # the pooled connection BEFORE the FTP list/download below. Holding it
  6455. # across the FTP round-trips left one connection idle-in-transaction per
  6456. # in-flight scan (issue #2572).
  6457. async with async_session() as db:
  6458. from backend.app.services.print_log import claimed_timelapse_stems
  6459. service = ArchiveService(db)
  6460. archive = await service.get_archive(archive_id)
  6461. if not archive:
  6462. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  6463. return
  6464. if not await _timelapse_still_wanted(db, archive, run_id, run_started_at):
  6465. logger.info(
  6466. "[TIMELAPSE] Archive %s has its video or is printing again, stopping the run's poll",
  6467. archive_id,
  6468. )
  6469. return
  6470. result = await db.execute(select(Printer).where(Printer.id == scan_printer_id))
  6471. printer = result.scalar_one_or_none()
  6472. if not printer:
  6473. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  6474. return
  6475. claimed = await claimed_timelapse_stems(db, scan_printer_id, archive_id=archive_id, run_id=run_id)
  6476. # I/O phase (no DB connection held): FTP list + download.
  6477. video_files, found_path = await _list_timelapse_videos(printer)
  6478. # The poll can run for dozens of rounds, so only narrate a round
  6479. # that saw something change. Repeating the whole listing every 30 s
  6480. # would bury the one interesting line in the support bundle.
  6481. names_now = {f.get("name", "") for f in video_files}
  6482. changed = attempt == 1 or names_now != seen_names
  6483. seen_names = names_now
  6484. speak = logger.info if changed else logger.debug
  6485. if video_files:
  6486. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  6487. if changed:
  6488. for f in video_files[:5]:
  6489. logger.info("[TIMELAPSE] - %s", f.get("name"))
  6490. attached = await _attach_first_unclaimed_timelapse(
  6491. archive_id,
  6492. printer,
  6493. video_files,
  6494. baseline_names,
  6495. claimed,
  6496. attempt,
  6497. logger,
  6498. quiet=not changed,
  6499. require_unambiguous=not baseline_trusted,
  6500. plate_id=plate_id,
  6501. run_started_at=run_started_at,
  6502. run_id=run_id,
  6503. )
  6504. if attached:
  6505. return
  6506. else:
  6507. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  6508. except Exception as e:
  6509. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  6510. if attempt >= max_attempts or time.monotonic() >= deadline:
  6511. break
  6512. # No name-match fallback: it compared the print name against the filename,
  6513. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  6514. # bundles it fired 159 times and matched zero times, so all it added was a
  6515. # misleading log line before giving up.
  6516. logger.warning(
  6517. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  6518. archive_id,
  6519. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  6520. )
  6521. async def _attach_layer_timelapse(
  6522. archive_id: int,
  6523. timelapse_path: Path,
  6524. plate_id: int | None,
  6525. run_started_at: datetime | None,
  6526. run_id: int | None = None,
  6527. ) -> None:
  6528. """Attach the external camera's stitched timelapse to the archive.
  6529. The camera's video is the one the user set up in Bambuddy, so it wins
  6530. over the printer's own when both are on: it replaces the printer's video
  6531. (usually there first; stitching takes minutes) and that file is deleted,
  6532. leaving nothing in the archive folder unreferenced. ``run_started_at`` is
  6533. the run the frames were taken for: when the archive is printing again by
  6534. the time the stitch is done, the video is not the new run's and is
  6535. dropped. The stitched file is a temporary either way.
  6536. ``run_id`` is the print that ended (archive redesign): the video is that
  6537. run's and replaces that run's printer video; the poll by start above is
  6538. for a print without a run.
  6539. """
  6540. from backend.app.services.print_log import run_of, superseded
  6541. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  6542. logger = logging.getLogger(__name__)
  6543. try:
  6544. async with async_session() as db:
  6545. service = ArchiveService(db)
  6546. archive = await service.get_archive(archive_id)
  6547. if archive is None:
  6548. return
  6549. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6550. if run_id is not None and run is None:
  6551. logger.info("[LAYER-TL] Run %s of archive %s is gone; dropping its layer timelapse", run_id, archive_id)
  6552. return
  6553. if run is not None and await superseded(db, run):
  6554. logger.info(
  6555. "[LAYER-TL] A later print took over run %s of archive %s; dropping its layer timelapse",
  6556. run_id,
  6557. archive_id,
  6558. )
  6559. return
  6560. if run is None and archive.started_at != run_started_at:
  6561. logger.info(
  6562. "[LAYER-TL] Archive %s is printing again; dropping the previous run's layer timelapse", archive_id
  6563. )
  6564. return
  6565. holder = run if run is not None else archive
  6566. replaced = holder.timelapse_path
  6567. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  6568. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  6569. if not await service.attach_timelapse(
  6570. archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=plate_id, run_id=run_id
  6571. ):
  6572. return
  6573. attached = holder.timelapse_path
  6574. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  6575. if replaced and replaced != attached:
  6576. try:
  6577. old = safe_join_under(app_settings.base_dir, replaced, http=False)
  6578. except PathTraversalError:
  6579. return
  6580. await asyncio.to_thread(old.unlink, missing_ok=True)
  6581. logger.info("[LAYER-TL] Replaced the printer's timelapse %s on archive %s", replaced, archive_id)
  6582. finally:
  6583. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6584. # ``run_started_at`` not given: attach whichever run the archive is on.
  6585. _ANY_RUN = object()
  6586. async def _attach_first_unclaimed_timelapse(
  6587. archive_id: int,
  6588. printer,
  6589. video_files: list[dict],
  6590. baseline_names: set[str],
  6591. claimed: set[str],
  6592. attempt: int,
  6593. logger: logging.Logger,
  6594. *,
  6595. quiet: bool = False,
  6596. require_unambiguous: bool = False,
  6597. plate_id: int | None = None,
  6598. run_started_at: datetime | None | object = _ANY_RUN,
  6599. run_id: int | None = None,
  6600. ) -> bool:
  6601. """Download and attach the one video that belongs to this print.
  6602. A candidate is any file absent from the print-start baseline. More than one
  6603. can qualify when a previous print's video landed late, after this print's
  6604. baseline was taken — those are filtered out by name, because they are
  6605. already attached to another archive. Sorting the candidates instead would
  6606. mean sorting on mtime or on the filename timestamp, both of which come from
  6607. the printer's unsynced clock.
  6608. Returns True once a video is attached. The printer's copy is deleted only
  6609. after the attach succeeds on bytes whose length matched the listing.
  6610. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  6611. already seen this exact listing — the poll runs for many rounds and only the
  6612. rounds where something changed are worth an INFO line.
  6613. """
  6614. from backend.app.services.bambu_ftp import (
  6615. DownloadDeadlineExceeded,
  6616. delete_archived_timelapse,
  6617. download_file_bytes_async,
  6618. remote_file_settled,
  6619. )
  6620. speak = logger.debug if quiet else logger.info
  6621. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  6622. if not new_files:
  6623. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  6624. return False
  6625. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  6626. if not candidates:
  6627. speak(
  6628. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  6629. attempt,
  6630. len(new_files),
  6631. )
  6632. return False
  6633. if len(candidates) > 1:
  6634. if require_unambiguous:
  6635. # The baseline is not evidence -- it was taken off a card that could
  6636. # not be read -- so "new since the baseline" does not narrow these
  6637. # down at all. Taking the first would attach an arbitrary video to
  6638. # this print and then delete it from the printer.
  6639. logger.warning(
  6640. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  6641. "leaving all of them on the printer for manual selection",
  6642. attempt,
  6643. len(candidates),
  6644. ", ".join(str(f.get("name")) for f in candidates),
  6645. )
  6646. return False
  6647. logger.warning(
  6648. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  6649. "the rest stay on the printer for manual selection",
  6650. attempt,
  6651. len(candidates),
  6652. ", ".join(str(f.get("name")) for f in candidates),
  6653. )
  6654. target = candidates[0]
  6655. file_name = str(target.get("name") or "") # every listed entry has one
  6656. remote_path = target.get("path") or f"/timelapse/{file_name}"
  6657. logger.info(
  6658. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  6659. attempt,
  6660. file_name,
  6661. archive_id,
  6662. )
  6663. # The listing always carries a size (`list_files` skips entries it can't
  6664. # parse), but read it explicitly: the delete below is destructive and must
  6665. # depend on a size we actually had, not on one we hoped was there.
  6666. expected_size = target.get("size")
  6667. try:
  6668. timelapse_data = await download_file_bytes_async(
  6669. printer.ip_address,
  6670. printer.access_code,
  6671. remote_path,
  6672. printer_model=printer.model,
  6673. expected_size=expected_size,
  6674. )
  6675. except DownloadDeadlineExceeded:
  6676. # Too slow for its size this round; the printer keeps its copy.
  6677. timelapse_data = None
  6678. if not timelapse_data:
  6679. # Short or failed transfer. The printer keeps its copy, so the next
  6680. # round can try again — which is exactly why the delete below is
  6681. # gated on a verified download.
  6682. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  6683. return False
  6684. # The length check above proves we got what the listing said, not that the
  6685. # printer had finished writing. A video still being written can be listed
  6686. # short, served short, and pass — so confirm it has stopped growing before
  6687. # committing to it and deleting the original (#2704).
  6688. if not await remote_file_settled(
  6689. printer.ip_address,
  6690. printer.access_code,
  6691. remote_path,
  6692. len(timelapse_data),
  6693. printer_model=printer.model,
  6694. ):
  6695. return False
  6696. # Write phase: attach in a fresh short-lived session. The download took a
  6697. # while: by now the archive may have its video, or be printing again for a
  6698. # newer run, whose video this is not. Then nothing is attached or deleted,
  6699. # and the poll ends (True).
  6700. async with async_session() as db:
  6701. service = ArchiveService(db)
  6702. if run_id is not None or run_started_at is not _ANY_RUN:
  6703. current = await service.get_archive(archive_id)
  6704. started = None if run_started_at is _ANY_RUN else cast("datetime | None", run_started_at)
  6705. if current is None or not await _timelapse_still_wanted(db, current, run_id, started):
  6706. logger.info(
  6707. "[TIMELAPSE] Archive %s moved on during the download (video attached or printing again); "
  6708. "%s stays on the printer",
  6709. archive_id,
  6710. file_name,
  6711. )
  6712. return True
  6713. success = await service.attach_timelapse(
  6714. archive_id, timelapse_data, file_name, plate_id=plate_id, run_id=run_id
  6715. )
  6716. if not success:
  6717. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  6718. return False
  6719. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  6720. await delete_archived_timelapse(
  6721. printer.ip_address,
  6722. printer.access_code,
  6723. remote_path,
  6724. verified=expected_size is not None,
  6725. printer_model=printer.model,
  6726. printer_name=printer.name,
  6727. )
  6728. return True
  6729. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  6730. # module-level so tests can monkeypatch them down to ~0 without timing out.
  6731. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  6732. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  6733. # How long the *background* upgrade keeps waiting after the notification has
  6734. # already gone out (#2704 follow-up). The short bound above exists so a slow
  6735. # printer can't hold up the print-complete notification; this one exists so the
  6736. # archive still ends up with the better frame afterwards.
  6737. #
  6738. # Measured across 261 attaches in the support bundles, the video lands a median
  6739. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  6740. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  6741. # was 546s. Every other model was inside 26s. The long budget is therefore
  6742. # almost entirely for P1-series users; on everything else the short wait already
  6743. # wins and this task never runs.
  6744. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  6745. async def _capture_finish_photo_from_timelapse(
  6746. archive_id: int,
  6747. archive_dir: Path,
  6748. timeout: float | None = None,
  6749. rotation: int = 0,
  6750. run_id: int | None = None,
  6751. ) -> tuple[str | None, bool]:
  6752. """Wait for the per-print timelapse to land on the archive and extract its
  6753. last frame as the finish photo (#1397).
  6754. Bambu firmware stops timelapse recording after the toolhead parks but
  6755. before the bed-drop end-gcode runs, so the last frame frames the finished
  6756. print correctly. A live camera grab at gcode_state=FINISH captures the
  6757. bed already lowered.
  6758. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  6759. ``archive.timelapse_path`` when the file lands. This function polls for
  6760. that field.
  6761. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  6762. the wait ran out with no video on the archive yet — i.e. the video may
  6763. still be coming and a later attempt could succeed. It is False when the
  6764. video landed (whether or not extraction worked), because in that case
  6765. waiting longer changes nothing. The caller uses that to decide between
  6766. falling back permanently and scheduling a background upgrade.
  6767. ``rotation`` is the printer's camera_rotation, applied to the extracted
  6768. still (#2708) so this source agrees with every other finish-photo source.
  6769. The archived video itself is the printer's own file and is left alone —
  6770. rotating it would mean re-encoding it.
  6771. ``run_id`` is the print that ended: its own video is the one waited for,
  6772. not the archive's, which can be another plate's.
  6773. """
  6774. import uuid
  6775. from backend.app.models.archive import PrintArchive
  6776. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  6777. from backend.app.services.print_log import run_of
  6778. logger = logging.getLogger(__name__)
  6779. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  6780. deadline = asyncio.get_event_loop().time() + budget
  6781. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  6782. while True:
  6783. async with async_session() as db:
  6784. if run_id is not None:
  6785. run = await run_of(db, archive_id, run_id)
  6786. timelapse_relpath = run.timelapse_path if run else None
  6787. else:
  6788. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6789. archive = result.scalar_one_or_none()
  6790. timelapse_relpath = archive.timelapse_path if archive else None
  6791. if timelapse_relpath:
  6792. video_path = app_settings.base_dir / timelapse_relpath
  6793. if video_path.exists() and video_path.stat().st_size > 0:
  6794. photos_dir = archive_dir / "photos"
  6795. photos_dir.mkdir(parents=True, exist_ok=True)
  6796. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6797. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6798. output_path = photos_dir / filename
  6799. if await extract_video_last_frame(video_path, output_path):
  6800. await apply_camera_rotation_to_file(output_path, rotation, logger)
  6801. logger.info(
  6802. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  6803. video_path.name,
  6804. archive_id,
  6805. )
  6806. return filename, False
  6807. logger.warning(
  6808. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  6809. video_path.name,
  6810. archive_id,
  6811. )
  6812. return None, False
  6813. if asyncio.get_event_loop().time() >= deadline:
  6814. logger.info(
  6815. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  6816. archive_id,
  6817. budget,
  6818. )
  6819. return None, True
  6820. await asyncio.sleep(poll_interval)
  6821. async def _upgrade_finish_photo_from_timelapse(
  6822. archive_id: int, archive_dir: Path, rotation: int = 0, run_id: int | None = None
  6823. ) -> None:
  6824. """Add the timelapse's last frame to an archive after the fact (#2704).
  6825. The print-complete notification waits only ~60s for the video, because
  6826. holding a notification for minutes is worse than sending it with a live
  6827. camera grab. On a P1-series printer the video often lands well after that,
  6828. so the archive used to be stuck with the live grab — which is taken at
  6829. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  6830. the worse photo of the two.
  6831. This keeps waiting in the background and, when the video arrives, extracts
  6832. the frame and puts it *first* in the archive's photo list, so opening the
  6833. gallery shows it. The live grab is deliberately kept: the notification that
  6834. already went out links to that exact file, and deleting it would leave a
  6835. broken image in Discord or Telegram. ``run_id`` is the print it is for,
  6836. whose list leads with it too.
  6837. """
  6838. from backend.app.services.print_log import add_run_photo, run_of
  6839. logger = logging.getLogger(__name__)
  6840. filename, _ = await _capture_finish_photo_from_timelapse(
  6841. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation, run_id=run_id
  6842. )
  6843. if not filename:
  6844. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  6845. return
  6846. try:
  6847. async with async_session() as db:
  6848. from backend.app.models.archive import PrintArchive
  6849. archive = await db.get(PrintArchive, archive_id)
  6850. if archive is None:
  6851. return
  6852. photos = list(archive.photos or [])
  6853. if filename in photos:
  6854. return
  6855. # Front of the list: PhotoGalleryModal opens at index 0.
  6856. archive.photos = [filename, *photos]
  6857. add_run_photo(await run_of(db, archive_id, run_id) if run_id is not None else None, filename, first=True)
  6858. await db.commit()
  6859. except Exception as e:
  6860. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  6861. return
  6862. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  6863. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  6864. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  6865. """Put the filament-attribution context back after a restart mid-print.
  6866. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  6867. both die with the process. The print keeps running, so at completion the
  6868. tracker would fall back to whatever the printer reports *now* — and AMS
  6869. filament backup makes "now" the substitute tray, charging the whole print
  6870. to the spool that only finished it.
  6871. The persisted row is only trusted when its print name still matches what
  6872. the printer says it is running: a row left behind by a completion we never
  6873. saw must not attach itself to the next print.
  6874. """
  6875. try:
  6876. from backend.app.api.routes.settings import get_setting
  6877. from backend.app.services.usage_tracker import (
  6878. clear_persisted_session,
  6879. get_persisted_ams_mapping,
  6880. get_persisted_print_name,
  6881. get_persisted_spool_change_log,
  6882. restore_session,
  6883. )
  6884. persisted_name = await get_persisted_print_name(db, printer_id)
  6885. current_name = (state.subtask_name or "").strip()
  6886. if persisted_name and current_name and persisted_name.strip() != current_name:
  6887. logger.info(
  6888. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  6889. printer_id,
  6890. persisted_name,
  6891. current_name,
  6892. )
  6893. await clear_persisted_session(db, printer_id)
  6894. # Fall through to seeding: the print on the printer is real, it just
  6895. # isn't the one the row described.
  6896. persisted_log = None
  6897. else:
  6898. # Spoolman users get the tray-change log back but no in-memory
  6899. # session — see ``on_print_start`` on why that dict is load-bearing
  6900. # for the remain%-sync guard.
  6901. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6902. persisted_log = await restore_session(
  6903. db,
  6904. printer_id,
  6905. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  6906. )
  6907. # The slot pills (#1762) read the mapping captured from the print
  6908. # command, which dies with the process as well. One this process
  6909. # has captured since is newer.
  6910. if state.print_ams_mapping is None:
  6911. state.print_ams_mapping = await get_persisted_ams_mapping(db, printer_id)
  6912. # Spools swapped on a tray before the restart (#3325); anything this
  6913. # process has recorded since goes after them.
  6914. persisted_swaps = await get_persisted_spool_change_log(db, printer_id)
  6915. if persisted_swaps:
  6916. seen = getattr(state, "spool_change_log", None) or []
  6917. state.spool_change_log = persisted_swaps + [item for item in seen if item not in persisted_swaps]
  6918. if persisted_log:
  6919. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  6920. # Anything this process already observed goes after the persisted
  6921. # history — the log is ordered by layer, and a fresh process can
  6922. # only have seen changes from later in the print.
  6923. for entry in state.tray_change_log or []:
  6924. if tuple(entry) not in restored:
  6925. restored.append(tuple(entry))
  6926. state.tray_change_log = restored
  6927. tray_now = state.tray_now
  6928. if 0 <= tray_now <= 254:
  6929. if not state.tray_change_log:
  6930. # No persisted history — a print that started before this build,
  6931. # or before the row existed. Seed with the tray feeding right
  6932. # now so the remainder of the print is at least attributable to
  6933. # the right spool.
  6934. state.tray_change_log = [(tray_now, state.layer_num)]
  6935. logger.info(
  6936. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  6937. printer_id,
  6938. tray_now,
  6939. state.layer_num,
  6940. )
  6941. # The tray handler updates ``last_loaded_tray`` on every push
  6942. # regardless of whether it logged a change, so re-align it to avoid
  6943. # a duplicate entry on the next push. Only ever with a real tray:
  6944. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  6945. # 255" fallback, and writing 255 into it would defeat that.
  6946. state.last_loaded_tray = tray_now
  6947. except Exception:
  6948. # Never let attribution recovery cost the caller its timelapse
  6949. # baseline — that capture has to happen before the printer uploads
  6950. # the in-flight MP4 and there is no second chance at it.
  6951. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  6952. async def on_print_running_observed(printer_id: int, data: dict):
  6953. """Restart-recovery for a print that started before Bambuddy came up.
  6954. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  6955. after Bambuddy startup (#1304 guard, prevents duplicate archive
  6956. creation). This hook restores the persisted archive into ``_active_prints``
  6957. and captures the timelapse baseline that normally hangs off print start.
  6958. Fires once per session, in lieu of on_print_start when restart-recovery
  6959. kicks in. The printer doesn't upload the timelapse until after PRINT
  6960. COMPLETE, so a baseline captured any time during the print is still
  6961. pre-upload.
  6962. """
  6963. logger = logging.getLogger(__name__)
  6964. async with async_session() as db:
  6965. from backend.app.models.printer import Printer
  6966. state = printer_manager.get_status(printer_id)
  6967. if state is not None:
  6968. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  6969. if authorization is True:
  6970. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  6971. await _restore_usage_tracking_session(printer_id, state, db, logger)
  6972. await _restore_printable_objects(printer_id, state, db, logger)
  6973. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6974. printer = result.scalar_one_or_none()
  6975. if not printer:
  6976. logger.warning(
  6977. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  6978. printer_id,
  6979. )
  6980. return
  6981. # Avoid double-capture: ownership reconciliation above must still run when
  6982. # a baseline already exists, but the camera work itself is one-shot.
  6983. if printer_id in _timelapse_baselines:
  6984. logger.debug(
  6985. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  6986. printer_id,
  6987. )
  6988. return
  6989. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  6990. class _RunOfArchive:
  6991. """An archive as one of its runs printed it: the run's job id, start and
  6992. plate, the rest the archive's. What the reconcile judges and closes."""
  6993. def __init__(self, archive, run):
  6994. self._archive = archive
  6995. self.subtask_id = run.subtask_id
  6996. self.started_at = run.started_at
  6997. self.plate_id = run.plate_id if run.plate_id is not None else archive.plate_id
  6998. def __getattr__(self, name):
  6999. return getattr(self._archive, name)
  7000. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  7001. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  7002. against the printer's current MQTT state.
  7003. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  7004. COMPLETE events, typically a print finishing during an MQTT disconnect
  7005. window followed by a smart-plug power cycle):
  7006. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  7007. provably not running anymore — only branch that should fire under
  7008. normal disconnect-then-reconnect timing.
  7009. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  7010. firmware mints a fresh ``subtask_id`` for each print, including the
  7011. ghost replay it runs after a power cycle from a leftover SD file —
  7012. so a mismatch unambiguously means the in-DB archive is no longer
  7013. the print on the printer.
  7014. 3. Printer is running but ``subtask_name`` is empty. The printer
  7015. doesn't know what it's running; the archive's reference to it is
  7016. already broken.
  7017. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  7018. with matching subtask_id+subtask_name is left alone. The cost of a false
  7019. positive is a print closed while it still runs: the reconcile takes its
  7020. ``_active_prints`` entry and the archive is no longer ``printing``, so
  7021. the real PRINT COMPLETE later finds no archive to close (#1679). The
  7022. cost of a false negative is the ghost-print loop in #1542. What the
  7023. archive is closed as is ``_reconciled_outcome``'s call.
  7024. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  7025. MQTT has connected but the first ``push_status`` response hasn't been
  7026. applied yet — ``PrinterState`` is sitting on its construction defaults.
  7027. The reconcile caller in ``on_printer_status_change`` is already gated
  7028. on a real ``state.state``, so in normal operation this branch is
  7029. unreachable; it's kept as belt-and-braces for future callers and for
  7030. the narrow window where a partial state update could arrive
  7031. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  7032. ``not stale`` on degenerate input is strictly conservative: a real
  7033. stale archive will still be caught by the next push_status arriving
  7034. with terminal state.
  7035. """
  7036. current_state = (state.state or "").upper()
  7037. if current_state in ("", "UNKNOWN"):
  7038. # No real push_status yet — PrinterState defaults are not evidence.
  7039. return False, ""
  7040. if current_state in ("IDLE", "FINISH", "FAILED"):
  7041. return True, f"printer state {current_state}"
  7042. # Below here the printer is in a running / pre-running state (RUNNING /
  7043. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  7044. current_subtask_id = (state.subtask_id or "").strip()
  7045. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  7046. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  7047. current_subtask_name = (state.subtask_name or "").strip()
  7048. if not current_subtask_name:
  7049. return True, "printer subtask_name empty"
  7050. return False, ""
  7051. async def prime_kprofile_table(printer_id: int) -> int:
  7052. """Read the printer's calibration table once per connection.
  7053. The AMS slot card shows a K value per slot (#2854). On the printers whose
  7054. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  7055. report ``cali_idx`` and nothing else -- that number can only come from
  7056. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  7057. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  7058. backup, or the printer answering a query BambuStudio made on the report
  7059. topic we share. A Bambuddy that nobody visited showed a card with no K
  7060. values at all.
  7061. Only the diameters actually fitted are asked for, which is one request on a
  7062. single-nozzle printer and two on a dual. Probing the four sizes blind is
  7063. what the backup does, and it is both wasteful and the thing that used to
  7064. blank the table.
  7065. Returns the number of nozzles whose table was read.
  7066. """
  7067. client = printer_manager.get_client(printer_id)
  7068. state = printer_manager.get_status(printer_id)
  7069. if client is None or state is None or not state.connected:
  7070. return 0
  7071. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  7072. # ask once, and both entries are empty until the first push_status lands.
  7073. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  7074. if not diameters:
  7075. logging.getLogger(__name__).debug(
  7076. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  7077. printer_id,
  7078. )
  7079. return 0
  7080. primed = 0
  7081. for diameter in diameters:
  7082. try:
  7083. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  7084. except Exception as exc: # noqa: BLE001
  7085. # A printer that won't answer costs the card its K values, nothing
  7086. # more — never the connection this runs on the back of.
  7087. logging.getLogger(__name__).warning(
  7088. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  7089. )
  7090. continue
  7091. primed += 1
  7092. logging.getLogger(__name__).info(
  7093. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  7094. )
  7095. return primed
  7096. def _sd_files_in_use(state) -> set[str]:
  7097. """Names of the SD-card files the printer may be printing right now (#3009).
  7098. The post-print cleanup works out what to delete from the finished archive,
  7099. not from the printer. When reconciliation closes an old archive because the
  7100. printer has moved on to a new job, and that job is the same file reprinted
  7101. from the printer's screen, the cleanup would delete the file mid-print.
  7102. Empty unless the printer is busy: on an ordinary completion the state is
  7103. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  7104. name, a path or a URL depending on firmware, and some report only the
  7105. plate's G-code, so the job name is matched as well, in the same spellings
  7106. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  7107. ignores case.
  7108. """
  7109. def _text(value) -> str:
  7110. return value.strip() if isinstance(value, str) else ""
  7111. if state is None:
  7112. return set()
  7113. current_state = _text(getattr(state, "state", None)).upper()
  7114. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  7115. return set()
  7116. in_use: set[str] = set()
  7117. gcode_file = _text(getattr(state, "gcode_file", None))
  7118. if gcode_file:
  7119. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  7120. # both legal in a file name, and raises on some inputs.
  7121. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  7122. if name:
  7123. in_use.add(name.lower())
  7124. subtask_name = _text(getattr(state, "subtask_name", None))
  7125. if subtask_name:
  7126. for name in (subtask_name, subtask_name.replace(" ", "_")):
  7127. for ext in (".3mf", ".gcode"):
  7128. in_use.add(f"{name}{ext}".lower())
  7129. return in_use
  7130. def _reconciled_outcome(archive, state) -> str:
  7131. """What a stale archive is closed as at reconnect (#3310).
  7132. A print that ends while Bambuddy restarts is never seen to end: the new
  7133. MQTT client's first status is already FINISH, which is not a transition.
  7134. The printer keeps reporting the finished job's ``subtask_id`` until the
  7135. next print, so a matching id proves the FINISH or FAILED is this
  7136. archive's. Anything else -- IDLE, another job, an id of "0" (a print
  7137. started outside the cloud) or none -- says only that the print is over,
  7138. not how, and stays ``aborted``.
  7139. """
  7140. current_state = (state.state or "").upper()
  7141. if current_state not in ("FINISH", "FAILED"):
  7142. return "aborted"
  7143. archive_id = (archive.subtask_id or "").strip()
  7144. current_id = str(state.subtask_id or "").strip()
  7145. if archive_id in ("", "0") or archive_id != current_id:
  7146. return "aborted"
  7147. return "completed" if current_state == "FINISH" else "failed"
  7148. def _reconciled_end_time(archive, now: datetime, plate_id: int | None = None) -> datetime | None:
  7149. """When a print reconciled as completed most likely ended, or None (#3310).
  7150. The printer does not say when it finished, and the reconnect can be hours
  7151. later. Its start plus the slicer's estimate for the plate it printed,
  7152. never later than now, is the best guess; None when either is missing,
  7153. and the run then keeps no duration, as an aborted one does.
  7154. ``plate_id`` is the plate this run printed, from its queue job: a reprint
  7155. of another plate reuses the archive without changing ``archive.plate_id``.
  7156. """
  7157. started = archive.started_at
  7158. if not started:
  7159. return None
  7160. if started.tzinfo is None:
  7161. started = started.replace(tzinfo=timezone.utc)
  7162. plate = plate_id if plate_id is not None else archive.plate_id
  7163. estimate = None
  7164. if archive.file_path:
  7165. from backend.app.utils.threemf_tools import extract_print_time_from_3mf
  7166. full_path = (
  7167. app_settings.base_dir / archive.file_path
  7168. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7169. try:
  7170. estimate = extract_print_time_from_3mf(full_path, plate)
  7171. except Exception as exc: # noqa: BLE001
  7172. logging.getLogger(__name__).debug(
  7173. "Plate estimate for reconciled archive %s unreadable: %s", archive.id, exc
  7174. )
  7175. if plate is None and estimate != archive.print_time_seconds:
  7176. # Without a plate the first plate's estimate is read. The archive
  7177. # carries the sum over all plates (#1593), so a difference means
  7178. # several plates and no telling which one printed.
  7179. estimate = None
  7180. elif plate is None:
  7181. # Nothing to read the plate from; the archive's own estimate, as for
  7182. # a single-plate file.
  7183. estimate = archive.print_time_seconds
  7184. if not estimate or estimate <= 0:
  7185. return None
  7186. return min(started + timedelta(seconds=int(estimate)), now)
  7187. async def reconcile_stale_active_prints(printer_id: int) -> int:
  7188. """Synthesise ``on_print_complete`` for archives whose print can't be
  7189. running on the printer anymore.
  7190. Called once per MQTT (re)connection (from on_printer_status_change when
  7191. the connected edge flips False → True) and at Bambuddy startup (from
  7192. the FastAPI lifespan). Without this, a print that completes during a
  7193. disconnect window — followed by a smart-plug-driven power cycle — leaves
  7194. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  7195. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  7196. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  7197. power cycle until the operator notices (#1542 follow-up). Reconciliation
  7198. closes the loop by faking the missed PRINT COMPLETE — the existing
  7199. cleanup chain handles SD-file deletion, status updates, usage tracking,
  7200. and notifications.
  7201. The status is ``_reconciled_outcome``'s: ``completed`` or ``failed``
  7202. when the printer still reports the archive's own job as finished or
  7203. failed, ``aborted`` otherwise. Nothing corrects it later: the archive is
  7204. no longer ``printing``, so a later PRINT COMPLETE finds no archive, and
  7205. after a restart the printer's FINISH is not one (#3310).
  7206. Returns the number of archives reconciled.
  7207. """
  7208. state = printer_manager.get_status(printer_id)
  7209. if not state:
  7210. return 0
  7211. # Don't reconcile while disconnected — we'd be making a decision against
  7212. # stale cached state. The connected → reconcile edge handles this.
  7213. if not state.connected:
  7214. return 0
  7215. from backend.app.models.archive import PrintArchive
  7216. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
  7217. reconciled = 0
  7218. async with async_session() as db:
  7219. # The prints on this printer Bambuddy saw start: their runs open here.
  7220. # The archive row is shared by every plate of a file, its printer, job
  7221. # and start the latest start's, so each is judged as its run.
  7222. open_runs = (
  7223. await db.scalars(
  7224. select(PrintLogEntry)
  7225. .where(PrintLogEntry.printer_id == printer_id, PrintLogEntry.status == RUN_OPEN)
  7226. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7227. )
  7228. ).all()
  7229. by_run = {
  7230. archive.id: archive
  7231. for archive in (
  7232. await db.scalars(
  7233. select(PrintArchive).where(
  7234. PrintArchive.id.in_([run.archive_id for run in open_runs if run.archive_id is not None])
  7235. )
  7236. )
  7237. ).all()
  7238. }
  7239. active: list = [_RunOfArchive(by_run[run.archive_id], run) for run in open_runs if run.archive_id in by_run]
  7240. # And as before runs were opened at the start: a printing archive of
  7241. # this printer with no run open anywhere (printing since before).
  7242. archives_with_open_runs = select(PrintLogEntry.archive_id).where(
  7243. PrintLogEntry.status == RUN_OPEN, PrintLogEntry.archive_id.is_not(None)
  7244. )
  7245. result = await db.execute(
  7246. select(PrintArchive)
  7247. .where(
  7248. PrintArchive.printer_id == printer_id,
  7249. PrintArchive.status == "printing",
  7250. PrintArchive.id.not_in(archives_with_open_runs),
  7251. )
  7252. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7253. )
  7254. active.extend(result.scalars().all())
  7255. if not active:
  7256. return 0
  7257. # The plate each run printed, from its queue job (#3310).
  7258. from backend.app.models.print_queue import PrintQueueItem
  7259. async with async_session() as db:
  7260. plate_rows = await db.execute(
  7261. select(PrintQueueItem.archive_id, PrintQueueItem.plate_id).where(
  7262. PrintQueueItem.printer_id == printer_id,
  7263. PrintQueueItem.status == "printing",
  7264. PrintQueueItem.archive_id.in_([a.id for a in active]),
  7265. )
  7266. )
  7267. run_plates = {archive_id: plate for archive_id, plate in plate_rows.all() if plate is not None}
  7268. logger = logging.getLogger(__name__)
  7269. for archive in active:
  7270. is_stale, reason = _is_active_archive_stale(archive, state)
  7271. if not is_stale:
  7272. continue
  7273. logger.info(
  7274. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  7275. printer_id,
  7276. archive.id,
  7277. archive.filename,
  7278. reason,
  7279. )
  7280. # Synthesised payload: minimal fields the on_print_complete chain
  7281. # needs. `_reconciled` marker lets downstream code distinguish this
  7282. # from a real MQTT-driven completion if it ever needs to (e.g. for
  7283. # metrics / debug logging). raw_data is the live printer state so
  7284. # the usage tracker can compare end-of-print remain% against the
  7285. # captured start values.
  7286. outcome = _reconciled_outcome(archive, state)
  7287. payload = {
  7288. "status": outcome,
  7289. "filename": archive.filename,
  7290. "subtask_name": archive.print_name or "",
  7291. "subtask_id": archive.subtask_id or "",
  7292. "raw_data": state.raw_data or {},
  7293. "_reconciled": True,
  7294. }
  7295. if isinstance(archive, _RunOfArchive):
  7296. # The archive it closes, which its names and printer may not find:
  7297. # another printer's plate of it can have started since.
  7298. payload["_reconciled_archive_id"] = archive.id
  7299. if outcome != "aborted":
  7300. # The printer's progress and layer are this job's, so a partial
  7301. # run is charged what it printed rather than nothing.
  7302. if state.progress:
  7303. payload["last_progress"] = state.progress
  7304. if state.layer_num:
  7305. payload["last_layer_num"] = state.layer_num
  7306. if outcome == "failed":
  7307. payload["hms_errors"] = [e.completion_payload() for e in state.hms_errors or []]
  7308. if outcome == "completed":
  7309. ended = _reconciled_end_time(archive, datetime.now(timezone.utc), run_plates.get(archive.id))
  7310. if ended:
  7311. payload["_reconciled_completed_at"] = ended
  7312. try:
  7313. await on_print_complete(printer_id, payload)
  7314. reconciled += 1
  7315. except Exception as e:
  7316. # Catch-all: a reconciliation failure must not block the
  7317. # printer's normal status flow. The archive stays in
  7318. # ``status="printing"`` and the next reconnect retries.
  7319. logger.warning(
  7320. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  7321. archive.id,
  7322. e,
  7323. )
  7324. return reconciled
  7325. # #2547: clearance left between the nozzle and the top of the print when the
  7326. # plate is commanded back into camera framing. The nozzle is parked away from
  7327. # the part by then, so this is belt-and-braces against a max_z_height that
  7328. # under-reports (e.g. a slicer that excludes a final Z hop).
  7329. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  7330. # How far below the restored position to drop the plate again afterwards, so
  7331. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  7332. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  7333. # on machines with less headroom.
  7334. _PLATE_PARK_DROP_MM = 100.0
  7335. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  7336. # this axis, so it is a proven-safe speed for the full travel.
  7337. _PLATE_RESTORE_FEEDRATE = 600
  7338. # Time allowed for the plate to reach the restored position before the camera
  7339. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  7340. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  7341. # How long `_background_finish_photo` waits for this producer. Must cover the
  7342. # settle window plus a worst-case RTSP grab (15s), and stay below the
  7343. # notification path's own photo wait so a slow producer degrades to a
  7344. # photo-less notification rather than a missed one. The chamber light's
  7345. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  7346. # camera_light.MAX_DELAY_SECONDS stays below it.
  7347. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  7348. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  7349. """The ``_active_prints`` keys a finished print may be registered under.
  7350. Matching how they were registered in on_print_start. Shared by
  7351. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  7352. to find the same binding.
  7353. """
  7354. possible_keys = []
  7355. # Try subtask_name variations first (most reliable for matching)
  7356. if subtask_name:
  7357. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  7358. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  7359. possible_keys.append((printer_id, subtask_name))
  7360. # Try filename variations
  7361. if filename:
  7362. # Extract just the filename if it's a path
  7363. fname = filename.split("/")[-1] if "/" in filename else filename
  7364. if fname.endswith(".3mf"):
  7365. possible_keys.append((printer_id, fname))
  7366. elif fname.endswith(".gcode"):
  7367. base_name = fname.rsplit(".", 1)[0]
  7368. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  7369. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7370. possible_keys.append((printer_id, fname))
  7371. else:
  7372. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  7373. possible_keys.append((printer_id, f"{fname}.3mf"))
  7374. possible_keys.append((printer_id, fname))
  7375. # Also try full path versions
  7376. if filename.endswith(".3mf"):
  7377. possible_keys.append((printer_id, filename))
  7378. elif filename.endswith(".gcode"):
  7379. base_name = filename.rsplit(".", 1)[0]
  7380. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7381. possible_keys.append((printer_id, filename))
  7382. else:
  7383. possible_keys.append((printer_id, f"{filename}.3mf"))
  7384. possible_keys.append((printer_id, filename))
  7385. return possible_keys
  7386. def _archive_name_forms(archive) -> set[str]:
  7387. """The names an archive could be echoed back as, in normalised form (#3240).
  7388. Its print name, and its filename with and without the 3MF extension.
  7389. """
  7390. forms = set()
  7391. if archive.print_name:
  7392. forms.add(_normalise_subtask_name(archive.print_name))
  7393. if archive.filename:
  7394. forms.add(_normalise_subtask_name(archive.filename))
  7395. for suffix in (".gcode.3mf", ".3mf"):
  7396. if archive.filename.lower().endswith(suffix):
  7397. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  7398. forms.discard("")
  7399. return forms
  7400. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  7401. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  7402. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  7403. from the plate recorded when the job was dispatched. Neither is touched:
  7404. ``on_print_complete`` pops both, which is why the finish-photo producer
  7405. calls this before its first await, while they are still there.
  7406. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  7407. archive, or that it only knows by a name -- and on any error: the producer
  7408. calls this before the ``try`` that always releases the photo consumer, so
  7409. it must not raise.
  7410. """
  7411. try:
  7412. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  7413. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  7414. if archive_id is None:
  7415. return None, None
  7416. return archive_id, _print_plate_ids.get((printer_id, archive_id))
  7417. except Exception:
  7418. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  7419. return None, None
  7420. async def _max_z_for_current_print(
  7421. printer_id: int,
  7422. data: dict,
  7423. logger,
  7424. archive_id: int | None,
  7425. plate_id: int | None = None,
  7426. ) -> float | None:
  7427. """Height of the print that just finished on ``printer_id``, or None (#2547).
  7428. This number becomes the target of a real Z move, so every step here refuses
  7429. rather than guesses. A height belonging to some *other* print is the one
  7430. failure that could drive the nozzle into the model: 20 mm carried onto a
  7431. 200 mm print would command the plate up through the part.
  7432. Three independent things therefore have to agree before a height is
  7433. returned:
  7434. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  7435. when it started (see ``_bound_print``), never one found by name. A name
  7436. is not an identity: every plate of a multi-plate file shares one, and a
  7437. reprint reuses its archive row, so the newest archive with the right
  7438. name can be another plate of the same file. Support bundles show the
  7439. old name lookup doing exactly that (archive 288 for a print bound to
  7440. 169, 313 layers against 125), stopped only by the layer check below.
  7441. No binding, no move.
  7442. 2. **Identity.** The bound archive's name still has to be the finished
  7443. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  7444. because the printer echoes spaces as underscores (#3240). Exact: not a
  7445. substring, and not the completion check's tolerance for a truncated
  7446. echo.
  7447. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  7448. match the layer count the printer itself reported over MQTT for the print
  7449. that just ended. These come from genuinely different sources, so a
  7450. mismatch means the row is not this print, whatever its name says.
  7451. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  7452. plate of a multi-plate file reuses the archive row without updating its
  7453. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  7454. ``on_print_complete`` may already have flipped the status by the time we
  7455. run.
  7456. """
  7457. subtask_name = (data.get("subtask_name") or "").strip()
  7458. if not subtask_name:
  7459. # Nothing to identify the print by — refuse rather than fall back to
  7460. # "whatever ran last on this printer".
  7461. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  7462. return None
  7463. if archive_id is None:
  7464. logger.info(
  7465. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  7466. printer_id,
  7467. subtask_name,
  7468. )
  7469. return None
  7470. try:
  7471. from backend.app.models.archive import PrintArchive
  7472. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  7473. async with async_session() as db:
  7474. result = await db.execute(
  7475. select(PrintArchive).where(
  7476. PrintArchive.id == archive_id,
  7477. PrintArchive.printer_id == printer_id,
  7478. PrintArchive.status.in_(("printing", "completed")),
  7479. PrintArchive.deleted_at.is_(None),
  7480. )
  7481. )
  7482. archive = result.scalar_one_or_none()
  7483. if archive is None or not archive.file_path:
  7484. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  7485. return None
  7486. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  7487. logger.warning(
  7488. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  7489. printer_id,
  7490. archive_id,
  7491. subtask_name,
  7492. )
  7493. return None
  7494. client = printer_manager.get_client(printer_id)
  7495. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  7496. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  7497. logger.warning(
  7498. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  7499. "— refusing to move the plate on a height that may not be this print's",
  7500. printer_id,
  7501. archive.id,
  7502. archive.total_layers,
  7503. reported_layers,
  7504. )
  7505. return None
  7506. # Stored relative to the data directory, like every other archive path
  7507. # (#3240: this read a `data_dir` setting that does not exist).
  7508. path = app_settings.base_dir / archive.file_path
  7509. plate = plate_id or archive.plate_id or 1
  7510. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  7511. except Exception as e:
  7512. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  7513. return None
  7514. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  7515. """Raise the plate back into camera framing before the finish photo (#2547).
  7516. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  7517. the time ``gcode_state`` reaches FINISH the finished print sits far below
  7518. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  7519. This commands an absolute ``G1 Z`` back to just above the last printed
  7520. layer.
  7521. Absolute, not relative, is the whole safety argument. ``max_z_height +
  7522. clearance`` is a height the toolhead was physically at seconds earlier, so
  7523. it is inside the travel limits by construction and leaves the nozzle above
  7524. the part. It is also unambiguous across model families: Z is the
  7525. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  7526. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  7527. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  7528. (#2579).
  7529. Returns True if the move was sent and waited out, False if it was skipped.
  7530. """
  7531. client = printer_manager.get_client(printer_id)
  7532. if client is None:
  7533. return False
  7534. # Re-read state immediately before commanding motion. If the queue has
  7535. # already started the next print, the printer is no longer ours to move.
  7536. state = getattr(client, "state", None)
  7537. if state is None or state.state != "FINISH":
  7538. logger.info(
  7539. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  7540. printer_id,
  7541. getattr(state, "state", "unknown"),
  7542. )
  7543. return False
  7544. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  7545. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  7546. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  7547. return False
  7548. logger.info(
  7549. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  7550. printer_id,
  7551. target_z,
  7552. max_z_height,
  7553. _PLATE_RESTORE_CLEARANCE_MM,
  7554. _PLATE_RESTORE_SETTLE_SECONDS,
  7555. )
  7556. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  7557. return True
  7558. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  7559. """Drop the plate again after the finish photo (#2547).
  7560. Without this the user walks up to a finished print sitting just under the
  7561. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  7562. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  7563. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  7564. print homes anyway.
  7565. """
  7566. client = printer_manager.get_client(printer_id)
  7567. state = getattr(client, "state", None) if client else None
  7568. if client is None or state is None or state.state != "FINISH":
  7569. return
  7570. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  7571. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  7572. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  7573. """True if a queue item is about to take this printer (#2547).
  7574. The scheduler dispatches the next job the moment a print completes, and a
  7575. plate move interleaved with a print start is not a race worth having. The
  7576. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  7577. this window; this closes the head of it.
  7578. """
  7579. try:
  7580. from backend.app.models.print_queue import PrintQueueItem
  7581. async with async_session() as db:
  7582. result = await db.execute(
  7583. select(PrintQueueItem.id)
  7584. .where(
  7585. PrintQueueItem.printer_id == printer_id,
  7586. PrintQueueItem.status.in_(("pending", "printing")),
  7587. )
  7588. .limit(1)
  7589. )
  7590. return result.scalar_one_or_none() is not None
  7591. except Exception as e:
  7592. # Fail closed: if we can't tell, don't move the plate.
  7593. logging.getLogger(__name__).debug(
  7594. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  7595. )
  7596. return True
  7597. async def on_finish_photo_moment(printer_id: int, data: dict):
  7598. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  7599. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  7600. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  7601. fallback for prints that skip stage 22 (cancel, external-spool-only,
  7602. HMS halt, firmware variants). Grabs one frame via the same
  7603. external-camera / RTSP path the post-completion fallback uses, stores
  7604. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  7605. ``_background_finish_photo`` consume the cached bytes when it runs.
  7606. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  7607. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  7608. set to Smooth (#1721). No force-on now means the user's explicit
  7609. timelapse=off in the slicer send dialog is respected.
  7610. """
  7611. logger = logging.getLogger(__name__)
  7612. trigger = data.get("trigger", "unknown")
  7613. timelapse_was_active = bool(data.get("timelapse_was_active"))
  7614. logger.info(
  7615. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  7616. printer_id,
  7617. trigger,
  7618. timelapse_was_active,
  7619. )
  7620. # If a timelapse is actively recording, skip the pre-capture — the
  7621. # post-completion path will extract the last frame from the recorded
  7622. # video, which still provides the best framing (toolhead parked,
  7623. # before bed drop) without the per-layer parking side effects.
  7624. if timelapse_was_active:
  7625. logger.info(
  7626. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  7627. printer_id,
  7628. )
  7629. return
  7630. # #1790: register the producer-done event BEFORE the first await so the
  7631. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  7632. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  7633. # The `finally` below guarantees `set()` runs on every exit, including
  7634. # early returns and exceptions, so the consumer's bounded wait can't hang.
  7635. producer_done = asyncio.Event()
  7636. _stage22_finish_in_flight[printer_id] = producer_done
  7637. # #3240: also before the first await. On the FINISH-state path
  7638. # `on_print_complete` is dispatched right behind us and pops both the
  7639. # print's archive binding and its plate; read here, they are still there.
  7640. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  7641. # #2547: set once the plate has actually been raised, and read by the
  7642. # `finally` below. Declared out here so a failure anywhere after the move —
  7643. # a camera timeout, a DB error — still lowers the plate again.
  7644. restore_max_z: float | None = None
  7645. try:
  7646. async with async_session() as db:
  7647. from backend.app.api.routes.settings import get_setting
  7648. from backend.app.models.printer import Printer
  7649. capture_setting = await get_setting(db, "capture_finish_photo")
  7650. if capture_setting is not None and capture_setting.lower() != "true":
  7651. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  7652. return
  7653. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7654. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  7655. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7656. printer = result.scalar_one_or_none()
  7657. if printer is None:
  7658. logger.warning(
  7659. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  7660. printer_id,
  7661. )
  7662. return
  7663. frame_bytes: bytes | None = None
  7664. # #2708: the banked frame arrives already rotated — it comes from
  7665. # `_capture_snapshot_for_notification`, which rotates before returning.
  7666. # Every other source below is a raw grab. Tracking which lets us store
  7667. # exactly one rotation in `_stage22_finish_frames` either way.
  7668. frame_already_rotated = False
  7669. # On the FINISH-state path the End G-code has already run, and two very
  7670. # different situations arrive here needing opposite answers.
  7671. #
  7672. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  7673. # snippet may have ejected the plate — the scene in front of the camera
  7674. # is no longer the finished print, and no amount of moving the plate
  7675. # brings it back. Use the banked in-print frame instead.
  7676. #
  7677. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  7678. # than the camera frames well, and the toolhead is parked out of the
  7679. # way. That is the *best* moment available on firmware that never emits
  7680. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  7681. # back. Preferring the bank here unconditionally, as this code used to,
  7682. # is what shipped a mid-print photo with the toolhead over the part.
  7683. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  7684. banked = _inprint_frame_bank.get(printer_id)
  7685. if banked:
  7686. frame_bytes = banked
  7687. frame_already_rotated = True
  7688. logger.info(
  7689. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  7690. "frame (%d bytes) instead of a post-swap live grab",
  7691. len(banked),
  7692. )
  7693. else:
  7694. logger.warning(
  7695. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  7696. "in-print bank is empty — falling back to a live grab, which may show a "
  7697. "swapped or empty plate",
  7698. printer_id,
  7699. )
  7700. # `restore_max_z` is set only once the plate is actually up, because the
  7701. # `finally` reads it to decide whether it owes a move back down.
  7702. #
  7703. # Never on a print whose End G-code Bambuddy injected, even when the bank
  7704. # came up empty above: that machine may have just ejected its plate, and
  7705. # driving Z into whatever a swap mechanism is doing is not a risk worth
  7706. # taking for a photo of a bed we already know may be bare.
  7707. if (
  7708. frame_bytes is None
  7709. and trigger == "finish_state"
  7710. and restore_plate_enabled
  7711. and not print_dispatch_context.end_gcode_injected(printer_id)
  7712. ):
  7713. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  7714. if wants_restore is None:
  7715. logger.info(
  7716. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  7717. printer_id,
  7718. )
  7719. elif await _plate_restore_is_blocked_by_queue(printer_id):
  7720. logger.info(
  7721. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  7722. printer_id,
  7723. )
  7724. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  7725. restore_max_z = wants_restore
  7726. # Chamber light for the live capture below (#1655). The banked frame
  7727. # above was taken without it, like every in-print bank.
  7728. async with camera_light(printer if frame_bytes is None else None):
  7729. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  7730. from backend.app.api.routes.camera import live_frame_for_capture
  7731. from backend.app.services.external_camera import capture_frame
  7732. # #2707: this used to collide with the live view and fail, which is
  7733. # how finish-photo notifications went out with no image attached.
  7734. # Leaving frame_bytes None keeps the rest of the fallback chain.
  7735. defer, buffered = live_frame_for_capture(printer_id)
  7736. if defer:
  7737. frame_bytes = buffered
  7738. else:
  7739. frame_bytes = await capture_frame(
  7740. printer.external_camera_url,
  7741. printer.external_camera_type or "mjpeg",
  7742. snapshot_url=printer.external_camera_snapshot_url,
  7743. )
  7744. if frame_bytes:
  7745. logger.info(
  7746. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  7747. len(frame_bytes),
  7748. )
  7749. elif frame_bytes is None:
  7750. from backend.app.api.routes.camera import get_buffered_frame
  7751. buffered = get_buffered_frame(printer_id)
  7752. if buffered:
  7753. frame_bytes = buffered
  7754. logger.info(
  7755. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  7756. len(frame_bytes),
  7757. )
  7758. else:
  7759. from backend.app.services.camera import capture_camera_frame_bytes
  7760. frame_bytes = await capture_camera_frame_bytes(
  7761. ip_address=printer.ip_address,
  7762. access_code=printer.access_code,
  7763. model=printer.model,
  7764. timeout=15,
  7765. )
  7766. if frame_bytes:
  7767. logger.info(
  7768. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  7769. len(frame_bytes),
  7770. )
  7771. if frame_bytes:
  7772. if not frame_already_rotated:
  7773. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  7774. _stage22_finish_frames[printer_id] = frame_bytes
  7775. else:
  7776. logger.warning(
  7777. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  7778. printer_id,
  7779. )
  7780. except Exception as e:
  7781. logger.warning(
  7782. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  7783. printer_id,
  7784. e,
  7785. )
  7786. finally:
  7787. # #2547: we raised the plate, so we own lowering it — including when the
  7788. # capture above failed or threw partway through.
  7789. if restore_max_z is not None:
  7790. try:
  7791. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  7792. except Exception as e:
  7793. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7794. # #1790: always unblock the consumer's bounded wait — whether we stored
  7795. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  7796. # dict entry by the consumer doesn't affect signalling.
  7797. producer_done.set()
  7798. def _subtask_name_from_filename(filename: str) -> str:
  7799. """Recover the subtask name a print command would have carried for *filename*.
  7800. The dispatcher derives the printer-facing subtask name from the archive's
  7801. file name, so stripping the extensions back off gives the value MQTT echoes
  7802. on completion. Only the two extensions Bambuddy actually stores are removed,
  7803. and in the order they nest (``.gcode.3mf``), so a model whose own name
  7804. contains a dot -- ``My.Model.3mf`` -- keeps it.
  7805. """
  7806. name = PurePosixPath(filename).name
  7807. for suffix in (".3mf", ".gcode"):
  7808. if name.lower().endswith(suffix):
  7809. name = name[: -len(suffix)]
  7810. return name
  7811. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  7812. """Whether the subtask name is the printed 3MF's own file name.
  7813. A print started from the printer's screen reports the same full name, with
  7814. its extension, as both subtask and file (#3009). A dispatched print reports
  7815. a bare subtask name; one that merely ends in ".3mf" can be a model named
  7816. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  7817. """
  7818. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  7819. return False
  7820. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  7821. # How the printer marks a subtask name it had to cut short. Observed on real
  7822. # hardware at ~100 characters, but the cut-off is not a fixed character count
  7823. # (a name with multibyte characters came back at 98), so match the marker
  7824. # rather than a length.
  7825. _SUBTASK_TRUNCATION_MARKER = "..."
  7826. def _normalise_subtask_name(name: str) -> str:
  7827. """Canonical form for comparing a dispatched name against MQTT's echo.
  7828. The printer does not echo the name back verbatim: it substitutes
  7829. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  7830. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  7831. The 3MF lookup in this module has always known that -- it builds
  7832. space-to-underscore variants of every candidate filename, and its
  7833. directory search normalises both sides before comparing. This exists so
  7834. the completion check reads the same rule from the same place instead of
  7835. growing its own, which is exactly how it came to disagree (#2829).
  7836. A space at either end is substituted too: ``Part .gcode.3mf`` is
  7837. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  7838. are dropped after the substitution so both sides agree (#3241).
  7839. """
  7840. return name.strip().replace(" ", "_").strip("_").casefold()
  7841. def _3mf_files_for_print(paths: list[str], search_term: str) -> list[str]:
  7842. """The 3MF files of the printer's folder listings that are this print's.
  7843. A file of the print's own name wins, in whichever folder. Only without one
  7844. is a file that merely contains the name taken, and then only when it is
  7845. the one such file: "Cube_large.3mf" is not "Cube"'s file, and of several
  7846. candidates none can be told apart. Paths keep the listings' order.
  7847. """
  7848. threemf = [path for path in paths if path.lower().endswith(".3mf")]
  7849. exact = [path for path in threemf if _subtask_names_match(_subtask_name_from_filename(path), search_term)]
  7850. if exact:
  7851. return exact
  7852. term = _normalise_subtask_name(search_term)
  7853. partial = [path for path in threemf if term in _normalise_subtask_name(PurePosixPath(path).name)]
  7854. if len(partial) > 1:
  7855. logging.getLogger(__name__).info(
  7856. "Several 3MF files contain %r and none is named for it: %s", search_term, partial
  7857. )
  7858. return []
  7859. return partial
  7860. def _subtask_names_match(expected: str, observed: str) -> bool:
  7861. """Whether two subtask names describe the same print.
  7862. Beyond the space/underscore substitution, the printer truncates long names
  7863. and marks the cut with ``...``. A truncated echo has to count as a match or
  7864. every print with a long name strands its queue item the same way.
  7865. """
  7866. expected_n = _normalise_subtask_name(expected)
  7867. observed_n = _normalise_subtask_name(observed)
  7868. if expected_n == observed_n:
  7869. return True
  7870. # Either side can be the truncated one: the printer truncates what it
  7871. # echoes, and an archive whose own filename was recorded from a previous
  7872. # truncated echo carries the marker too.
  7873. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  7874. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  7875. continue
  7876. # The full side has lost its edge underscores; a cut that lands right
  7877. # after one keeps it, so drop it here too (#3241). Nothing left before
  7878. # the marker is no evidence of anything, and must not match every name.
  7879. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  7880. if kept and full.startswith(kept):
  7881. return True
  7882. return False
  7883. async def _queue_item_dispatched_name(db, item) -> str:
  7884. """The subtask name *item* was dispatched under, or "" when unknowable.
  7885. A row with no archive, or an archive with no file name, is unverifiable
  7886. rather than wrong; every caller answers that with its permissive branch.
  7887. """
  7888. if item.archive_id is None:
  7889. return ""
  7890. from backend.app.models.archive import PrintArchive
  7891. archive = await db.get(PrintArchive, item.archive_id)
  7892. if archive is None or not archive.filename:
  7893. return ""
  7894. return _subtask_name_from_filename(archive.filename)
  7895. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  7896. """Whether this completion event is plausibly about *item*'s print.
  7897. The caller finds its queue row by printer and ``status='printing'`` alone,
  7898. which is all a completion event gives it -- there is no run identifier in
  7899. the MQTT payload to match on. That makes the lookup indiscriminate: any
  7900. completion delivered for this printer closes whichever row happens to be
  7901. printing, however unrelated. Comparing the subtask name against the archive
  7902. the row was dispatched with costs one primary-key load and rules that out.
  7903. Deliberately permissive: it answers False only on a positive disagreement
  7904. between two names we actually have. A row with no archive, an archive with
  7905. no file name, or an event with no subtask name is unverifiable rather than
  7906. wrong, and refusing those would strand the item in ``printing`` and wedge
  7907. the printer's queue -- a worse failure than the one being prevented.
  7908. """
  7909. observed = (data.get("subtask_name") or "").strip()
  7910. if not observed or item.archive_id is None:
  7911. return True
  7912. from backend.app.models.archive import PrintArchive
  7913. archive = await db.get(PrintArchive, item.archive_id)
  7914. if archive is None or not archive.filename:
  7915. return True
  7916. expected = _subtask_name_from_filename(archive.filename)
  7917. if not expected or _subtask_names_match(expected, observed):
  7918. return True
  7919. logging.getLogger(__name__).warning(
  7920. "Ignoring print completion for queue item %s: it was dispatched as %r "
  7921. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  7922. "printing rather than closing a run this event is not about.",
  7923. item.id,
  7924. expected,
  7925. archive.id,
  7926. archive.filename,
  7927. observed,
  7928. )
  7929. return False
  7930. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  7931. """Spend the 3MF download cache on a still-empty fallback archive.
  7932. ``on_print_complete`` drops the cache as its first act, which deletes the
  7933. file. If the cover endpoint (or anything else) pulled the 3MF while the
  7934. print ran and the archive never got one, this is the last moment those bytes
  7935. exist (#2957).
  7936. """
  7937. logger = logging.getLogger(__name__)
  7938. names = [
  7939. n
  7940. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  7941. if n
  7942. ]
  7943. for name in names:
  7944. try:
  7945. cached = get_cached_3mf(printer_id, name)
  7946. # The print has ended: its completion prices the archive, so no
  7947. # print-start estimate is scheduled to race it.
  7948. if cached and await try_recover_fallback_archive(printer_id, name, cached, price=False):
  7949. return
  7950. except Exception as e:
  7951. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  7952. # Longest the print's end waits for its file to be deleted from the SD card
  7953. _SD_CLEANUP_BUDGET_SECONDS = 45.0
  7954. async def _cleanup_sd_card_after_print(
  7955. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  7956. ) -> None:
  7957. """Delete a finished print's file from the printer's SD card."""
  7958. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  7959. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  7960. # auto-start files found in root on power cycle, causing ghost prints.
  7961. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  7962. try:
  7963. if subtask_name:
  7964. archive_filename: str | None = None
  7965. async with async_session() as db:
  7966. from backend.app.models.archive import PrintArchive
  7967. from backend.app.models.printer import Printer
  7968. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7969. printer = result.scalar_one_or_none()
  7970. if archive_id:
  7971. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  7972. archive_filename = archive_row.scalar_one_or_none()
  7973. if printer:
  7974. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  7975. from backend.app.utils.filename import derive_remote_filename
  7976. # Primary candidate: the exact path the dispatcher uploaded to
  7977. # (derived from archive.filename via the same rule as upload).
  7978. # Without it, a library row that ended up with a doubled
  7979. # .gcode.3mf (#1542) leaves the real file behind because the
  7980. # subtask_name + ext fallbacks below don't match what's on the
  7981. # SD card. Fallbacks remain for archive-less prints (subtask
  7982. # never resolved to an archive) and for older naming variants.
  7983. candidate_paths: list[str] = []
  7984. if archive_filename:
  7985. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  7986. for ext in (".3mf", ".gcode"):
  7987. fallback = f"/{subtask_name}{ext}"
  7988. if fallback not in candidate_paths:
  7989. candidate_paths.append(fallback)
  7990. # Three outcomes track across all candidates so the final log
  7991. # line reflects what actually happened. The A1 in #1721 always
  7992. # ends here with ``any_not_found=True`` and the others False
  7993. # — its firmware auto-cleans the SD card before our cleanup
  7994. # runs, every candidate FTP-DELE returns 550, and the old
  7995. # code burned 3 retries × 2 s × 3 candidates per print
  7996. # logging a misleading "may linger" WARNING on a successful
  7997. # print.
  7998. any_deleted = False
  7999. any_real_failure = False
  8000. any_not_found = False
  8001. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  8002. for remote_path in candidate_paths:
  8003. if PurePosixPath(remote_path).name.lower() in files_in_use:
  8004. logger.info(
  8005. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  8006. remote_path,
  8007. printer.name,
  8008. )
  8009. continue
  8010. # Retry only the FAILED case — 550 NOT_FOUND will never
  8011. # recover by waiting, so a "file isn't here" answer
  8012. # advances immediately to the next candidate without
  8013. # consuming the retry budget.
  8014. for attempt in range(1, 4):
  8015. try:
  8016. delete_result = await delete_file_async(
  8017. printer.ip_address,
  8018. printer.access_code,
  8019. remote_path,
  8020. printer_model=printer.model,
  8021. )
  8022. except Exception as e:
  8023. delete_result = DeleteResult.FAILED
  8024. logger.warning(
  8025. "SD card cleanup attempt %d/3 raised for %s: %s",
  8026. attempt,
  8027. remote_path,
  8028. e,
  8029. )
  8030. if delete_result == DeleteResult.DELETED:
  8031. any_deleted = True
  8032. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  8033. break
  8034. if delete_result == DeleteResult.NOT_FOUND:
  8035. any_not_found = True
  8036. break # 550 will not recover; try next candidate
  8037. # FAILED: real error — retry with backoff, then give up
  8038. if attempt < 3:
  8039. await asyncio.sleep(2)
  8040. else:
  8041. any_real_failure = True
  8042. logger.warning(
  8043. "SD card cleanup failed after 3 attempts for %s "
  8044. "(network/auth/transient error — file may linger on SD card)",
  8045. remote_path,
  8046. )
  8047. if not any_deleted and not any_real_failure and any_not_found:
  8048. # Every candidate said "not here." Either the printer
  8049. # firmware swept the SD card itself (common on A1) or the
  8050. # dispatcher's upload path doesn't match our candidate
  8051. # rule. Either way: nothing to clean up, no warning.
  8052. logger.debug(
  8053. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  8054. "(printer likely self-cleaned)",
  8055. printer.name,
  8056. )
  8057. except Exception as e:
  8058. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  8059. async def on_print_complete(printer_id: int, data: dict):
  8060. """Handle print completion - update the archive status.
  8061. The printer counts as printing until the print's usage is booked (or this
  8062. ends), so the AMS remain% weight sync can't charge it a second time while
  8063. the usage tracker works (WU-3). Marked before the first await.
  8064. """
  8065. from backend.app.services.usage_tracker import done_completing, mark_completing
  8066. mark_completing(printer_id)
  8067. try:
  8068. await _close_out_print(printer_id, data)
  8069. finally:
  8070. done_completing(printer_id)
  8071. async def _close_out_print(printer_id: int, data: dict):
  8072. import time
  8073. logger = logging.getLogger(__name__)
  8074. start_time = time.time()
  8075. def log_timing(section: str):
  8076. elapsed = time.time() - start_time
  8077. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  8078. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  8079. octoeverywhere_detection_service.reset_printer(printer_id)
  8080. # A kill-switch stop sends its provider notification immediately. Keep the
  8081. # task so the later notification path can await it and avoid a duplicate;
  8082. # if that immediate attempt failed, the regular completion path retries.
  8083. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  8084. # Last chance before the bytes go: if this print's archive is still an empty
  8085. # fallback and something downloaded the 3MF while it ran, fill the archive in
  8086. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  8087. # below deletes the file (#2957).
  8088. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  8089. # A pending cool-off retry has nothing left to recover for — the cache is
  8090. # about to be dropped and the print is over.
  8091. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  8092. if retry_task and not retry_task.done():
  8093. retry_task.cancel()
  8094. # Drop the 3MF download cache for this printer (#972). The print is over,
  8095. # nothing else legitimately needs the bytes; keeping them would only risk
  8096. # handing a stale file to the next print if it reuses the same name.
  8097. clear_3mf_cache(printer_id)
  8098. try:
  8099. ws_data = {
  8100. "status": data.get("status"),
  8101. "filename": data.get("filename"),
  8102. "subtask_name": data.get("subtask_name"),
  8103. "timelapse_was_active": data.get("timelapse_was_active"),
  8104. }
  8105. await ws_manager.send_print_complete(printer_id, ws_data)
  8106. log_timing("WebSocket send_print_complete")
  8107. except Exception as e:
  8108. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  8109. # Capture user info before clearing (needed for print log entry)
  8110. _print_user_info = printer_manager.get_current_print_user(printer_id)
  8111. # Clear current print user tracking (Issue #206)
  8112. printer_manager.clear_current_print_user(printer_id)
  8113. # If the user explicitly stopped this print from the queue UI the printer will
  8114. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  8115. # correct "print stopped" notification/email is sent instead of a failure alert.
  8116. _raw_status = data.get("status", "completed")
  8117. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  8118. logger.info(
  8119. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  8120. _raw_status,
  8121. printer_id,
  8122. )
  8123. data = {**data, "status": "cancelled"}
  8124. elif printer_id in _kill_switch_stopped and _raw_status in ("failed", "aborted"):
  8125. logger.info(
  8126. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (stopped by the printer kill switch)",
  8127. _raw_status,
  8128. printer_id,
  8129. )
  8130. data = {**data, "status": "cancelled", "_kill_switch": True}
  8131. _user_stopped_printers.discard(printer_id)
  8132. _kill_switch_stopped.discard(printer_id)
  8133. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  8134. # may have left material on the bed: a user can cancel ten hours into a
  8135. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  8136. # touchscreen-stop reports `aborted` rather than `cancelled` because
  8137. # `_user_stopped_printers` is only populated when the user stops via the
  8138. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  8139. # which auto-dispatched the next queued print onto a fouled bed two seconds
  8140. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  8141. # Auto Off power cycles and Bambuddy restarts.
  8142. try:
  8143. notify_live_activities.print_finished(printer_id, data)
  8144. except Exception:
  8145. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  8146. _final_status = data.get("status", "completed")
  8147. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  8148. printer_manager.set_awaiting_plate_clear(printer_id, True)
  8149. # MQTT relay - publish print complete
  8150. try:
  8151. printer_info = printer_manager.get_printer(printer_id)
  8152. if printer_info:
  8153. await mqtt_relay.on_print_complete(
  8154. printer_id,
  8155. printer_info.name,
  8156. printer_info.serial_number,
  8157. data.get("filename", ""),
  8158. data.get("subtask_name", ""),
  8159. data.get("status", "completed"),
  8160. )
  8161. except Exception:
  8162. pass # Don't fail print complete callback if MQTT fails
  8163. filename = data.get("filename", "")
  8164. subtask_name = data.get("subtask_name", "")
  8165. if not filename and not subtask_name:
  8166. # Which print ended can't be told: the printer reported no name since
  8167. # Bambuddy started (a print that failed while preparing, a calibration).
  8168. # Charge nothing, but close the print session, which otherwise kept the
  8169. # AMS weight sync off until the next print (AS-5). A print archived as
  8170. # running is closed and charged by the reconnect reconcile.
  8171. logger.warning("Print complete without filename or subtask_name")
  8172. try:
  8173. from backend.app.services.usage_tracker import discard_session
  8174. async with async_session() as db:
  8175. await discard_session(db, printer_id)
  8176. except Exception as e:
  8177. logger.warning("Failed to clear print session for printer %s: %s", printer_id, e)
  8178. return
  8179. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  8180. # Build list of possible keys to try (matching how they were registered in on_print_start)
  8181. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  8182. # Find the archive for this print
  8183. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  8184. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  8185. archive_id = None
  8186. for key in possible_keys:
  8187. archive_id = _active_prints.pop(key, None)
  8188. if archive_id:
  8189. _owned_print_archive_ids.discard(archive_id)
  8190. logger.info("Found archive %s with key %s", archive_id, key)
  8191. # Also clean up the printer's other keys pointing to this archive;
  8192. # another printer's are a plate of it still printing there.
  8193. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id and k[0] == printer_id]
  8194. for k in keys_to_remove:
  8195. _active_prints.pop(k, None)
  8196. break
  8197. # The archive bound when the print started, before the name search below.
  8198. # Only this one may give the finish-photo plate restore a height (#3240):
  8199. # the search matches names by substring.
  8200. bound_archive_id = archive_id
  8201. if not archive_id and data.get("_reconciled") and data.get("_reconciled_archive_id"):
  8202. # The reconcile names the archive whose run on this printer it
  8203. # closes. Only while that run is open: the print's real end may have
  8204. # closed it meanwhile, or closed the print without managing to write
  8205. # it, and either way there is nothing left to end twice.
  8206. if await _archive_of_open_run(printer_id) != data["_reconciled_archive_id"]:
  8207. logger.info(
  8208. "[RECONCILE] Archive %s has no run open on printer %s any more; nothing to close",
  8209. data["_reconciled_archive_id"],
  8210. printer_id,
  8211. )
  8212. return
  8213. archive_id = data["_reconciled_archive_id"]
  8214. ending_job = str(data.get("subtask_id") or "").strip()
  8215. if not archive_id and ending_job not in ("", "0"):
  8216. # Not bound (a restart since the start): this job's run, open on the
  8217. # printer. Only by its job id: a run open there can be of the print
  8218. # running now, while the end is of an earlier one closed late (the
  8219. # restart's reconcile of a missed end).
  8220. archive_id = await _archive_of_open_run(printer_id, subtask_id=ending_job)
  8221. if archive_id:
  8222. logger.info("Found archive %s by the run of job %s open on printer %s", archive_id, ending_job, printer_id)
  8223. if not archive_id:
  8224. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  8225. async with async_session() as db:
  8226. from backend.app.models.archive import PrintArchive
  8227. # Try matching by subtask_name (stored as print_name) first. The
  8228. # same name rule as the queue's completion check: a name inside
  8229. # another ("Clip" in "Cable Clip") is a different print, and the
  8230. # printer's underscores for spaces and truncation still match.
  8231. if subtask_name:
  8232. printing = await db.scalars(
  8233. select(PrintArchive)
  8234. .where(PrintArchive.printer_id == printer_id)
  8235. .where(PrintArchive.status == "printing")
  8236. .order_by(PrintArchive.created_at.desc())
  8237. )
  8238. # A print started from the printer's screen reports its file
  8239. # name, extensions included, as the subtask (#3009).
  8240. reported = {subtask_name, _subtask_name_from_filename(subtask_name)}
  8241. archive = next(
  8242. (
  8243. candidate
  8244. for candidate in printing
  8245. if any(
  8246. (candidate.print_name and _subtask_names_match(candidate.print_name, name))
  8247. or (
  8248. candidate.filename
  8249. and _subtask_names_match(_subtask_name_from_filename(candidate.filename), name)
  8250. )
  8251. for name in reported
  8252. )
  8253. ),
  8254. None,
  8255. )
  8256. if archive:
  8257. archive_id = archive.id
  8258. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  8259. # Also try by filename
  8260. if not archive_id and filename:
  8261. result = await db.execute(
  8262. select(PrintArchive)
  8263. .where(PrintArchive.printer_id == printer_id)
  8264. .where(PrintArchive.filename == filename)
  8265. .where(PrintArchive.status == "printing")
  8266. .order_by(PrintArchive.created_at.desc())
  8267. .limit(1)
  8268. )
  8269. archive = result.scalar_one_or_none()
  8270. if archive:
  8271. archive_id = archive.id
  8272. # Bounded: a printer whose FTP hangs on DELE took up to 3 candidates x 3
  8273. # attempts x a 60 s timeout, about nine minutes, before the queue item was
  8274. # closed below. The stranded-job closer gives up after five and closed it
  8275. # first, so the job's auto-off and its billing never ran. Inline rather
  8276. # than in the background, so the next job of the same file isn't released
  8277. # (and uploaded under the name being deleted) while the cleanup still
  8278. # works on it. A delete already sent may still finish in its FTP thread
  8279. # after the cutoff, as one past delete_file_async's own timeout always did.
  8280. try:
  8281. await asyncio.wait_for(
  8282. _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger),
  8283. timeout=_SD_CLEANUP_BUDGET_SECONDS,
  8284. )
  8285. except TimeoutError:
  8286. logger.warning(
  8287. "SD card cleanup on printer %s took over %ss; leaving the file there and closing the print",
  8288. printer_id,
  8289. _SD_CLEANUP_BUDGET_SECONDS,
  8290. )
  8291. log_timing("SD card cleanup")
  8292. # Update queue item status early — must run before the archive_id early-return
  8293. # so queue items don't get stuck in "printing" when archive lookup fails.
  8294. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  8295. queue_item_id = None
  8296. billing_run_id: str | None = None
  8297. billing_user_id: int | None = None
  8298. billing_cost_center_id: int | None = None
  8299. billing_plate_id: int | None = None
  8300. queue_status = None
  8301. queue_auto_off = False
  8302. try:
  8303. from backend.app.core.database import run_with_retry
  8304. from backend.app.models.print_queue import PrintQueueItem
  8305. async def _update_queue_status(db):
  8306. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  8307. nonlocal queue_item_id, queue_status, queue_auto_off
  8308. result = await db.execute(
  8309. select(PrintQueueItem)
  8310. .where(PrintQueueItem.printer_id == printer_id)
  8311. .where(PrintQueueItem.status == "printing")
  8312. )
  8313. printing_items = list(result.scalars().all())
  8314. if len(printing_items) > 1:
  8315. logger.warning(
  8316. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  8317. printer_id,
  8318. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  8319. )
  8320. item = printing_items[0] if printing_items else None
  8321. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  8322. return
  8323. if item:
  8324. queue_status = data.get("status", "completed")
  8325. # MQTT sends "aborted" for cancelled prints; normalise to
  8326. # "cancelled" so it matches the queue schema Literal.
  8327. if queue_status == "aborted":
  8328. queue_status = "cancelled"
  8329. item.status = queue_status
  8330. item.completed_at = datetime.now(timezone.utc)
  8331. if queue_status == "failed" and not item.error_message:
  8332. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  8333. # Bump usage counters on the source library file so admins can
  8334. # sort by "last printed" and (eventually) auto-purge stale
  8335. # files — #1008.
  8336. await _bump_library_file_usage_if_completed(db, item, queue_status)
  8337. await db.commit()
  8338. queue_item_id = item.id
  8339. billing_run_id = item.billing_run_id
  8340. billing_user_id = item.created_by_id
  8341. billing_cost_center_id = item.cost_center_id
  8342. billing_plate_id = item.plate_id
  8343. queue_auto_off = item.auto_off_after
  8344. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  8345. await run_with_retry(_update_queue_status, label="queue status update")
  8346. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  8347. # their own sessions and have their own error handling — no retry needed.
  8348. if queue_item_id is not None:
  8349. # Batch orders (#342): this run may have been the last one an order
  8350. # owed. Re-evaluate here rather than lazily on read, so a finished
  8351. # order reports itself complete without someone opening the page.
  8352. try:
  8353. from backend.app.services.print_batch import refresh_batch_status_for_item
  8354. async with async_session() as db:
  8355. await refresh_batch_status_for_item(db, queue_item_id)
  8356. await db.commit()
  8357. except Exception as e:
  8358. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  8359. # MQTT relay - publish queue job completed
  8360. try:
  8361. printer_info = printer_manager.get_printer(printer_id)
  8362. await mqtt_relay.on_queue_job_completed(
  8363. job_id=queue_item_id,
  8364. filename=filename or subtask_name,
  8365. printer_id=printer_id,
  8366. printer_name=printer_info.name if printer_info else "Unknown",
  8367. status=queue_status,
  8368. )
  8369. except Exception:
  8370. pass # Don't fail if MQTT fails
  8371. # Check if queue is now empty and send notification
  8372. try:
  8373. from sqlalchemy import func as sa_func
  8374. async with async_session() as db:
  8375. count_result = await db.execute(
  8376. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  8377. )
  8378. pending_count = count_result.scalar() or 0
  8379. if pending_count == 0:
  8380. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  8381. completed_result = await db.execute(
  8382. select(sa_func.count(PrintQueueItem.id)).where(
  8383. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  8384. PrintQueueItem.completed_at >= today_start,
  8385. )
  8386. )
  8387. completed_count = completed_result.scalar() or 1
  8388. await notification_service.on_queue_completed(
  8389. completed_count=completed_count,
  8390. db=db,
  8391. )
  8392. except Exception:
  8393. pass # Don't fail if notification fails
  8394. # Handle auto_off_after - power off printer if the queue item opted
  8395. # in. Delegates to the smart-plug manager so the off honours each
  8396. # plug's configured strategy (time delay or temperature threshold),
  8397. # is cancelled if the printer starts printing again, and never cuts
  8398. # power on a loaded print (#1890). Previously an inline block here
  8399. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  8400. # timeout regardless of print state — cutting a touchscreen reprint.
  8401. if queue_auto_off:
  8402. try:
  8403. async with async_session() as db:
  8404. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  8405. except Exception as e:
  8406. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  8407. except Exception as e:
  8408. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  8409. log_timing("Queue item update")
  8410. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  8411. # Must run before archive_id early-return so it fires for all prints (including
  8412. # prints started from BambuStudio/touchscreen that have no archive).
  8413. if data.get("status") == "completed":
  8414. try:
  8415. from backend.app.api.routes.settings import get_setting
  8416. async with async_session() as db:
  8417. threshold_str = await get_setting(db, "bed_cooled_threshold")
  8418. threshold = float(threshold_str) if threshold_str else 35.0
  8419. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  8420. async with async_session() as db:
  8421. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  8422. if providers:
  8423. _bed_cool_waiters[printer_id] = {
  8424. "threshold": threshold,
  8425. "filename": filename or subtask_name or "",
  8426. "registered_at": time.time(),
  8427. }
  8428. logger.info(
  8429. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  8430. printer_id,
  8431. threshold,
  8432. )
  8433. else:
  8434. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  8435. except Exception as e:
  8436. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  8437. # Capture the slicer estimate before usage tracking runs. The tracker may
  8438. # update archive.cost with this run's measured cost; billing partial runs
  8439. # against that already-partial value would discount the charge twice.
  8440. billing_planned_grams: float | None = None
  8441. billing_base_cost: float | None = None
  8442. if archive_id:
  8443. try:
  8444. async with async_session() as db:
  8445. from backend.app.models.archive import PrintArchive
  8446. billing_archive = await db.get(PrintArchive, archive_id)
  8447. if billing_archive:
  8448. billing_path = (
  8449. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  8450. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8451. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  8452. billing_archive,
  8453. billing_path,
  8454. billing_plate_id
  8455. if billing_plate_id is not None
  8456. else _get_start_plate_id(printer_id, archive_id),
  8457. )
  8458. except Exception as e:
  8459. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  8460. # --- Track filament consumption (must run before archive_id early-return so usage
  8461. # is recorded even when auto-archive is disabled) ---
  8462. usage_results: list[dict] = []
  8463. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  8464. stored_ams_mapping = data.get("ams_mapping")
  8465. # Fallback to _print_ams_mappings for queue/reprint (set before print starts).
  8466. # Drained either way, like the plate below: left over, it would be read by
  8467. # the archive's next run, dispatched without a mapping.
  8468. registered_ams_mapping = _print_ams_mappings.pop((printer_id, archive_id), None) if archive_id else None
  8469. if not stored_ams_mapping:
  8470. stored_ams_mapping = registered_ams_mapping
  8471. # Always drain the plate_id register on completion — the session already
  8472. # consumed it at print-start injection; leaving it would leak into the next
  8473. # print on the same archive_id (rare but possible with reprints) (#1697).
  8474. # Capture the popped value so the completion notification can scope the
  8475. # archive-level (summed-across-plates per #1593) filament + time totals
  8476. # down to the single plate that was actually printed (#1785).
  8477. notify_plate_id: int | None = None
  8478. if archive_id:
  8479. notify_plate_id = _print_plate_ids.pop((printer_id, archive_id), None)
  8480. # The start estimate must not outlive the real cost written below (COST-4).
  8481. if archive_id:
  8482. await _settle_archive_cost_estimate(archive_id)
  8483. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  8484. try:
  8485. async with async_session() as db:
  8486. from backend.app.api.routes.settings import get_setting
  8487. _spoolman_on = await get_setting(db, "spoolman_enabled")
  8488. if not _spoolman_on or _spoolman_on.lower() != "true":
  8489. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  8490. async with async_session() as db:
  8491. usage_results = await usage_on_print_complete(
  8492. printer_id,
  8493. data,
  8494. printer_manager,
  8495. db,
  8496. archive_id=archive_id,
  8497. ams_mapping=stored_ams_mapping,
  8498. )
  8499. if usage_results:
  8500. await ws_manager.broadcast(
  8501. {
  8502. "type": "spool_usage_logged",
  8503. "printer_id": printer_id,
  8504. "usage": usage_results,
  8505. }
  8506. )
  8507. log_timing("Usage tracker")
  8508. except Exception as e:
  8509. logger.warning("Usage tracker on_print_complete failed: %s", e)
  8510. # Drop the print-start context unconditionally — the Spoolman branch above
  8511. # skips the internal tracker entirely, so nothing else would clear what
  8512. # print start captured, and a row surviving its print would be restored
  8513. # onto the next one after a restart.
  8514. try:
  8515. from backend.app.services.usage_tracker import discard_session
  8516. async with async_session() as db:
  8517. await discard_session(db, printer_id)
  8518. except Exception as e:
  8519. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  8520. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  8521. # A partial run's cost from the Spoolman spools it was charged to; the
  8522. # built-in inventory's comes in usage_results.
  8523. spoolman_run_cost: float | None = None
  8524. if archive_id:
  8525. if data.get("status") == "completed":
  8526. try:
  8527. await _report_spoolman_usage(printer_id, archive_id)
  8528. log_timing("Spoolman usage report")
  8529. except Exception as e:
  8530. logger.warning("Spoolman usage reporting failed: %s", e)
  8531. else:
  8532. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  8533. try:
  8534. async with async_session() as db:
  8535. spoolman_run_cost = await _cleanup_spoolman_tracking(
  8536. printer_id,
  8537. archive_id,
  8538. db,
  8539. last_layer_num=data.get("last_layer_num"),
  8540. last_progress=data.get("last_progress"),
  8541. status=data.get("status") or "failed",
  8542. )
  8543. except Exception as e:
  8544. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  8545. await _release_archived_spoolman_slots(printer_id)
  8546. log_timing("Filament usage tracking")
  8547. if not archive_id:
  8548. # The printer's own calibration run has no archive by design, so this
  8549. # arrives here every time one finishes. Returning before the no-archive
  8550. # notification keeps a calibration from being announced as a finished
  8551. # print. Everything above this point has already run — the plate-clear
  8552. # gate, the queue reconciliation, the SD-card cleanup — so only the
  8553. # notification is skipped.
  8554. if is_internal_printer_job(filename, subtask_name):
  8555. logger.info(
  8556. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  8557. filename,
  8558. subtask_name,
  8559. )
  8560. return
  8561. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  8562. # Still send print-complete/failed/stopped notifications even without an archive.
  8563. # Try to enrich with queue/library-file data so user-specific emails work too.
  8564. async def _notify_no_archive():
  8565. try:
  8566. async with async_session() as db:
  8567. from backend.app.models.library import LibraryFile
  8568. from backend.app.models.print_queue import PrintQueueItem
  8569. from backend.app.models.printer import Printer
  8570. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8571. printer_obj = result.scalar_one_or_none()
  8572. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  8573. # Only the queue item this completion itself closed (the
  8574. # reconciliation above, which checks the run belongs to it).
  8575. # A print started outside Bambuddy closed none, and must not
  8576. # borrow an earlier job's owner, email or times.
  8577. no_archive_data: dict | None = None
  8578. try:
  8579. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  8580. if queue_item:
  8581. no_archive_data = {"created_by_id": queue_item.created_by_id}
  8582. # How long it really ran, as the archive path reports it (#1198).
  8583. started = to_naive_utc(queue_item.started_at)
  8584. ended = to_naive_utc(queue_item.completed_at)
  8585. # Not for a completion reconciled at reconnect: it
  8586. # ended at an unknown time while the printer was
  8587. # offline, and "now" is the reconnect (DB-C9).
  8588. if (
  8589. not data.get("_reconciled")
  8590. and started
  8591. and ended
  8592. and (ended - started).total_seconds() > 0
  8593. ):
  8594. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  8595. # Estimated time: the queue item caches it from its
  8596. # archive or library file; otherwise read the library
  8597. # file's metadata (LibraryFile has no column for it).
  8598. if queue_item.print_time_seconds:
  8599. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  8600. elif queue_item.library_file_id:
  8601. lib_result = await db.execute(
  8602. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  8603. )
  8604. lib_file = lib_result.scalar_one_or_none()
  8605. estimate = (
  8606. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  8607. )
  8608. if estimate:
  8609. no_archive_data["print_time_seconds"] = estimate
  8610. except Exception as lookup_err:
  8611. logger.debug(
  8612. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  8613. )
  8614. # Enrich with usage tracker results (captured in enclosing scope)
  8615. if usage_results:
  8616. if no_archive_data is None:
  8617. no_archive_data = {}
  8618. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  8619. if total_from_usage > 0:
  8620. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8621. no_archive_data["usage_results"] = usage_results
  8622. # Try MQTT remaining_time for print duration when no queue/library data
  8623. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  8624. mqtt_remaining = data.get("remaining_time")
  8625. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  8626. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  8627. ps = data.get("status", "completed")
  8628. logger.info(
  8629. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  8630. )
  8631. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8632. await notification_service.on_print_complete(
  8633. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  8634. )
  8635. else:
  8636. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8637. # Send user-specific email if we have a created_by_id
  8638. if no_archive_data and no_archive_data.get("created_by_id"):
  8639. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8640. await _dispatch_user_print_email(
  8641. ps,
  8642. no_archive_data["created_by_id"],
  8643. p_name,
  8644. raw_filename,
  8645. db,
  8646. )
  8647. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  8648. except Exception as e:
  8649. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  8650. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  8651. return
  8652. log_timing("Archive lookup")
  8653. # Update archive status
  8654. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  8655. try:
  8656. async with async_session() as db:
  8657. service = ArchiveService(db)
  8658. status = data.get("status", "completed")
  8659. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  8660. if hms_errors:
  8661. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  8662. failure_reason = derive_failure_reason(status, hms_errors)
  8663. if data.get("_reconciled") and (status == "aborted" or (status == "failed" and not failure_reason)):
  8664. # A reconciled completion closes out a stale archive at
  8665. # reconnect — it is not a user action, so don't mislabel it
  8666. # "userCancelled". It shares the stale-cleanup path's key
  8667. # (issue #2974) and records that the real end time is unknown,
  8668. # which is also why its logged duration is 0 (#2592). A failed
  8669. # one the printer's errors explain keeps their reason (#3310).
  8670. failure_reason = "noStatusUpdate"
  8671. elif data.get("_kill_switch"):
  8672. # Not the user's cancel: the kill switch stopped a print that did
  8673. # not come from Bambuddy.
  8674. failure_reason = "killSwitch"
  8675. if failure_reason:
  8676. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  8677. elif status == "failed" and hms_errors:
  8678. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  8679. await service.update_archive_status(
  8680. archive_id,
  8681. status=status,
  8682. completed_at=(
  8683. # A reconciled completed print ended at an estimated time,
  8684. # not at the reconnect (#3310).
  8685. data.get("_reconciled_completed_at") or datetime.now(timezone.utc)
  8686. if status in ("completed", "failed", "aborted", "cancelled")
  8687. else None
  8688. ),
  8689. failure_reason=failure_reason,
  8690. )
  8691. logger.info(
  8692. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  8693. )
  8694. await ws_manager.send_archive_updated(
  8695. {
  8696. "id": archive_id,
  8697. "status": status,
  8698. }
  8699. )
  8700. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  8701. # MQTT relay - publish archive updated
  8702. try:
  8703. await mqtt_relay.on_archive_updated(
  8704. archive_id=archive_id,
  8705. print_name=filename or subtask_name,
  8706. status=status,
  8707. )
  8708. except Exception:
  8709. pass # Don't fail if MQTT fails
  8710. except Exception as e:
  8711. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  8712. # Continue with other operations even if archive update fails
  8713. log_timing("Archive status update")
  8714. # Apply finance wallet charge or release reservations once. For all partial
  8715. # terminal states (failed, aborted at the printer display, or cancelled via
  8716. # Bambuddy) use this run's measured spool delta, falling back to the last
  8717. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  8718. # estimate and therefore cannot represent an interrupted run.
  8719. try:
  8720. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  8721. async with async_session() as db:
  8722. from backend.app.models.archive import PrintArchive
  8723. from backend.app.services.finance_billing import apply_print_charge_for_archive
  8724. from backend.app.services.print_log import run_being_ended
  8725. archive = await db.get(PrintArchive, archive_id)
  8726. # The run this end fills in below: charged as its own, not as
  8727. # the archive's latest dispatch (another plate of it, maybe).
  8728. charged_run = await run_being_ended(db, archive_id, printer_id, archive.started_at) if archive else None
  8729. if archive and billing_run_id is None and charged_run is None:
  8730. billing_run_id = getattr(archive, "billing_run_id", None)
  8731. if archive and archive.created_by_id is None and _print_user_info:
  8732. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  8733. await db.flush()
  8734. run_status = data.get("status", "completed")
  8735. last_progress = data.get("last_progress")
  8736. if last_progress is None:
  8737. last_progress = data.get("progress")
  8738. actual_run_grams = _compute_run_filament_grams(
  8739. run_status,
  8740. billing_planned_grams,
  8741. last_progress,
  8742. usage_results,
  8743. )
  8744. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  8745. in_memory_cost_center_id = _print_cost_center_ids.pop((printer_id, archive_id), None)
  8746. charged = await apply_print_charge_for_archive(
  8747. db,
  8748. archive_id,
  8749. charged_user_id=billing_user_id,
  8750. cost_center_id=(
  8751. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  8752. ),
  8753. print_queue_id=queue_item_id,
  8754. print_run_id=billing_run_id,
  8755. base_cost_override=billing_base_cost,
  8756. filament_usage=filament_usage,
  8757. run_entry_id=charged_run.id if charged_run is not None else None,
  8758. run_status=run_status,
  8759. )
  8760. await db.commit()
  8761. if charged:
  8762. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  8763. except Exception as e:
  8764. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  8765. printer_info = printer_manager.get_printer(printer_id)
  8766. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  8767. billing_filename = filename or subtask_name or "Unknown"
  8768. billing_error = str(e)
  8769. try:
  8770. await ws_manager.broadcast(
  8771. {
  8772. "type": "billing_charge_failed",
  8773. "printer_id": printer_id,
  8774. "printer_name": billing_printer_name,
  8775. "filename": billing_filename,
  8776. "archive_id": archive_id,
  8777. }
  8778. )
  8779. except Exception as notification_error:
  8780. logger.error(
  8781. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  8782. archive_id,
  8783. notification_error,
  8784. )
  8785. async def _notify_billing_charge_failed() -> None:
  8786. try:
  8787. async with async_session() as notification_db:
  8788. await notification_service.on_billing_charge_failed(
  8789. printer_id,
  8790. billing_printer_name,
  8791. billing_filename,
  8792. archive_id,
  8793. billing_error,
  8794. notification_db,
  8795. )
  8796. except Exception as provider_error:
  8797. logger.error(
  8798. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  8799. archive_id,
  8800. provider_error,
  8801. exc_info=True,
  8802. )
  8803. spawn_background_task(
  8804. _notify_billing_charge_failed(),
  8805. name=f"billing-charge-failed-{archive_id}",
  8806. )
  8807. log_timing("Finance charge update")
  8808. # Write independent print log entry (separate table, never touches archives)
  8809. # The run's id, for the energy work below: the archive's newest run is
  8810. # the one started last, which with plates of it on two printers need not
  8811. # be the one that just ended.
  8812. completed_run_id: int | None = None
  8813. async def _write_run(db):
  8814. # Retried on a locked SQLite database: a run left open here would be
  8815. # closed again by the next reconnect's reconcile.
  8816. nonlocal completed_run_id
  8817. from backend.app.models.archive import PrintArchive
  8818. from backend.app.services.print_log import discard_open_runs, record_archive_wear, write_log_entry
  8819. archive = await db.get(PrintArchive, archive_id)
  8820. if archive is None:
  8821. # Deleted while it printed: its run has nothing left to end on.
  8822. discarded = await discard_open_runs(db, printer_id)
  8823. await db.commit()
  8824. await _announce_discarded_runs(discarded, printer_id)
  8825. if archive:
  8826. # Back-fill created_by_id on reprint (#730): reprint reuses the
  8827. # source archive row rather than creating a new one, so an
  8828. # archive that was auto-created from a printer-initiated
  8829. # print (created_by_id=NULL) would otherwise stay unattributed
  8830. # forever. When we have a print-session user AND the archive
  8831. # has no attribution yet, credit the current user. Never
  8832. # overwrite an existing attribution — the original uploader
  8833. # keeps ownership.
  8834. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  8835. if archive.created_by_id is None and _print_user_id is not None:
  8836. archive.created_by_id = _print_user_id
  8837. p_info = printer_manager.get_printer(printer_id)
  8838. # Per-run actuals — written to PrintLogEntry so stats reflect
  8839. # what THIS print actually used, not the source archive's
  8840. # first-run values (#1378). Helper handles the partial-print
  8841. # math (failed / cancelled / stopped get scaled to progress
  8842. # or to tracked spool deltas).
  8843. _run_status = data.get("status", "completed")
  8844. # #2614: scope the per-run estimate to the printed plate. For a
  8845. # multi-plate 3MF dispatched one plate at a time, the archive's
  8846. # filament/cost are the whole-file totals; the PrintLogEntry must
  8847. # reflect only this plate. No effect on single-plate archives (the
  8848. # plate estimate equals the whole-file value) or on the tracker
  8849. # path (measured spool deltas win in _compute_run_filament_grams).
  8850. _est_full_path = (
  8851. app_settings.base_dir / archive.file_path if archive.file_path else None
  8852. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8853. # The plate that printed, as billing reads it: a reprint of
  8854. # another plate must not log the archive's first plate.
  8855. _run_plate_id = billing_plate_id if billing_plate_id is not None else notify_plate_id
  8856. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path, _run_plate_id)
  8857. if _run_plate_id is None:
  8858. _run_plate_id = archive.plate_id
  8859. _run_grams = _compute_run_filament_grams(
  8860. _run_status,
  8861. _est_grams,
  8862. data.get("last_progress", data.get("progress")),
  8863. usage_results,
  8864. )
  8865. # Per-run cost — prefer usage_results sum. For partial prints
  8866. # we deliberately skip the topup-to-estimate logic in
  8867. # usage_tracker (which assumes the print completed); the raw
  8868. # tracked-spool sum is closer to what THIS run actually cost.
  8869. _run_cost: float | None = None
  8870. if usage_results:
  8871. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  8872. if _run_cost is None and _run_status != "completed":
  8873. _run_cost = spoolman_run_cost
  8874. if _run_cost is None and _run_status == "completed":
  8875. _run_cost = _est_cost
  8876. from backend.app.models.printer import Printer as _Printer
  8877. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  8878. run_entry = await write_log_entry(
  8879. db,
  8880. archive_id=archive.id,
  8881. # Captured by _update_queue_status above; None for
  8882. # printer-initiated prints with no queue row. Batch
  8883. # cost/energy roll-up joins on it (#342).
  8884. queue_item_id=queue_item_id,
  8885. status=_run_status,
  8886. print_name=archive.print_name,
  8887. # The plate this run printed, as the estimate above takes
  8888. # it; the archive's own is the latest run's.
  8889. plate_id=_run_plate_id,
  8890. printer_name=p_info.name if p_info else None,
  8891. printer_id=printer_id,
  8892. started_at=archive.started_at,
  8893. completed_at=archive.completed_at,
  8894. filament_type=archive.filament_type,
  8895. filament_color=archive.filament_color,
  8896. filament_used_grams=_run_grams,
  8897. cost=_run_cost,
  8898. wear_cost_per_hour=_wear_rate,
  8899. failure_reason=archive.failure_reason,
  8900. thumbnail_path=archive.thumbnail_path,
  8901. created_by_id=archive.created_by_id,
  8902. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  8903. # Reconciled completions have an unknown real end time —
  8904. # log 0 duration instead of the whole disconnect gap (#2592),
  8905. # unless it was estimated (#3310).
  8906. reconciled=bool(data.get("_reconciled")) and not data.get("_reconciled_completed_at"),
  8907. # Its time is the estimate or nothing, never measured (#3310).
  8908. duration_unmeasured=bool(data.get("_reconciled")),
  8909. # The real end of a print stopped while its printer was offline.
  8910. replaces_offline_stop=True,
  8911. )
  8912. await record_archive_wear(db, archive, run_entry)
  8913. await db.commit()
  8914. completed_run_id = run_entry.id
  8915. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  8916. try:
  8917. from backend.app.core.database import run_with_retry
  8918. await run_with_retry(_write_run, label="print log entry")
  8919. except Exception as e:
  8920. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  8921. await _publish_run_completed(completed_run_id, printer_id)
  8922. log_timing("Print log entry")
  8923. # Run slow operations as background tasks to avoid blocking the event loop
  8924. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  8925. async def _background_energy_calculation():
  8926. """Calculate and save energy usage in background.
  8927. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  8928. backend restart no longer loses per-print energy data).
  8929. """
  8930. try:
  8931. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  8932. async with async_session() as db:
  8933. from backend.app.models.archive import PrintArchive
  8934. from backend.app.models.print_log import PrintLogEntry
  8935. from backend.app.services.print_log import energy_start_of
  8936. archive = await db.get(PrintArchive, archive_id)
  8937. if archive is None:
  8938. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  8939. return
  8940. # The ended run's own start reading: the archive's is its
  8941. # latest start's, maybe another plate's on another printer.
  8942. run_row = await db.get(PrintLogEntry, completed_run_id) if completed_run_id is not None else None
  8943. start = energy_start_of(run_row, archive)
  8944. if start is None:
  8945. logger.info("[ENERGY-BG] No start kWh recorded for archive %s's run", archive_id)
  8946. return
  8947. starting_kwh = start.kwh
  8948. candidates = await energy_plug_candidates(db, printer_id)
  8949. if not candidates:
  8950. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  8951. return
  8952. # Same ordering as the start reading, so the delta below is
  8953. # against the counter that produced `starting_kwh` (#2859).
  8954. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  8955. if selected is None:
  8956. logger.warning(
  8957. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  8958. printer_id,
  8959. ", ".join(plug.name for plug in candidates),
  8960. )
  8961. return
  8962. plug, energy = selected
  8963. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  8964. energy_used = round(energy["total"] - starting_kwh, 4)
  8965. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  8966. if energy_used < 0:
  8967. logger.warning(
  8968. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  8969. archive_id,
  8970. starting_kwh,
  8971. energy["total"],
  8972. )
  8973. return
  8974. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  8975. # Each hour of the print at the price of that hour (#1251). If
  8976. # that fails, the last price known, as before, rather than no
  8977. # energy at all. Read first: the session may be unusable after.
  8978. last_price = await stored_price(db)
  8979. try:
  8980. energy_cost_value = round(
  8981. await print_energy_cost(
  8982. db,
  8983. plug_id=start.plug_id,
  8984. start_at=start.at,
  8985. start_kwh=starting_kwh,
  8986. start_price=start.price,
  8987. end_kwh=energy["total"],
  8988. end_plug_id=plug.id,
  8989. price_now=await current_price(db),
  8990. ),
  8991. 3,
  8992. )
  8993. except Exception as e:
  8994. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  8995. energy_cost_value = round(energy_used * last_price, 3)
  8996. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  8997. # reprint doesn't visually clobber the source archive's energy data
  8998. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  8999. from sqlalchemy import func
  9000. existing_runs = await db.scalar(
  9001. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  9002. )
  9003. if (existing_runs or 0) <= 1:
  9004. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  9005. # we just wrote for THIS print. Either way it's the first run.
  9006. archive.energy_kwh = energy_used
  9007. archive.energy_cost = energy_cost_value
  9008. # The ended run's energy (write_log_entry above ran before this
  9009. # background task, so its energy fields are still NULL). With
  9010. # no run written, none: the archive's newest is another print's.
  9011. if run_row is not None:
  9012. run_row.energy_kwh = energy_used
  9013. run_row.energy_cost = energy_cost_value
  9014. await db.commit()
  9015. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  9016. except Exception as e:
  9017. logger.warning("[ENERGY-BG] Failed: %s", e)
  9018. async def _background_finish_photo() -> str | None:
  9019. """Capture finish photo in background. Returns photo filename if captured."""
  9020. # #2547: set once this function has raised the plate itself (the
  9021. # timelapse path, where the moment producer returned without doing it).
  9022. # Declared out here so the `finally` can lower it again no matter where
  9023. # the capture below fails.
  9024. plate_restored_z: float | None = None
  9025. try:
  9026. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  9027. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  9028. # Read phase: settings + printer + archive in a short session, released
  9029. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  9030. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  9031. # tens of seconds; holding this session across it pinned one pooled
  9032. # connection idle-in-transaction per finishing print (issue #2572).
  9033. async with async_session() as db:
  9034. from backend.app.api.routes.settings import get_setting
  9035. from backend.app.models.archive import PrintArchive
  9036. from backend.app.models.printer import Printer
  9037. capture_enabled = await get_setting(db, "capture_finish_photo")
  9038. if capture_enabled is not None and capture_enabled.lower() != "true":
  9039. return None
  9040. if not archive_id:
  9041. return None
  9042. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  9043. archive = (
  9044. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  9045. ).scalar_one_or_none()
  9046. if not printer or not archive:
  9047. return None
  9048. import uuid
  9049. from datetime import datetime
  9050. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  9051. if not archive.file_path:
  9052. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  9053. archive_dir = resolve_archive_dir(archive)
  9054. photo_filename = None
  9055. # Prefer the timelapse last-frame source when a timelapse was
  9056. # recording — it captures the moment after the toolhead parks
  9057. # but before the bed drops, which the live-camera grab below
  9058. # would miss (#1397). Skipped for external cameras (those have
  9059. # their own framing and don't see a Bambu timelapse). Only
  9060. # runs when the USER explicitly enabled timelapse for this
  9061. # print — #1721 removed Bambuddy's force-on at dispatch
  9062. # because it caused per-layer nozzle parking on Smooth-mode
  9063. # slicer profiles.
  9064. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  9065. printer.external_camera_enabled and printer.external_camera_url
  9066. )
  9067. timelapse_still_pending = False
  9068. if prefer_timelapse_source:
  9069. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  9070. archive_id=archive_id,
  9071. archive_dir=archive_dir,
  9072. rotation=getattr(printer, "camera_rotation", 0),
  9073. run_id=completed_run_id,
  9074. )
  9075. # #1721: replacement framing path — on_finish_photo_moment
  9076. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  9077. # parked, bed not yet dropped) and cached the JPEG bytes in
  9078. # _stage22_finish_frames. Consume them now so the saved photo
  9079. # has the better framing instead of the post-bed-drop angle
  9080. # the live-camera fallback below would give.
  9081. if not photo_filename:
  9082. # #1790: on the FINISH-state fallback path the producer
  9083. # task is dispatched back-to-back with this consumer, so
  9084. # a bare pop would race past with an empty result and
  9085. # the RTSP fallback below would collide with the
  9086. # producer's still-in-flight grab (single-client RTSP
  9087. # on Bambu printers). Wait for the producer to finish
  9088. # or give up before touching the cache.
  9089. #
  9090. # #2547: 20s was enough when the producer only ever grabbed a
  9091. # frame. It now also raises the plate first, which costs the
  9092. # settle window before the grab even starts — so the budget has
  9093. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  9094. # under the notification's own photo wait below.
  9095. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  9096. if in_flight is not None:
  9097. try:
  9098. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  9099. except TimeoutError:
  9100. logger.warning(
  9101. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  9102. printer_id,
  9103. )
  9104. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  9105. if cached_frame:
  9106. # Already rotated by the producer (#2708) — rotating again
  9107. # here would undo the fix on the banked-frame path, whose
  9108. # bytes reach the cache having been rotated once already.
  9109. photos_dir = archive_dir / "photos"
  9110. photos_dir.mkdir(parents=True, exist_ok=True)
  9111. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9112. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9113. photo_path = photos_dir / photo_filename
  9114. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  9115. logger.info(
  9116. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  9117. photo_filename,
  9118. len(cached_frame),
  9119. )
  9120. # #2547: the timelapse path reaches the live grab below whenever the
  9121. # video hasn't landed in time — the documented usual outcome on
  9122. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  9123. # returned early for those prints without raising the plate, so
  9124. # without this the photo that actually ships in the notification is
  9125. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  9126. # asked us to fix. The archive still gets the better video frame
  9127. # later; this is about the image the user is sent.
  9128. #
  9129. # Gated on `timelapse_was_active` precisely because that is the
  9130. # condition under which the producer skipped. On every other path it
  9131. # has already raised and lowered the plate, and repeating that here
  9132. # would be a second pointless round trip.
  9133. if (
  9134. not photo_filename
  9135. and data.get("timelapse_was_active")
  9136. and not print_dispatch_context.end_gcode_injected(printer_id)
  9137. ):
  9138. try:
  9139. async with async_session() as db:
  9140. from backend.app.api.routes.settings import get_setting
  9141. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  9142. if restore_setting is None or restore_setting.lower() == "true":
  9143. max_z = await _max_z_for_current_print(
  9144. printer_id, data, logger, bound_archive_id, notify_plate_id
  9145. )
  9146. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  9147. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  9148. plate_restored_z = max_z
  9149. except Exception as e:
  9150. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  9151. # Fallback chain: external camera → buffered live frame →
  9152. # fresh RTSP capture. Only runs if the timelapse path above
  9153. # didn't already produce a photo.
  9154. # Chamber light for the live capture below (#1655).
  9155. async with camera_light(printer if not photo_filename else None):
  9156. if not photo_filename:
  9157. if printer.external_camera_enabled and printer.external_camera_url:
  9158. logger.info("[PHOTO-BG] Using external camera")
  9159. from backend.app.api.routes.camera import live_frame_for_capture
  9160. from backend.app.services.external_camera import capture_frame
  9161. # #2707: the second half of the finish-photo failure — the
  9162. # pre-capture and this fallback both collided with the live
  9163. # view. None here continues down the fallback chain.
  9164. defer, buffered = live_frame_for_capture(printer_id)
  9165. if defer:
  9166. frame_data = buffered
  9167. else:
  9168. frame_data = await capture_frame(
  9169. printer.external_camera_url,
  9170. printer.external_camera_type or "mjpeg",
  9171. snapshot_url=printer.external_camera_snapshot_url,
  9172. )
  9173. if frame_data:
  9174. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  9175. photos_dir = archive_dir / "photos"
  9176. photos_dir.mkdir(parents=True, exist_ok=True)
  9177. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9178. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9179. photo_path = photos_dir / photo_filename
  9180. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  9181. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  9182. else:
  9183. # Check if camera stream is active - use buffered frame to avoid freeze
  9184. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  9185. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  9186. active_chamber_for_printer = [
  9187. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  9188. ]
  9189. buffered_frame = get_buffered_frame(printer_id)
  9190. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  9191. # Use frame from active stream
  9192. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  9193. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  9194. photos_dir = archive_dir / "photos"
  9195. photos_dir.mkdir(parents=True, exist_ok=True)
  9196. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9197. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9198. photo_path = photos_dir / photo_filename
  9199. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  9200. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  9201. else:
  9202. # No active stream - capture new frame
  9203. from backend.app.services.camera import capture_finish_photo
  9204. photo_filename = await capture_finish_photo(
  9205. printer_id=printer_id,
  9206. ip_address=printer.ip_address,
  9207. access_code=printer.access_code,
  9208. model=printer.model,
  9209. archive_dir=archive_dir,
  9210. rotation=getattr(printer, "camera_rotation", 0),
  9211. )
  9212. # Write phase: attach the photo in a fresh short-lived session.
  9213. if photo_filename:
  9214. async with async_session() as db:
  9215. from backend.app.models.archive import PrintArchive
  9216. from backend.app.services.print_log import add_run_photo, run_of
  9217. arch = await db.get(PrintArchive, archive_id)
  9218. # The ended print's own list takes it too: the archive's
  9219. # holds every print's.
  9220. run = await run_of(db, archive_id, completed_run_id) if completed_run_id is not None else None
  9221. if arch is not None:
  9222. photos = arch.photos or []
  9223. photos.append(photo_filename)
  9224. arch.photos = photos
  9225. add_run_photo(run, photo_filename)
  9226. await db.commit()
  9227. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  9228. # The short wait above is bounded so a slow printer can't hold up
  9229. # the print-complete notification, which is what the caller is
  9230. # blocking on. When it ran out with the video still on its way,
  9231. # keep waiting off to the side and add the better frame to the
  9232. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  9233. # users, whose videos routinely take minutes to transfer, never get
  9234. # the pre-bed-drop framing this path exists to provide.
  9235. #
  9236. # Spawned here rather than at the point the wait gave up: both this
  9237. # function and the upgrade do a read-modify-write on `photos`, and
  9238. # the live-camera fallback above can take tens of seconds. Starting
  9239. # the upgrade before that write means the two can interleave and one
  9240. # silently drops the other's entry, leaving a JPEG on disk that the
  9241. # gallery never lists.
  9242. if timelapse_still_pending:
  9243. from backend.app.services import archive_work
  9244. spawn_background_task(
  9245. archive_work.held_while(
  9246. archive_id,
  9247. _upgrade_finish_photo_from_timelapse(
  9248. archive_id,
  9249. archive_dir,
  9250. rotation=getattr(printer, "camera_rotation", 0),
  9251. run_id=completed_run_id,
  9252. ),
  9253. ),
  9254. name=f"finish-photo-upgrade-{archive_id}",
  9255. )
  9256. return photo_filename
  9257. except Exception as e:
  9258. logger.warning("[PHOTO-BG] Failed: %s", e)
  9259. return None
  9260. finally:
  9261. # #2547: we raised the plate, so we owe the move back down — even if
  9262. # the capture in between threw. Otherwise the user finds the print
  9263. # pinned under the nozzle.
  9264. if plate_restored_z is not None:
  9265. try:
  9266. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  9267. except Exception as e:
  9268. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  9269. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  9270. # Photo capture task - result will be used by notifications
  9271. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  9272. log_timing("Background tasks scheduled (energy, photo)")
  9273. # Also run smart plug, notifications, and maintenance as background tasks
  9274. print_status = data.get("status", "completed")
  9275. async def _background_smart_plug():
  9276. """Handle smart plug automation in background."""
  9277. try:
  9278. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  9279. async with async_session() as db:
  9280. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  9281. logger.info("[AUTO-OFF-BG] Completed")
  9282. except Exception as e:
  9283. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  9284. async def _background_notifications(finish_photo_filename: str | None = None):
  9285. """Send print complete notifications in background."""
  9286. try:
  9287. logger.info(
  9288. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  9289. )
  9290. async with async_session() as db:
  9291. from backend.app.models.archive import PrintArchive
  9292. from backend.app.models.printer import Printer
  9293. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9294. printer = result.scalar_one_or_none()
  9295. printer_name = printer.name if printer else f"Printer {printer_id}"
  9296. archive_data = None
  9297. if archive_id:
  9298. from backend.app.models.print_log import PrintLogEntry
  9299. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  9300. archive = archive_result.scalar_one_or_none()
  9301. # The run that ended: the archive shows its latest, which
  9302. # with another plate of it printing elsewhere is not this.
  9303. run = await db.get(PrintLogEntry, completed_run_id) if completed_run_id is not None else None
  9304. run_started = run.started_at if run is not None else archive.started_at if archive else None
  9305. run_completed = run.completed_at if run is not None else archive.completed_at if archive else None
  9306. if archive:
  9307. # Actual elapsed time from started_at/completed_at when both are
  9308. # populated (every terminal status sets completed_at after #1198).
  9309. # Falls back to None so the notification path can decide whether to
  9310. # render the slicer estimate as a last resort.
  9311. actual_time_seconds = None
  9312. # Unknown for a completion reconciled at reconnect: the
  9313. # print ended while the printer was offline and
  9314. # completed_at is the reconnect, so the gap would read
  9315. # as the duration -- 14 h for a night offline (DB-C9).
  9316. # An estimated end (#3310) gives the estimate.
  9317. if (
  9318. run_started
  9319. and run_completed
  9320. and (not data.get("_reconciled") or data.get("_reconciled_completed_at"))
  9321. ):
  9322. elapsed = (run_completed - run_started).total_seconds()
  9323. if elapsed > 0:
  9324. actual_time_seconds = int(elapsed)
  9325. archive_data = {
  9326. "print_time_seconds": archive.print_time_seconds,
  9327. "actual_time_seconds": actual_time_seconds,
  9328. "actual_filament_grams": archive.filament_used_grams,
  9329. "failure_reason": run.failure_reason if run is not None else archive.failure_reason,
  9330. "created_by_id": archive.created_by_id,
  9331. }
  9332. # Scale filament usage for partial prints
  9333. if print_status != "completed" and archive.filament_used_grams:
  9334. progress = data.get("progress") or 0
  9335. scale = _partial_progress_scale(progress)
  9336. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  9337. archive_data["progress"] = progress
  9338. # Pass per-slot data from archive.extra_data
  9339. if archive.extra_data and archive.extra_data.get("filament_slots"):
  9340. slots = archive.extra_data["filament_slots"]
  9341. if print_status != "completed":
  9342. scale = _partial_progress_scale(data.get("progress"))
  9343. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  9344. archive_data["filament_slots"] = slots
  9345. # Scope project-summed totals down to the plate that was
  9346. # actually printed — see _scope_notification_archive_data_to_plate
  9347. # for the why (#1785).
  9348. archive_data = _scope_notification_archive_data_to_plate(
  9349. archive_data,
  9350. archive.file_path,
  9351. notify_plate_id,
  9352. print_status,
  9353. data.get("progress"),
  9354. app_settings.base_dir,
  9355. )
  9356. # Enrich filament_grams from usage_results when archive has no 3MF data
  9357. if not archive_data.get("actual_filament_grams") and usage_results:
  9358. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  9359. if total_from_usage > 0:
  9360. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  9361. # Pass usage tracker results for AMS slot info in notifications
  9362. if usage_results:
  9363. archive_data["usage_results"] = usage_results
  9364. # Which archive and print it was (archive redesign).
  9365. archive_data["archive_id"] = archive_id
  9366. archive_data["run_id"] = completed_run_id
  9367. # Add finish photo URL and image bytes if available
  9368. if finish_photo_filename:
  9369. photo_url, photo_bytes = await _finish_photo_for_notification(
  9370. db, archive, archive_id, finish_photo_filename
  9371. )
  9372. if photo_url:
  9373. archive_data["finish_photo_url"] = photo_url
  9374. if photo_bytes:
  9375. archive_data["image_data"] = photo_bytes
  9376. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  9377. await notification_service.on_print_complete(
  9378. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  9379. )
  9380. else:
  9381. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  9382. # Post-print outcome confirmation (#1898). Runs in this
  9383. # background task so the finish photo fetched above rides
  9384. # along with the prompt.
  9385. if print_status == "completed" and archive_id:
  9386. await _dispatch_outcome_confirmation_safely(
  9387. db, printer_id, printer_name, data, archive_id, archive_data, run_id=completed_run_id
  9388. )
  9389. # Send user-specific email notification
  9390. if archive_data:
  9391. created_by_id = archive_data.get("created_by_id")
  9392. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  9393. await _dispatch_user_print_email(
  9394. print_status,
  9395. created_by_id,
  9396. printer_name,
  9397. raw_filename,
  9398. db,
  9399. image_data=archive_data.get("image_data"),
  9400. finish_photo_url=archive_data.get("finish_photo_url"),
  9401. )
  9402. logger.info("[NOTIFY-BG] Completed")
  9403. except Exception as e:
  9404. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  9405. async def _background_maintenance_check():
  9406. """Check for maintenance due in background."""
  9407. if print_status != "completed":
  9408. return
  9409. try:
  9410. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  9411. async with async_session() as db:
  9412. from backend.app.models.printer import Printer
  9413. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9414. printer = result.scalar_one_or_none()
  9415. printer_name = printer.name if printer else f"Printer {printer_id}"
  9416. await ensure_default_types(db)
  9417. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  9418. attention = [
  9419. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  9420. ]
  9421. items_needing_attention = [
  9422. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  9423. for item in attention
  9424. ]
  9425. if items_needing_attention:
  9426. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  9427. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  9428. # MQTT relay - publish maintenance alerts
  9429. for item in attention:
  9430. current_value, threshold, unit = maintenance_alert_values(item)
  9431. try:
  9432. await mqtt_relay.on_maintenance_alert(
  9433. printer_id=printer_id,
  9434. printer_name=printer_name,
  9435. maintenance_type=item.maintenance_type_name,
  9436. current_value=current_value,
  9437. threshold=threshold,
  9438. unit=unit,
  9439. )
  9440. except Exception:
  9441. pass # Don't fail if MQTT fails
  9442. else:
  9443. logger.info("[MAINT-BG] Completed (no items need attention)")
  9444. except Exception as e:
  9445. logger.warning("[MAINT-BG] Failed: %s", e)
  9446. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  9447. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  9448. # Notification task waits for photo capture to complete first (with timeout).
  9449. # When a timelapse was recording, photo sourcing polls the per-print
  9450. # timelapse for up to 60s (#1397) — extend the budget so the notification
  9451. # carries the correct bed-up photo instead of falling through to the
  9452. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  9453. #
  9454. # #2547: both budgets now have to cover a plate restore as well.
  9455. #
  9456. # Without timelapse, the wait is on the moment producer, which raises the
  9457. # plate before its grab — so this has to outlast that producer's own budget.
  9458. #
  9459. # With timelapse, the capture polls up to
  9460. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  9461. # falls back to a live grab, which is the case that raises the plate. At the
  9462. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  9463. # restore would have moved the plate for a photo nobody waited for.
  9464. photo_wait_timeout = (
  9465. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  9466. if data.get("timelapse_was_active")
  9467. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  9468. )
  9469. async def _photo_then_notify():
  9470. """Wait for photo capture, then send notification with photo URL."""
  9471. finish_photo = None
  9472. try:
  9473. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  9474. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  9475. except TimeoutError:
  9476. logger.warning(
  9477. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  9478. photo_wait_timeout,
  9479. )
  9480. except Exception as e:
  9481. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  9482. try:
  9483. await _background_notifications(finish_photo)
  9484. except Exception as e:
  9485. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  9486. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  9487. # Stitch external camera layer timelapse if session was active
  9488. print_status = data.get("status", "completed")
  9489. async def _background_layer_timelapse():
  9490. """Stitch layer timelapse and attach to archive."""
  9491. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  9492. try:
  9493. if print_status == "completed":
  9494. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  9495. # The run the frames belong to, read before the stitch: it can
  9496. # take long enough for the archive to start printing again.
  9497. run_started_at = None
  9498. if archive_id:
  9499. async with async_session() as db:
  9500. run_archive = await ArchiveService(db).get_archive(archive_id)
  9501. run_started_at = run_archive.started_at if run_archive else None
  9502. timelapse_path = await tl_complete(printer_id)
  9503. if timelapse_path and archive_id:
  9504. await _attach_layer_timelapse(
  9505. archive_id, timelapse_path, notify_plate_id, run_started_at, run_id=completed_run_id
  9506. )
  9507. elif timelapse_path:
  9508. # Timelapse created but no archive - just clean up
  9509. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  9510. else:
  9511. # Print failed or cancelled - cancel timelapse session
  9512. cancel_session(printer_id)
  9513. logger.info(
  9514. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  9515. )
  9516. except Exception as e:
  9517. logger.warning("[LAYER-TL] Failed: %s", e)
  9518. # A completed print's session left _active_sessions when its stitch
  9519. # began: the one there now belongs to the next print, which may have
  9520. # started during the stitch, and must not lose its frames.
  9521. if print_status != "completed":
  9522. try:
  9523. cancel_session(printer_id)
  9524. except Exception:
  9525. pass # Best-effort timelapse session cancellation on error
  9526. from backend.app.services import archive_work
  9527. # Held through the stitch, which can take longer than a merge waits after
  9528. # a print (archive redesign P2).
  9529. layer_timelapse = _background_layer_timelapse()
  9530. if archive_id:
  9531. layer_timelapse = archive_work.held_while(archive_id, layer_timelapse)
  9532. spawn_background_task(layer_timelapse, name="background-layer-timelapse")
  9533. log_timing("All background tasks scheduled")
  9534. # Auto-scan for timelapse if recording was active during the print
  9535. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  9536. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  9537. # Schedule timelapse scan as background task with retries
  9538. # The printer needs time to encode the video after print completion
  9539. _schedule_timelapse_scan(archive_id, printer_id, plate_id=notify_plate_id, run_id=completed_run_id)
  9540. log_timing("Timelapse scan scheduled")
  9541. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  9542. # AMS sensor history recording
  9543. _ams_history_task: asyncio.Task | None = None
  9544. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  9545. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  9546. def _retention_days(stored: str | None, default: int) -> int:
  9547. """A history retention setting as days to keep: at least 1, the default
  9548. when unset or unreadable. A stored 0 or less (the API took one before it
  9549. had a minimum) would put the cutoff at now and delete all history."""
  9550. try:
  9551. return max(1, int(stored)) if stored is not None else default
  9552. except (TypeError, ValueError):
  9553. return default
  9554. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  9555. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  9556. _ams_alarm_cooldown: dict[str, datetime] = {}
  9557. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  9558. # (printer_id, ams_id) already reported as sending the drop index and no
  9559. # percentage. Logged once each so a supported printer that turns out to do this
  9560. # shows up in a support bundle rather than as a user wondering where the
  9561. # humidity reading went -- see the note at the read site below (#3140).
  9562. _ams_index_only_logged: set[tuple[int, int]] = set()
  9563. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  9564. """Temperature at which the AMS alarm fires, falling back to the display band.
  9565. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  9566. when a notification was sent as well, which is why a room above it made the
  9567. alarm fire once an hour for as long as the weather lasted -- and the only way
  9568. to stop that was to raise the display band and lose the colour that says the
  9569. unit is warm (#2905).
  9570. Unset resolves to the fair threshold, so an install that never sets one is
  9571. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  9572. so that arrives here as a string and is handled by the same branch as any
  9573. other unparseable value -- there is no separate sentinel to keep in sync.
  9574. A non-positive value is refused rather than honoured: zero would alarm
  9575. permanently, and it is far more likely to be a cleared field than a
  9576. deliberate choice.
  9577. """
  9578. if raw_alarm_value is None:
  9579. return fair_threshold
  9580. try:
  9581. value = float(raw_alarm_value)
  9582. except (TypeError, ValueError):
  9583. return fair_threshold
  9584. if not math.isfinite(value) or value <= 0:
  9585. return fair_threshold
  9586. return value
  9587. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  9588. # through a cycle and the cool-down after it (#1802). Stored in the settings
  9589. # table rather than alongside _ams_alarm_cooldown above, because a restart
  9590. # partway through a cool-down would otherwise resume alarming about heat the
  9591. # user asked for — the same internal-timestamp-row pattern as
  9592. # support.py's debug_logging_enabled_at.
  9593. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  9594. # Upper bound on that suppression. The latch normally clears as soon as the unit
  9595. # reads at or below the threshold; see utils.ams_drying for why this cap only
  9596. # matters when it never does.
  9597. AMS_DRYING_GRACE_MINUTES = 120
  9598. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  9599. """Read the persisted per-AMS drying latch, dropping entries out of window.
  9600. Anything older than the grace cap would expire on its next visit anyway, so
  9601. discarding it here costs nothing and stops rows for deleted printers from
  9602. accumulating.
  9603. Stamps ahead of now get two defences, because a box whose clock jumps
  9604. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  9605. ones are discarded outright, and the rest are clamped to now. Without the
  9606. clamp the cap would measure from a moment that has not happened yet and hold
  9607. the alarm quiet for the skew on top of the cap. One unnecessary notification
  9608. after a clock jump is a far better failure than an alarm silently disabled
  9609. for hours.
  9610. """
  9611. from backend.app.models.settings import Settings
  9612. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9613. setting = result.scalar_one_or_none()
  9614. if not setting or not setting.value:
  9615. return {}
  9616. try:
  9617. raw = json.loads(setting.value)
  9618. except (ValueError, TypeError):
  9619. return {} # Corrupted row → no latch, alarms behave as they did before
  9620. if not isinstance(raw, dict):
  9621. return {}
  9622. now = datetime.now(timezone.utc)
  9623. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  9624. latch: dict[str, datetime] = {}
  9625. for key, value in raw.items():
  9626. try:
  9627. stamp = datetime.fromisoformat(str(value))
  9628. except (ValueError, TypeError):
  9629. continue
  9630. if stamp.tzinfo is None:
  9631. stamp = stamp.replace(tzinfo=timezone.utc)
  9632. if not (now - window <= stamp <= now + window):
  9633. continue
  9634. # Nothing may sit in the future: suppression is measured as now minus
  9635. # the stamp, so a stamp ahead of now would extend it by the skew on top
  9636. # of the cap. Clamping the survivors keeps the cap an actual cap.
  9637. latch[str(key)] = min(stamp, now)
  9638. return latch
  9639. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  9640. """Persist the latch, writing only when it actually changed.
  9641. Adds the session change but does not commit — the caller's own commit
  9642. carries it, so the latch lands in the same transaction as the sensor rows
  9643. that produced it.
  9644. """
  9645. from backend.app.models.settings import Settings
  9646. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  9647. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9648. setting = result.scalar_one_or_none()
  9649. if setting is None:
  9650. # Don't create the row on installs that never dry anything.
  9651. if payload != "{}":
  9652. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  9653. elif setting.value != payload:
  9654. setting.value = payload
  9655. def _ams_has_filament(ams_data: dict) -> bool:
  9656. """True if this AMS unit has at least one tray slot holding filament.
  9657. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  9658. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  9659. still report sensor readings, but those readings are ambient and not
  9660. actionable: no filament to dry, no humidity to push down. #1619 — gate
  9661. humidity/temperature alarms on this check so empty units don't generate
  9662. hourly noise. Sensor history still records regardless so the UI charts
  9663. stay continuous.
  9664. Fallback path inspects the `tray` array's `tray_type` fields for setups
  9665. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  9666. """
  9667. bits = ams_data.get("tray_exist_bits")
  9668. if isinstance(bits, str) and bits.strip():
  9669. try:
  9670. return int(bits, 16) > 0
  9671. except ValueError:
  9672. pass
  9673. trays = ams_data.get("tray")
  9674. if isinstance(trays, list):
  9675. return any(
  9676. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  9677. )
  9678. return False
  9679. async def record_ams_history():
  9680. """Background task to record AMS humidity and temperature data."""
  9681. logger = logging.getLogger(__name__)
  9682. # Wait a short time for MQTT connections to establish on startup
  9683. await asyncio.sleep(10)
  9684. while True:
  9685. try:
  9686. from backend.app.models.ams_history import AMSSensorHistory
  9687. from backend.app.models.printer import Printer
  9688. from backend.app.models.settings import Settings
  9689. async with async_session() as db:
  9690. # Get all active printers
  9691. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9692. printers = result.scalars().all()
  9693. # Get alarm thresholds from settings
  9694. humidity_threshold = 60.0 # Default: fair threshold
  9695. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  9696. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  9697. setting = result.scalar_one_or_none()
  9698. if setting:
  9699. try:
  9700. humidity_threshold = float(setting.value)
  9701. except (ValueError, TypeError):
  9702. pass # Keep default threshold if stored value is invalid
  9703. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  9704. setting = result.scalar_one_or_none()
  9705. if setting:
  9706. try:
  9707. temp_fair_threshold = float(setting.value)
  9708. except (ValueError, TypeError):
  9709. pass # Keep default threshold if stored value is invalid
  9710. # The alarm gets its own threshold, seeded from the resolved fair
  9711. # value so an install that has never set one behaves exactly as
  9712. # it did before (#2905). ams_temp_fair decides when the card turns
  9713. # amber; 35 C is a reasonable place to change a colour and not a
  9714. # reasonable place to page someone. A room above it makes the
  9715. # alarm fire once an hour for as long as the weather lasts, and
  9716. # the only way to stop it was to raise the display band and lose
  9717. # the colour that says the unit is warm.
  9718. #
  9719. # An unset value is stored as the literal "None", which the except
  9720. # below swallows the same way it swallows garbage -- so the
  9721. # fallback costs nothing and needs no sentinel of its own.
  9722. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  9723. setting = result.scalar_one_or_none()
  9724. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  9725. temp_fair_threshold, setting.value if setting else None
  9726. )
  9727. # Per-filament humidity threshold overrides (#1605) — resolved
  9728. # per-AMS below from the loaded tray types. Reuses the same
  9729. # resolver as the auto-drying scheduler so behavior stays in
  9730. # lockstep across both consumers.
  9731. from backend.app.services.print_scheduler import PrintScheduler
  9732. per_type_humidity_thresholds: dict[str, int] = {}
  9733. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  9734. setting = result.scalar_one_or_none()
  9735. if setting and setting.value:
  9736. try:
  9737. raw = json.loads(setting.value)
  9738. if isinstance(raw, dict):
  9739. for k, v in raw.items():
  9740. try:
  9741. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  9742. v
  9743. )
  9744. except (TypeError, ValueError):
  9745. continue
  9746. except (ValueError, TypeError):
  9747. pass # Invalid JSON → no overrides, fall through to global threshold
  9748. # Per-AMS drying latch (#1802), loaded once per pass and written
  9749. # back below only if a unit changed it.
  9750. drying_latch = await _load_ams_drying_latch(db)
  9751. drying_latch_before = dict(drying_latch)
  9752. recorded_count = 0
  9753. for printer in printers:
  9754. # Get current state from printer manager
  9755. state = printer_manager.get_status(printer.id)
  9756. if not state or not state.connected or not state.raw_data:
  9757. continue # Skip disconnected printers - don't use stale data
  9758. raw_data = state.raw_data
  9759. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  9760. continue
  9761. # Record data for each AMS unit
  9762. for ams_data in raw_data["ams"]:
  9763. ams_id = int(ams_data.get("id", 0))
  9764. # Percentage only. The 1-5 index is inverted, so
  9765. # charting it as a percentage drew the wettest units as
  9766. # the driest (#3140); a unit that reports no percentage
  9767. # leaves a gap in the chart instead. See
  9768. # utils/ams_humidity.
  9769. humidity = ams_humidity_percent(ams_data)
  9770. # No supported printer is known to send the index
  9771. # alone -- the report came from unsupported firmware,
  9772. # and no install has been seen using the old fallback.
  9773. # "Known" is doing work there, so say so once per unit:
  9774. # the alternative is a silent blank card.
  9775. if humidity is None and ams_data.get("humidity") is not None:
  9776. unit_key = (printer.id, ams_id)
  9777. if unit_key not in _ams_index_only_logged:
  9778. _ams_index_only_logged.add(unit_key)
  9779. logger.info(
  9780. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  9781. "percentage. The index is inverted and is not shown as a percentage "
  9782. "(#3140), so this unit has no humidity reading, chart or alarm. "
  9783. "Please report this with the printer and AMS firmware versions.",
  9784. printer.name,
  9785. ams_id,
  9786. )
  9787. # Get temperature
  9788. temperature = None
  9789. temp_str = ams_data.get("temp")
  9790. if temp_str is not None:
  9791. try:
  9792. temperature = float(temp_str)
  9793. except (ValueError, TypeError):
  9794. pass # Skip unparseable temperature value
  9795. # Skip if no data
  9796. if humidity is None and temperature is None:
  9797. continue
  9798. # Record the data point
  9799. history = AMSSensorHistory(
  9800. printer_id=printer.id,
  9801. ams_id=ams_id,
  9802. humidity=humidity,
  9803. # Both columns hold the same reading now that the
  9804. # index can no longer reach ``humidity``. Writing it
  9805. # through the same value also stops a genuine 0%
  9806. # from being stored as NULL, which the old truthiness
  9807. # test did.
  9808. humidity_raw=humidity,
  9809. temperature=temperature,
  9810. )
  9811. db.add(history)
  9812. recorded_count += 1
  9813. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  9814. is_ams_ht = ams_id >= 128
  9815. if is_ams_ht:
  9816. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  9817. else:
  9818. ams_label = f"AMS-{chr(65 + ams_id)}"
  9819. # Skip alarm dispatch for empty AMS units — humidity /
  9820. # temperature readings are ambient with no filament to
  9821. # protect, and the hourly notification just becomes
  9822. # noise. Sensor history was already recorded above so
  9823. # the UI charts stay continuous (#1619). Per-AMS check
  9824. # so a multi-AMS setup with one loaded + one empty
  9825. # still alarms on the loaded unit.
  9826. if not _ams_has_filament(ams_data):
  9827. continue
  9828. # Resolve per-filament humidity threshold for this AMS
  9829. # unit (#1605). Falls back to the global ams_humidity_fair
  9830. # when no per-type overrides are configured.
  9831. trays = ams_data.get("tray", []) or []
  9832. effective_humidity_threshold = float(
  9833. PrintScheduler.resolve_humidity_threshold(
  9834. trays, per_type_humidity_thresholds, int(humidity_threshold)
  9835. )
  9836. )
  9837. # Check humidity alarm (only if above threshold)
  9838. if humidity is not None and humidity > effective_humidity_threshold:
  9839. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  9840. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9841. now = datetime.now(timezone.utc)
  9842. if (
  9843. last_alarm is None
  9844. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9845. ):
  9846. _ams_alarm_cooldown[cooldown_key] = now
  9847. logger.info(
  9848. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  9849. )
  9850. try:
  9851. # Call different notification method based on AMS type
  9852. if is_ams_ht:
  9853. await notification_service.on_ams_ht_humidity_high(
  9854. printer.id,
  9855. printer.name,
  9856. ams_label,
  9857. humidity,
  9858. effective_humidity_threshold,
  9859. db,
  9860. )
  9861. else:
  9862. await notification_service.on_ams_humidity_high(
  9863. printer.id,
  9864. printer.name,
  9865. ams_label,
  9866. humidity,
  9867. effective_humidity_threshold,
  9868. db,
  9869. )
  9870. except Exception as e:
  9871. logger.warning("Failed to send humidity alarm: %s", e)
  9872. # A drying cycle heats the unit far past ams_temp_fair on
  9873. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  9874. # AMS-HT, against a 35 C default — so the alarm fired
  9875. # once an hour for the whole cycle and kept firing while
  9876. # the unit cooled back down (#1802). Latch on the
  9877. # firmware's own drying state and hold until the reading
  9878. # returns to normal. Humidity is deliberately left alone:
  9879. # it falls during drying, which is the whole point.
  9880. latch_key = f"{printer.id}:{ams_id}"
  9881. # The latch releases at `threshold`, so it takes the alarm
  9882. # number too. Handing it the display band would strand the
  9883. # latch on any unit that settles back above it -- a room
  9884. # where the AMS rests at 37.7 C never returns under a 35 C
  9885. # band, so the latch could only expire on the grace cap
  9886. # rather than releasing when the unit had actually cooled.
  9887. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  9888. drying_active=is_drying_active(ams_data),
  9889. temperature=temperature,
  9890. threshold=temp_alarm_threshold,
  9891. latched_at=drying_latch.get(latch_key),
  9892. now=datetime.now(timezone.utc),
  9893. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  9894. )
  9895. if new_latch is None:
  9896. drying_latch.pop(latch_key, None)
  9897. else:
  9898. drying_latch[latch_key] = new_latch
  9899. # Check temperature alarm (only if above threshold)
  9900. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  9901. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  9902. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9903. now = datetime.now(timezone.utc)
  9904. if (
  9905. last_alarm is None
  9906. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9907. ):
  9908. _ams_alarm_cooldown[cooldown_key] = now
  9909. logger.info(
  9910. f"Sending temperature alarm for {printer.name} {ams_label}: "
  9911. f"{temperature}°C > {temp_alarm_threshold}°C"
  9912. )
  9913. try:
  9914. # Call different notification method based on AMS type
  9915. if is_ams_ht:
  9916. # The reported threshold has to be the one
  9917. # that fired, or the message says "> 35 °C"
  9918. # while firing at 45.
  9919. await notification_service.on_ams_ht_temperature_high(
  9920. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9921. )
  9922. else:
  9923. await notification_service.on_ams_temperature_high(
  9924. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9925. )
  9926. except Exception as e:
  9927. logger.warning("Failed to send temperature alarm: %s", e)
  9928. if drying_latch != drying_latch_before:
  9929. await _save_ams_drying_latch(db, drying_latch)
  9930. await db.commit()
  9931. if recorded_count > 0:
  9932. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  9933. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  9934. global _ams_cleanup_counter
  9935. _ams_cleanup_counter += 1
  9936. if _ams_cleanup_counter >= 288:
  9937. _ams_cleanup_counter = 0
  9938. # Get retention days from settings
  9939. from backend.app.models.settings import Settings
  9940. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  9941. setting = result.scalar_one_or_none()
  9942. retention_days = _retention_days(setting.value if setting else None, AMS_HISTORY_RETENTION_DAYS)
  9943. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9944. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  9945. await db.commit()
  9946. if result.rowcount > 0:
  9947. logger.info(
  9948. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  9949. )
  9950. # Wait until next recording interval
  9951. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  9952. except asyncio.CancelledError:
  9953. break
  9954. except Exception as e:
  9955. logger.warning("AMS history recording failed: %s", e)
  9956. await asyncio.sleep(60) # Wait a bit before retrying
  9957. def start_ams_history_recording():
  9958. """Start the AMS history recording background task."""
  9959. global _ams_history_task
  9960. if _ams_history_task is None:
  9961. _ams_history_task = asyncio.create_task(record_ams_history())
  9962. logging.getLogger(__name__).info("AMS history recording started")
  9963. def stop_ams_history_recording():
  9964. """Stop the AMS history recording background task."""
  9965. global _ams_history_task
  9966. if _ams_history_task:
  9967. _ams_history_task.cancel()
  9968. _ams_history_task = None
  9969. logging.getLogger(__name__).info("AMS history recording stopped")
  9970. # Printer sensor history recording (nozzle / bed / chamber)
  9971. _printer_sensor_history_task: asyncio.Task | None = None
  9972. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  9973. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  9974. _printer_sensor_cleanup_counter = 0
  9975. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  9976. # MQTT parser writes, so we don't need to handle per-model field aliases here
  9977. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  9978. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  9979. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  9980. _SENSOR_TARGET_KEYS = {
  9981. "nozzle": "nozzle_target",
  9982. "nozzle_2": "nozzle_2_target",
  9983. "bed": "bed_target",
  9984. "chamber": "chamber_target",
  9985. }
  9986. async def record_printer_sensor_history():
  9987. """Background task to record nozzle / bed / chamber readings.
  9988. Pulls from `state.temperatures` (already normalised across all printer
  9989. models by the MQTT parser) rather than re-parsing raw_data, so we get
  9990. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  9991. """
  9992. logger = logging.getLogger(__name__)
  9993. await asyncio.sleep(10)
  9994. while True:
  9995. try:
  9996. from backend.app.models.printer import Printer
  9997. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  9998. from backend.app.models.settings import Settings
  9999. async with async_session() as db:
  10000. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  10001. printers = result.scalars().all()
  10002. recorded_count = 0
  10003. for printer in printers:
  10004. state = printer_manager.get_status(printer.id)
  10005. if not state or not state.connected:
  10006. continue
  10007. temps = getattr(state, "temperatures", None) or {}
  10008. if not isinstance(temps, dict):
  10009. continue
  10010. for kind in _SENSOR_KINDS:
  10011. if kind not in temps:
  10012. continue
  10013. try:
  10014. value = float(temps[kind])
  10015. except (ValueError, TypeError):
  10016. continue
  10017. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  10018. target_val: float | None = None
  10019. if target_raw is not None:
  10020. try:
  10021. target_val = float(target_raw)
  10022. except (ValueError, TypeError):
  10023. target_val = None
  10024. db.add(
  10025. PrinterSensorHistory(
  10026. printer_id=printer.id,
  10027. sensor_kind=kind,
  10028. value=value,
  10029. target=target_val,
  10030. )
  10031. )
  10032. recorded_count += 1
  10033. await db.commit()
  10034. if recorded_count > 0:
  10035. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  10036. # Periodic cleanup — once every ~24h at this interval.
  10037. global _printer_sensor_cleanup_counter
  10038. _printer_sensor_cleanup_counter += 1
  10039. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  10040. if _printer_sensor_cleanup_counter >= cleanup_every:
  10041. _printer_sensor_cleanup_counter = 0
  10042. result = await db.execute(
  10043. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  10044. )
  10045. setting = result.scalar_one_or_none()
  10046. retention_days = _retention_days(
  10047. setting.value if setting else None, PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  10048. )
  10049. cutoff = utcnow_naive() - timedelta(days=retention_days)
  10050. cleanup = await db.execute(
  10051. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  10052. )
  10053. await db.commit()
  10054. if cleanup.rowcount > 0:
  10055. logger.info(
  10056. "Cleaned up %s old printer sensor history entries (older than %s days)",
  10057. cleanup.rowcount,
  10058. retention_days,
  10059. )
  10060. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  10061. except asyncio.CancelledError:
  10062. break
  10063. except Exception as e:
  10064. logger.warning("Printer sensor history recording failed: %s", e)
  10065. await asyncio.sleep(60)
  10066. def start_printer_sensor_history_recording():
  10067. global _printer_sensor_history_task
  10068. if _printer_sensor_history_task is None:
  10069. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  10070. logging.getLogger(__name__).info("Printer sensor history recording started")
  10071. def stop_printer_sensor_history_recording():
  10072. global _printer_sensor_history_task
  10073. if _printer_sensor_history_task:
  10074. _printer_sensor_history_task.cancel()
  10075. _printer_sensor_history_task = None
  10076. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  10077. # Printer runtime tracking
  10078. _runtime_tracking_task: asyncio.Task | None = None
  10079. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  10080. # Printers the runtime tracker has seen connected since startup. One of them
  10081. # going offline clears its timestamp, so the time it was away is not counted
  10082. # when it comes back printing (DB-C5). A printer not yet seen -- still
  10083. # connecting after a restart -- keeps it for a grace period: a print that ran
  10084. # on through a Bambuddy restart is counted from the stored timestamp, as before.
  10085. _runtime_seen_connected: set[int] = set()
  10086. # A printer never seen connected this long after the tracker started is
  10087. # offline, not still connecting: its stored timestamp predates a gap too.
  10088. RUNTIME_STARTUP_GRACE_SECONDS = 120
  10089. async def track_printer_runtime():
  10090. """Background task to track printer active runtime (RUNNING state only).
  10091. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  10092. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  10093. which track mechanical wear. Pause time has no motion and no wear, so
  10094. counting it inflates maintenance warnings (#1521).
  10095. """
  10096. logger = logging.getLogger(__name__)
  10097. # Wait for MQTT connections to establish on startup
  10098. await asyncio.sleep(15)
  10099. started = time.monotonic()
  10100. while True:
  10101. try:
  10102. from backend.app.models.printer import Printer
  10103. # Fetch printer IDs in a short-lived read-only session
  10104. async with async_session() as db:
  10105. result = await db.execute(
  10106. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  10107. Printer.is_active.is_(True)
  10108. )
  10109. )
  10110. printer_rows = result.all()
  10111. now = datetime.now(timezone.utc)
  10112. updated_count = 0
  10113. # Update each printer in its own short session to minimise write-lock
  10114. # hold time and avoid blocking critical commits like queue status
  10115. # updates (#897).
  10116. for pid, pname, runtime_secs, last_update in printer_rows:
  10117. state = printer_manager.get_status(pid)
  10118. if not state:
  10119. logger.debug("[%s] Runtime tracking: no state available", pname)
  10120. continue
  10121. if not state.connected:
  10122. logger.debug("[%s] Runtime tracking: not connected", pname)
  10123. offline = pid in _runtime_seen_connected or (
  10124. time.monotonic() - started > RUNTIME_STARTUP_GRACE_SECONDS
  10125. )
  10126. if offline and last_update is not None:
  10127. try:
  10128. async with async_session() as db:
  10129. printer = await db.get(Printer, pid)
  10130. if printer:
  10131. printer.last_runtime_update = None
  10132. await db.commit()
  10133. except Exception as e:
  10134. # Still marked: the next offline tick tries again.
  10135. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  10136. continue
  10137. _runtime_seen_connected.discard(pid)
  10138. continue
  10139. _runtime_seen_connected.add(pid)
  10140. needs_commit = False
  10141. new_runtime = runtime_secs
  10142. new_last_update = last_update
  10143. if state.state == "RUNNING":
  10144. if last_update:
  10145. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  10146. elapsed = (now - lu).total_seconds()
  10147. if elapsed > 0:
  10148. new_runtime = runtime_secs + int(elapsed)
  10149. updated_count += 1
  10150. needs_commit = True
  10151. logger.debug(
  10152. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  10153. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  10154. )
  10155. else:
  10156. needs_commit = True
  10157. logger.debug("[%s] Runtime tracking: first active detection", pname)
  10158. new_last_update = now
  10159. else:
  10160. if last_update is not None:
  10161. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  10162. new_last_update = None
  10163. needs_commit = True
  10164. if needs_commit:
  10165. try:
  10166. async with async_session() as db:
  10167. result = await db.execute(select(Printer).where(Printer.id == pid))
  10168. printer = result.scalar_one_or_none()
  10169. if printer:
  10170. printer.runtime_seconds = new_runtime
  10171. printer.last_runtime_update = new_last_update
  10172. await db.commit()
  10173. except Exception as e:
  10174. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  10175. if updated_count > 0:
  10176. logger.debug("Updated runtime for %s printer(s)", updated_count)
  10177. except asyncio.CancelledError:
  10178. logger.info("Runtime tracking cancelled")
  10179. break
  10180. except Exception as e:
  10181. logger.warning("Runtime tracking failed: %s", e)
  10182. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  10183. def start_runtime_tracking():
  10184. """Start the printer runtime tracking background task."""
  10185. global _runtime_tracking_task
  10186. if _runtime_tracking_task is None:
  10187. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  10188. logging.getLogger(__name__).info("Printer runtime tracking started")
  10189. def stop_runtime_tracking():
  10190. """Stop the printer runtime tracking background task."""
  10191. global _runtime_tracking_task
  10192. if _runtime_tracking_task:
  10193. _runtime_tracking_task.cancel()
  10194. _runtime_tracking_task = None
  10195. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  10196. # SpoolBuddy device watchdog
  10197. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  10198. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  10199. async def _spoolbuddy_watchdog_loop():
  10200. """Periodic check for SpoolBuddy devices that have gone offline."""
  10201. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  10202. while True:
  10203. try:
  10204. await spoolbuddy_watchdog()
  10205. except asyncio.CancelledError:
  10206. break
  10207. except Exception as e:
  10208. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  10209. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  10210. def start_spoolbuddy_watchdog():
  10211. global _spoolbuddy_watchdog_task
  10212. if _spoolbuddy_watchdog_task is None:
  10213. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  10214. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  10215. def stop_spoolbuddy_watchdog():
  10216. global _spoolbuddy_watchdog_task
  10217. if _spoolbuddy_watchdog_task:
  10218. _spoolbuddy_watchdog_task.cancel()
  10219. _spoolbuddy_watchdog_task = None
  10220. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  10221. # Dead-MQTT-session recovery
  10222. #
  10223. # check_staleness() covers the "connected but silent" half-broken session. It
  10224. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  10225. # is the only thing left watching at that point. When paho stops making
  10226. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  10227. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  10228. # offline with the UI open the whole time, recovered only when something
  10229. # happened to nudge it.
  10230. #
  10231. # This loop is that backstop. It only touches printers that had a working
  10232. # session and lost it, and only when the MQTT port still answers — a printer
  10233. # that is simply switched off is left to paho, since rebuilding a client
  10234. # against an unreachable host achieves nothing and would fill the log every
  10235. # night.
  10236. _connection_watchdog_task: asyncio.Task | None = None
  10237. CONNECTION_WATCHDOG_INTERVAL = 60
  10238. # How long a printer must have been silent before we stop trusting paho.
  10239. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  10240. # so a session that is recovering on its own is never interrupted.
  10241. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  10242. # Per-printer floor between rebuild attempts.
  10243. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  10244. _connection_watchdog_last_attempt: dict[int, float] = {}
  10245. async def _recover_dead_printer_sessions() -> int:
  10246. """Rebuild MQTT clients that have been offline too long to still be trying.
  10247. Returns the number of printers a rebuild was attempted for (for tests and
  10248. for the caller's logging). Never raises: one unreachable printer must not
  10249. stop the sweep for the rest of the farm.
  10250. """
  10251. logger = logging.getLogger(__name__)
  10252. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  10253. now = time.monotonic()
  10254. recovered = 0
  10255. for printer_id, client in list(printer_manager._clients.items()):
  10256. try:
  10257. if client.state.connected:
  10258. _connection_watchdog_last_attempt.pop(printer_id, None)
  10259. continue
  10260. # Time since the last inbound message is the age of the last known
  10261. # good session — no extra bookkeeping needed, and it is the same
  10262. # clock is_stale() reads. 0 means this client has never had one:
  10263. # that is the initial-connect path, where paho retrying is the
  10264. # correct and only behaviour, so leave it be.
  10265. last_msg = client._last_message_time
  10266. if not last_msg:
  10267. continue
  10268. offline_for = time.time() - last_msg
  10269. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  10270. continue
  10271. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  10272. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  10273. continue
  10274. if not await check_port(client.ip_address, PORT_MQTT):
  10275. # Switched off, unplugged, or off the network. Paho's retry is
  10276. # the right handler; say so at debug level and move on.
  10277. logger.debug(
  10278. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  10279. "— leaving the reconnect to paho",
  10280. printer_id,
  10281. offline_for,
  10282. )
  10283. _connection_watchdog_last_attempt[printer_id] = now
  10284. continue
  10285. _connection_watchdog_last_attempt[printer_id] = now
  10286. recovered += 1
  10287. logger.warning(
  10288. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  10289. "rebuilding the client with a fresh session (last connect error: %s)",
  10290. printer_id,
  10291. offline_for,
  10292. PORT_MQTT,
  10293. client.last_connect_error or "none recorded",
  10294. )
  10295. # Async context, so this takes the hard-reset path: fresh client_id,
  10296. # paho's QoS 1 queue dropped. That matters — a project_file left
  10297. # unacked on the dead session would otherwise replay into the new
  10298. # one and trip 0500_4003 on the printer (#1136).
  10299. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  10300. except Exception as e:
  10301. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  10302. return recovered
  10303. async def _connection_watchdog_loop():
  10304. logger = logging.getLogger(__name__)
  10305. # Let the initial connects settle before judging anyone offline.
  10306. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  10307. while True:
  10308. try:
  10309. await _recover_dead_printer_sessions()
  10310. except asyncio.CancelledError:
  10311. break
  10312. except Exception as e:
  10313. logger.warning("Connection watchdog sweep failed: %s", e)
  10314. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  10315. def start_connection_watchdog():
  10316. global _connection_watchdog_task
  10317. if _connection_watchdog_task is None:
  10318. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  10319. logging.getLogger(__name__).info("Printer connection watchdog started")
  10320. def stop_connection_watchdog():
  10321. global _connection_watchdog_task
  10322. if _connection_watchdog_task:
  10323. _connection_watchdog_task.cancel()
  10324. _connection_watchdog_task = None
  10325. _connection_watchdog_last_attempt.clear()
  10326. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  10327. # Camera stream orphan cleanup
  10328. _camera_cleanup_task: asyncio.Task | None = None
  10329. CAMERA_CLEANUP_INTERVAL = 60
  10330. # Every this many camera cleanups (about an hour), the timelapse janitor too:
  10331. # kept frames of a failed stitch go after a day, not at the next restart.
  10332. TIMELAPSE_CLEANUP_EVERY = 60
  10333. async def _camera_cleanup_loop():
  10334. """Periodically clean up orphaned ffmpeg processes and timelapse leftovers."""
  10335. from backend.app.api.routes.camera import cleanup_orphaned_streams
  10336. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10337. rounds = 0
  10338. while True:
  10339. try:
  10340. rounds += 1
  10341. await cleanup_orphaned_streams()
  10342. except asyncio.CancelledError:
  10343. break
  10344. except Exception as e:
  10345. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  10346. try:
  10347. if rounds % TIMELAPSE_CLEANUP_EVERY == 0:
  10348. await asyncio.to_thread(cleanup_orphaned_timelapse_sessions)
  10349. except asyncio.CancelledError:
  10350. break
  10351. except Exception as e:
  10352. logging.getLogger(__name__).warning("Timelapse frames cleanup failed: %s", e)
  10353. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  10354. def start_camera_cleanup():
  10355. global _camera_cleanup_task
  10356. if _camera_cleanup_task is None:
  10357. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  10358. logging.getLogger(__name__).info("Camera stream cleanup started")
  10359. def stop_camera_cleanup():
  10360. global _camera_cleanup_task
  10361. if _camera_cleanup_task:
  10362. _camera_cleanup_task.cancel()
  10363. _camera_cleanup_task = None
  10364. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  10365. # ---------------------------------------------------------------------------
  10366. # Expected-print TTL eviction
  10367. # ---------------------------------------------------------------------------
  10368. def _evict_stale_expected_prints() -> None:
  10369. """Remove entries from _expected_prints / _expected_print_creators that are
  10370. older than _EXPECTED_PRINT_TTL_SECONDS.
  10371. This prevents unbounded growth when a print is registered (via
  10372. register_expected_print) but on_print_start never fires — e.g. because the
  10373. printer disconnects, the app restarts, or the print is started directly from
  10374. the printer panel without going through the queue.
  10375. """
  10376. # Use monotonic time so the TTL is unaffected by system clock adjustments
  10377. # (e.g. NTP sync, DST changes).
  10378. # A print that ended without its archive being found at completion leaves
  10379. # its id here; only running prints are owned.
  10380. _owned_print_archive_ids.intersection_update(_active_prints.values())
  10381. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  10382. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  10383. if not stale_keys:
  10384. return
  10385. evicted: set[tuple[int, int]] = set()
  10386. for key in stale_keys:
  10387. archive_id = _expected_prints.pop(key, None)
  10388. if archive_id is not None:
  10389. evicted.add((key[0], archive_id))
  10390. _expected_print_creators.pop(key, None)
  10391. _expected_print_registered_at.pop(key, None)
  10392. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  10393. # that have no remaining live keys in _expected_prints (all variants
  10394. # were just evicted) and are not printing right now. Print start pops
  10395. # only the names the printer reported, so the "<base>.gcode" variant
  10396. # outlives it; without the printing check its eviction two hours after
  10397. # dispatch threw away a running print's plate, AMS mapping and cost
  10398. # centre, which completion still reads (#3275).
  10399. for printer_id, archive_id in evicted:
  10400. if not _expected_or_printing_here(printer_id, archive_id):
  10401. _drop_dispatch(printer_id, archive_id)
  10402. logging.getLogger(__name__).info(
  10403. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  10404. )
  10405. async def _expected_prints_cleanup_loop() -> None:
  10406. """Background task: periodically evict stale expected-print entries."""
  10407. while True:
  10408. try:
  10409. _evict_stale_expected_prints()
  10410. except asyncio.CancelledError:
  10411. raise
  10412. except Exception as e:
  10413. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  10414. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  10415. def start_expected_prints_cleanup() -> None:
  10416. global _expected_prints_cleanup_task
  10417. if _expected_prints_cleanup_task is None:
  10418. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  10419. logging.getLogger(__name__).info("Expected prints cleanup started")
  10420. def stop_expected_prints_cleanup() -> None:
  10421. global _expected_prints_cleanup_task
  10422. if _expected_prints_cleanup_task:
  10423. _expected_prints_cleanup_task.cancel()
  10424. _expected_prints_cleanup_task = None
  10425. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  10426. # ---------------------------------------------------------------------------
  10427. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  10428. # ---------------------------------------------------------------------------
  10429. _auth_cleanup_task: asyncio.Task | None = None
  10430. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  10431. async def _run_auth_cleanup() -> None:
  10432. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  10433. from backend.app.core.database import async_session
  10434. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  10435. from backend.app.models.user_totp import UserTOTP
  10436. now = datetime.now(timezone.utc)
  10437. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  10438. try:
  10439. async with async_session() as db:
  10440. stale_cutoff = now - timedelta(hours=1)
  10441. result = await db.execute(
  10442. select(UserTOTP).where(
  10443. UserTOTP.is_enabled.is_(False),
  10444. UserTOTP.created_at < stale_cutoff,
  10445. )
  10446. )
  10447. stale_records = result.scalars().all()
  10448. if stale_records:
  10449. for rec in stale_records:
  10450. await db.delete(rec)
  10451. await db.commit()
  10452. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  10453. except Exception as e:
  10454. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  10455. # Remove expired revoked-JTI entries (they are no longer needed once the
  10456. # original token's exp has passed — the token would be rejected by JWT
  10457. # signature verification regardless).
  10458. try:
  10459. async with async_session() as db:
  10460. await db.execute(
  10461. delete(AuthEphemeralToken).where(
  10462. AuthEphemeralToken.token_type == "revoked_jti",
  10463. AuthEphemeralToken.expires_at < now,
  10464. )
  10465. )
  10466. await db.commit()
  10467. except Exception as e:
  10468. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  10469. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  10470. # Events outside this window can never affect rate-limit decisions — they only
  10471. # consume DB space. Use the same window constant as the rate limiter so the
  10472. # two are always in sync.
  10473. try:
  10474. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  10475. async with async_session() as db:
  10476. await db.execute(
  10477. delete(AuthRateLimitEvent).where(
  10478. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  10479. )
  10480. )
  10481. await db.commit()
  10482. except Exception as e:
  10483. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  10484. async def _auth_cleanup_loop() -> None:
  10485. """Periodic background task: run auth cleanup every hour."""
  10486. while True:
  10487. try:
  10488. await _run_auth_cleanup()
  10489. except asyncio.CancelledError:
  10490. break
  10491. except Exception as e:
  10492. logging.warning("Auth cleanup loop error: %s", e)
  10493. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  10494. def start_auth_cleanup() -> None:
  10495. global _auth_cleanup_task
  10496. if _auth_cleanup_task is None:
  10497. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  10498. logging.getLogger(__name__).info("Auth periodic cleanup started")
  10499. def stop_auth_cleanup() -> None:
  10500. global _auth_cleanup_task
  10501. if _auth_cleanup_task:
  10502. _auth_cleanup_task.cancel()
  10503. _auth_cleanup_task = None
  10504. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  10505. @asynccontextmanager
  10506. async def lifespan(app: FastAPI):
  10507. # Startup
  10508. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  10509. # anything else can spawn tasks that might trip it.
  10510. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  10511. install_proactor_reset_filter()
  10512. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  10513. # what turned descriptor exhaustion into a corrupted database (#2883).
  10514. from backend.app.core.fd_limit import raise_open_file_limit
  10515. raise_open_file_limit()
  10516. # Before init_db, so the warning is near the top of the log rather than
  10517. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  10518. warn_if_running_on_uvloop()
  10519. await init_db()
  10520. # Browser download tokens expire after five minutes. Remove abandoned
  10521. # prepared ZIPs at startup as well as before each new preparation so a
  10522. # quiet appliance cannot retain an unusable bundle indefinitely.
  10523. try:
  10524. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  10525. await prune_stale_printer_file_bundles()
  10526. except Exception as exc:
  10527. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  10528. # After migrations, so the is_env_managed column exists. Never raises --
  10529. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  10530. # startup (see apply_env_oidc_provider).
  10531. from backend.app.core.oidc_env import apply_env_oidc_provider
  10532. async with async_session() as oidc_db:
  10533. await apply_env_oidc_provider(oidc_db)
  10534. # Close out batches that finished before `completed` was a reachable status
  10535. # (#342). Without this the Batches tab opens on every batch created since
  10536. # the feature shipped, all still marked active. Never blocks startup.
  10537. try:
  10538. from backend.app.services.print_batch import backfill_batch_statuses
  10539. async with async_session() as batch_db:
  10540. await backfill_batch_statuses(batch_db)
  10541. except Exception as exc:
  10542. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  10543. # Each plate's estimate of archives made before they were kept (#3375),
  10544. # read from their 3MFs in the background: the readers use the whole
  10545. # file's figures until then.
  10546. global _plate_estimates_task
  10547. _plate_estimates_task = asyncio.create_task(_fill_plate_estimates())
  10548. # Register an app-scoped httpx client for Bambu Cloud services so
  10549. # per-request BambuCloudService instances reuse the same connection pool
  10550. # (important for routes like /cloud/filament-info that chain many
  10551. # get_setting_detail calls). The shared client stores no region/token
  10552. # state, so the per-request ownership pattern that fixed the region-bleed
  10553. # bug is preserved.
  10554. import httpx as _httpx
  10555. from backend.app.services.bambu_cloud import set_shared_http_client
  10556. from backend.app.services.model_providers.makerworld.service import (
  10557. set_shared_http_client as set_shared_makerworld_http_client,
  10558. )
  10559. from backend.app.services.orca_cloud import (
  10560. set_shared_http_client as set_shared_orca_http_client,
  10561. )
  10562. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  10563. set_shared_http_client(_shared_cloud_http_client)
  10564. # Reuse the same connection pool for MakerWorld — different host, same
  10565. # keep-alive pool saves a TLS handshake per request.
  10566. set_shared_makerworld_http_client(_shared_cloud_http_client)
  10567. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  10568. # each spun up (and never closed) its own client, leaking sockets.
  10569. set_shared_orca_http_client(_shared_cloud_http_client)
  10570. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  10571. # This can happen when a print was cancelled mid-print on versions before this fix.
  10572. try:
  10573. async with async_session() as db:
  10574. from backend.app.models.print_queue import PrintQueueItem
  10575. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  10576. aborted_items = result.scalars().all()
  10577. if aborted_items:
  10578. for item in aborted_items:
  10579. item.status = "cancelled"
  10580. await db.commit()
  10581. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  10582. except Exception as e:
  10583. logging.warning("Failed to fix aborted queue items: %s", e)
  10584. # Restore debug logging state from previous session
  10585. await init_debug_logging()
  10586. # Set up printer manager callbacks
  10587. loop = asyncio.get_event_loop()
  10588. printer_manager.set_event_loop(loop)
  10589. printer_manager.set_status_change_callback(on_printer_status_change)
  10590. printer_manager.set_print_start_callback(on_print_start)
  10591. printer_manager.set_print_complete_callback(on_print_complete)
  10592. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  10593. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  10594. printer_manager.set_ams_change_callback(on_ams_change)
  10595. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  10596. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  10597. await printer_manager.load_awaiting_plate_clear_from_db()
  10598. # Layer change callback for external camera timelapse
  10599. async def on_layer_change(printer_id: int, layer_num: int):
  10600. """Capture timelapse frame on layer change + first layer notification."""
  10601. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  10602. await tl_layer_change(printer_id, layer_num)
  10603. # #1867: bank a recent in-print frame so the finish-photo path has a
  10604. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  10605. # #2547 added `on_print_progress` as a second driver — this one alone
  10606. # stops firing once the final layer begins.
  10607. await _maybe_bank_inprint_frame(printer_id, layer_num)
  10608. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  10609. # Gate on actual printing state — Bambu firmware ticks layer_num during
  10610. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  10611. # nozzle clean), so a bare layer_num check can fire minutes before the
  10612. # first real extrusion. We require gcode_state == RUNNING and
  10613. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  10614. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  10615. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  10616. # edge fires later; _first_layer_notified stays clear until we actually send
  10617. # so a deferred re-evaluation can win. See issue #1837.
  10618. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  10619. client = printer_manager.get_client(printer_id)
  10620. state = client.state if client else None
  10621. if not state or state.state != "RUNNING":
  10622. return
  10623. if state.mc_print_sub_stage not in (None, 0):
  10624. return
  10625. _first_layer_notified[printer_id] = True
  10626. try:
  10627. async with async_session() as db:
  10628. from backend.app.models.printer import Printer
  10629. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  10630. printer = result.scalar_one_or_none()
  10631. if not printer:
  10632. return
  10633. printer_name = printer.name
  10634. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  10635. total_layers = state.total_layers if state else 0
  10636. image_data = await _capture_snapshot_for_notification(
  10637. printer_id, printer, logging.getLogger(__name__)
  10638. )
  10639. await notification_service.on_first_layer_complete(
  10640. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  10641. )
  10642. except Exception as e:
  10643. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  10644. printer_manager.set_layer_change_callback(on_layer_change)
  10645. async def on_print_progress(printer_id: int, percent: int):
  10646. """#2547: keep the in-print frame bank fresh through the final layer.
  10647. `on_layer_change` stops the moment the last layer starts, which on the
  10648. H2C capture that closed #2547 left the bank stale for the three minutes
  10649. that layer took. Progress is the only field that keeps advancing there,
  10650. and it freezes before the End G-code runs — so banking on it stays
  10651. inside the print and never sees a swapped plate.
  10652. """
  10653. client = printer_manager.get_client(printer_id)
  10654. state = client.state if client else None
  10655. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  10656. printer_manager.set_print_progress_callback(on_print_progress)
  10657. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  10658. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  10659. waiter = _bed_cool_waiters.get(printer_id)
  10660. if not waiter:
  10661. return
  10662. threshold = waiter["threshold"]
  10663. if bed_temp > threshold:
  10664. return
  10665. # Bed is at or below threshold — fire notification and remove waiter
  10666. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  10667. if not waiter_info:
  10668. return # Another callback already handled it
  10669. bed_cool_logger = logging.getLogger(__name__)
  10670. bed_cool_logger.info(
  10671. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  10672. bed_temp,
  10673. printer_id,
  10674. threshold,
  10675. )
  10676. try:
  10677. printer_info = printer_manager.get_printer(printer_id)
  10678. p_name = printer_info.name if printer_info else "Unknown"
  10679. async with async_session() as db:
  10680. await notification_service.on_bed_cooled(
  10681. printer_id=printer_id,
  10682. printer_name=p_name,
  10683. bed_temp=bed_temp,
  10684. threshold=threshold,
  10685. filename=waiter_info["filename"],
  10686. db=db,
  10687. )
  10688. except Exception as e:
  10689. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  10690. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  10691. async def on_drying_complete(printer_id: int, ams_id: int):
  10692. """Smart-plug auto-off-after-drying trigger (#1349).
  10693. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  10694. manager walks all plugs linked to this printer and turns off only
  10695. the ones with ``auto_off_after_drying`` enabled, after their
  10696. per-plug delay. Multiple AMS units finishing close together (e.g. a
  10697. dual-AMS dry that ends within the same MQTT push) call this once
  10698. per unit — the manager's ``_cancel_pending_off`` collapses
  10699. repeated scheduling on the same plug to one timer, so duplicate
  10700. fires are safe.
  10701. """
  10702. try:
  10703. async with async_session() as db:
  10704. await smart_plug_manager.on_drying_complete(printer_id, db)
  10705. except Exception as e:
  10706. logging.getLogger(__name__).warning(
  10707. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  10708. printer_id,
  10709. ams_id,
  10710. e,
  10711. )
  10712. printer_manager.set_drying_complete_callback(on_drying_complete)
  10713. async def on_drying_cycle_end(printer_id: int, cycle):
  10714. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  10715. from backend.app.services.spool_drying import record_drying_cycle
  10716. try:
  10717. async with async_session() as db:
  10718. await record_drying_cycle(db, printer_id, cycle)
  10719. except Exception as e:
  10720. logging.getLogger(__name__).warning(
  10721. "Failed to record drying for printer %d (AMS %d): %s",
  10722. printer_id,
  10723. cycle.ams_id,
  10724. e,
  10725. )
  10726. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  10727. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  10728. """Surface the read-back result of a spool assignment to the UI (#2582).
  10729. The MQTT client confirms (or fails to confirm) that the tray telemetry
  10730. echoed back the filament id we pushed. We relay that as a websocket
  10731. event so the frontend can toast "loaded" / "assignment didn't take"
  10732. instead of the historic silent fire-and-forget, which made the
  10733. AMS→Studio hand-off feel random to users.
  10734. """
  10735. try:
  10736. from backend.app.services.spool_assignment_notifications import (
  10737. _slot_label_from_global_tray,
  10738. )
  10739. if ams_id == 255:
  10740. global_id = 254 + tray_id
  10741. elif ams_id >= 128:
  10742. global_id = ams_id
  10743. else:
  10744. global_id = ams_id * 4 + tray_id
  10745. slot_label = _slot_label_from_global_tray(global_id)
  10746. printer_info = printer_manager.get_printer(printer_id)
  10747. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  10748. await ws_manager.broadcast(
  10749. {
  10750. "type": "spool_assignment_verified",
  10751. "printer_id": printer_id,
  10752. "printer_name": printer_name,
  10753. "ams_id": ams_id,
  10754. "tray_id": tray_id,
  10755. "slot": slot_label,
  10756. "verified": verified,
  10757. # Present on success: False means the filament setting landed
  10758. # but the K-profile (cali_idx) did not — the reporter's exact
  10759. # "loaded but no flow profile" symptom.
  10760. "kprofile_applied": detail.get("kprofile_applied", True),
  10761. }
  10762. )
  10763. except Exception as e:
  10764. logging.getLogger(__name__).warning(
  10765. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  10766. printer_id,
  10767. ams_id,
  10768. tray_id,
  10769. e,
  10770. )
  10771. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  10772. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  10773. """Persist a mid-print tray change for completion-time attribution.
  10774. AMS filament backup switches trays without telling the slicer, so the
  10775. tray-change log is the only record of which spool fed which layers.
  10776. Keeping it only in memory meant a restart mid-print charged everything
  10777. to the tray that finished the job.
  10778. """
  10779. try:
  10780. from backend.app.services.usage_tracker import record_tray_change
  10781. async with async_session() as db:
  10782. await record_tray_change(db, printer_id, tray_global, layer_num)
  10783. except Exception as e:
  10784. logging.getLogger(__name__).warning(
  10785. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  10786. printer_id,
  10787. tray_global,
  10788. layer_num,
  10789. e,
  10790. )
  10791. printer_manager.set_tray_change_callback(on_tray_change)
  10792. # Initialize MQTT relay from settings
  10793. async with async_session() as db:
  10794. from backend.app.api.routes.settings import get_setting
  10795. mqtt_settings = {
  10796. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  10797. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  10798. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  10799. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  10800. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  10801. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  10802. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  10803. }
  10804. await mqtt_relay.configure(mqtt_settings)
  10805. # Restore MQTT smart plug subscriptions
  10806. if mqtt_settings.get("mqtt_enabled"):
  10807. from backend.app.models.smart_plug import SmartPlug
  10808. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  10809. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  10810. mqtt_plugs = result.scalars().all()
  10811. restored = 0
  10812. for plug in mqtt_plugs:
  10813. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  10814. restored += 1
  10815. if restored:
  10816. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  10817. # Connect to all active printers
  10818. async with async_session() as db:
  10819. await init_printer_connections(db)
  10820. # Auto-connect to Spoolman if enabled
  10821. async with async_session() as db:
  10822. from backend.app.api.routes.settings import get_setting
  10823. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  10824. spoolman_url = await get_setting(db, "spoolman_url")
  10825. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  10826. try:
  10827. client = await init_spoolman_client(spoolman_url)
  10828. if await client.health_check():
  10829. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  10830. # Ensure the 'tag' extra field exists for RFID/UUID storage
  10831. field_ok = await client.ensure_tag_extra_field()
  10832. if not field_ok:
  10833. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  10834. # Register the BambuStudio slicer-preset fields used by the
  10835. # spool-edit / assign flow. Spoolman rejects PATCHes with
  10836. # unknown extra keys, so these must exist before any update
  10837. # that touches them.
  10838. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  10839. if not await client.ensure_extra_field(field_name):
  10840. logging.warning(
  10841. "Spoolman extra field %r registration failed — "
  10842. "spool slicer-preset edits will return 502",
  10843. field_name,
  10844. )
  10845. else:
  10846. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  10847. except Exception as e:
  10848. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  10849. # Start the print scheduler
  10850. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  10851. # Start the smart plug scheduler for time-based on/off
  10852. smart_plug_manager.start_scheduler()
  10853. # Start the Home Assistant sensor poller (#1148)
  10854. ha_sensor_manager.start()
  10855. location_ha_sensor_manager.start()
  10856. # Resume any pending auto-offs that were interrupted by restart
  10857. await smart_plug_manager.resume_pending_auto_offs()
  10858. # Start the notification digest scheduler
  10859. notification_service.start_digest_scheduler()
  10860. notify_live_activities.start()
  10861. notify_widgets.start()
  10862. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  10863. # provider in reactions/both mode; the notification routes resync them.
  10864. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  10865. # until the next provider save, not the whole startup.
  10866. try:
  10867. await telegram_reaction_poller.start()
  10868. except Exception as e:
  10869. logging.warning("Telegram reaction poller did not start: %s", e)
  10870. # Start the GitHub backup scheduler
  10871. await github_backup_service.start_scheduler()
  10872. # Start the local backup scheduler
  10873. await local_backup_service.start_scheduler()
  10874. await obico_detection_service.start()
  10875. await octoeverywhere_detection_service.start()
  10876. # Start the library trash sweeper (#1008)
  10877. await library_trash_service.start_scheduler()
  10878. # Start the archive auto-purge sweeper (#1008 follow-up)
  10879. await archive_purge_service.start_scheduler()
  10880. # Start AMS history recording
  10881. start_ams_history_recording()
  10882. # Start printer sensor (nozzle / bed / chamber) history recording
  10883. start_printer_sensor_history_recording()
  10884. # Start printer runtime tracking
  10885. start_runtime_tracking()
  10886. # Start SpoolBuddy device watchdog
  10887. start_spoolbuddy_watchdog()
  10888. # Start camera stream orphan cleanup
  10889. start_camera_cleanup()
  10890. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  10891. start_connection_watchdog()
  10892. # One-shot sweep for timelapse session directories orphaned by a crash
  10893. # or restart that happened mid-print (in-memory session tracking can't
  10894. # survive that, and nothing else reaps the leftover frames/output file)
  10895. try:
  10896. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10897. removed = cleanup_orphaned_timelapse_sessions()
  10898. if removed:
  10899. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  10900. except Exception as e:
  10901. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  10902. # Start expected-print TTL eviction (prevents memory leak when prints are
  10903. # registered but on_print_start never fires)
  10904. start_expected_prints_cleanup()
  10905. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  10906. start_auth_cleanup()
  10907. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  10908. from backend.app.services import announcements as announcements_service
  10909. announcements_service.start()
  10910. from backend.app.services.printer_media import start_printer_download_cleanup
  10911. start_printer_download_cleanup()
  10912. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  10913. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  10914. from backend.app.services.loop_watchdog import start_loop_watchdog
  10915. start_loop_watchdog()
  10916. # Initialize virtual printer manager and sync from DB
  10917. from backend.app.services.virtual_printer import virtual_printer_manager
  10918. virtual_printer_manager.set_session_factory(async_session)
  10919. virtual_printer_manager.set_printer_manager(printer_manager)
  10920. try:
  10921. await virtual_printer_manager.sync_from_db()
  10922. logging.info("Virtual printer manager synced from database")
  10923. except Exception as e:
  10924. logging.warning("Failed to sync virtual printers: %s", e)
  10925. yield
  10926. # Shutdown
  10927. print_scheduler.stop()
  10928. smart_plug_manager.stop_scheduler()
  10929. ha_sensor_manager.stop()
  10930. location_ha_sensor_manager.stop()
  10931. notification_service.stop_digest_scheduler()
  10932. await notify_live_activities.close()
  10933. await notify_widgets.close()
  10934. await telegram_reaction_poller.aclose()
  10935. github_backup_service.stop_scheduler()
  10936. local_backup_service.stop_scheduler()
  10937. library_trash_service.stop_scheduler()
  10938. archive_purge_service.stop_scheduler()
  10939. obico_detection_service.stop()
  10940. octoeverywhere_detection_service.stop()
  10941. stop_ams_history_recording()
  10942. stop_printer_sensor_history_recording()
  10943. stop_runtime_tracking()
  10944. stop_spoolbuddy_watchdog()
  10945. stop_camera_cleanup()
  10946. stop_connection_watchdog()
  10947. from backend.app.services.loop_watchdog import stop_loop_watchdog
  10948. stop_loop_watchdog()
  10949. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  10950. # cleanly rather than waiting on a queue that nothing will ever fill.
  10951. try:
  10952. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  10953. await shutdown_all_broadcasters()
  10954. except Exception as e:
  10955. logging.warning("Failed to shut down camera broadcasters: %s", e)
  10956. stop_expected_prints_cleanup()
  10957. stop_auth_cleanup()
  10958. if _plate_estimates_task is not None and not _plate_estimates_task.done():
  10959. _plate_estimates_task.cancel()
  10960. from backend.app.services import announcements as announcements_service
  10961. announcements_service.stop()
  10962. from backend.app.services.printer_media import stop_printer_download_cleanup
  10963. await stop_printer_download_cleanup()
  10964. # Stops a timelapse editor's ffmpeg rather than leaving it to the OS.
  10965. from backend.app.services import timelapse_jobs
  10966. await timelapse_jobs.cancel_all()
  10967. printer_manager.disconnect_all()
  10968. slot_unlink_grace.reset()
  10969. await close_spoolman_client()
  10970. # Stop all virtual printer services
  10971. await virtual_printer_manager.stop_all()
  10972. await mqtt_smart_plug_service.disconnect(timeout=2)
  10973. await mqtt_relay.disconnect(timeout=2)
  10974. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  10975. set_shared_http_client(None)
  10976. set_shared_makerworld_http_client(None)
  10977. set_shared_orca_http_client(None)
  10978. await _shared_cloud_http_client.aclose()
  10979. # Checkpoint WAL (SQLite only) and close all database connections
  10980. from backend.app.core.db_dialect import is_sqlite
  10981. if is_sqlite():
  10982. try:
  10983. async with engine.begin() as conn:
  10984. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  10985. logging.info("WAL checkpoint completed")
  10986. except Exception as e:
  10987. logging.warning("WAL checkpoint failed: %s", e)
  10988. await engine.dispose()
  10989. app = FastAPI(
  10990. title=app_settings.app_name,
  10991. description="Archive and manage Bambu Lab 3MF files",
  10992. version=APP_VERSION,
  10993. lifespan=lifespan,
  10994. )
  10995. # Added first so it sits innermost, next to the routes: a refused header's value
  10996. # (often a stored token) masked in every JSON body. See core.response_redaction.
  10997. app.add_middleware(RefusedHeaderResponseMask)
  10998. def _json_safe(value):
  10999. """The validation errors with every non-finite number written as text."""
  11000. if isinstance(value, float) and not math.isfinite(value):
  11001. return str(value)
  11002. if isinstance(value, dict):
  11003. return {key: _json_safe(item) for key, item in value.items()}
  11004. if isinstance(value, list | tuple):
  11005. return [_json_safe(item) for item in value]
  11006. return value
  11007. @app.exception_handler(RequestValidationError)
  11008. async def _validation_error(_request, exc: RequestValidationError) -> JSONResponse:
  11009. """FastAPI's own 422, except that it survives a non-finite number.
  11010. A body may carry ``Infinity`` or ``NaN`` (Python's JSON reader accepts
  11011. them), and the default handler echoes the input back in its errors,
  11012. which JSON cannot hold: the request ended in an error instead of a 422.
  11013. """
  11014. return JSONResponse(status_code=422, content={"detail": _json_safe(jsonable_encoder(exc.errors()))})
  11015. # =============================================================================
  11016. # Authentication Middleware - Secures ALL API routes by default
  11017. # =============================================================================
  11018. # Public routes that don't require authentication even when auth is enabled
  11019. PUBLIC_API_ROUTES = {
  11020. # Auth routes needed before/during login
  11021. "/api/v1/auth/status",
  11022. "/api/v1/auth/login",
  11023. "/api/v1/auth/setup", # Needed for initial setup and recovery
  11024. # Advanced auth status needed for login page
  11025. "/api/v1/auth/advanced-auth/status",
  11026. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  11027. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  11028. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  11029. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  11030. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  11031. # OIDC routes that must be reachable without a JWT
  11032. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  11033. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  11034. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  11035. # Connected apps: the app's server swaps a code for the user's identity,
  11036. # authenticated by its client secret rather than a login token.
  11037. "/api/v1/connect/token",
  11038. # Version check for updates (no sensitive data)
  11039. "/api/v1/updates/version",
  11040. # Metrics endpoint handles its own prometheus_token authentication
  11041. "/api/v1/metrics",
  11042. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  11043. # this BEFORE a JWT is available to pick up the firstboot wizard's
  11044. # hostname / timezone / locale and the chrony NTP-gate state. The
  11045. # response contains user-set defaults and a public sync flag — no
  11046. # secrets. Without this entry the global auth middleware returns 401
  11047. # before the route handler runs, regardless of the route's own
  11048. # "no auth required" intent.
  11049. "/api/v1/system/appliance",
  11050. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  11051. # authenticates with a long-lived ``camwall``-scoped token in the query
  11052. # string — exactly like the camera streams two lists below, and for the same
  11053. # reason (no header to put a JWT in). "Public" here only means the middleware
  11054. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  11055. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  11056. # plain ``camera_stream`` token does NOT open this door.
  11057. "/api/v1/camwall/printers",
  11058. # Overlay branding: the route enforces overlay-scoped token authentication.
  11059. "/api/v1/overlay-branding/logo",
  11060. }
  11061. # Route prefixes that are public (for routes with dynamic segments)
  11062. PUBLIC_API_PREFIXES = [
  11063. # WebSocket connections handle their own auth
  11064. "/api/v1/ws",
  11065. # OIDC authorize redirects — include provider_id in path
  11066. "/api/v1/auth/oidc/authorize/",
  11067. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  11068. # a phone with no session, so no header can carry a JWT — the single-use
  11069. # capability token in the path IS the credential (same reasoning as the
  11070. # /dl/ slicer downloads below). The route grants nothing beyond writing
  11071. # good/reject on the one archive the token was minted for.
  11072. "/api/v1/archives/confirm/",
  11073. ]
  11074. # Route patterns that are public (read-only display data)
  11075. # These are checked with "in path" - needed because browsers load images/videos
  11076. # via <img src> and <video src> which don't include Authorization headers
  11077. PUBLIC_API_PATTERNS = [
  11078. # Thumbnails
  11079. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  11080. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  11081. # Images and media
  11082. "/photos/", # /archives/{id}/photos/{filename}
  11083. "/project-image/", # /archives/{id}/project-image/{path}
  11084. "/qrcode", # /archives/{id}/qrcode
  11085. "/timelapse", # /archives/{id}/timelapse (video)
  11086. "/cover", # /printers/{id}/cover
  11087. "/icon", # /external-links/{id}/icon
  11088. # Camera (streams loaded via <img> tag)
  11089. "/camera/stream", # /printers/{id}/camera/stream
  11090. "/camera/snapshot", # /printers/{id}/camera/snapshot
  11091. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  11092. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  11093. # string (same reasoning as the camera streams above — no header to carry a
  11094. # JWT). "Public" only means the middleware steps aside; the route still runs
  11095. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  11096. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  11097. "/overlay-status", # /printers/{id}/overlay-status
  11098. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  11099. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  11100. # download token in the URL path instead.
  11101. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  11102. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  11103. # and these patterns match by substring. Without its own entry the middleware
  11104. # 401s the slicer's header-less request before the route's token check runs,
  11105. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  11106. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  11107. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  11108. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  11109. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  11110. ]
  11111. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  11112. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  11113. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  11114. Format: comma-separated list of ``scheme://host[:port]`` origins.
  11115. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  11116. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  11117. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  11118. Invalid entries are dropped with a warning rather than failing startup, so
  11119. a typo in one origin doesn't take the whole deployment down.
  11120. """
  11121. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  11122. if not raw:
  11123. return ()
  11124. valid: list[str] = []
  11125. for item in raw.split(","):
  11126. candidate = item.strip()
  11127. if not candidate:
  11128. continue
  11129. try:
  11130. parsed = urlparse(candidate)
  11131. except ValueError as e:
  11132. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  11133. continue
  11134. if parsed.scheme not in ("http", "https"):
  11135. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  11136. continue
  11137. if not parsed.netloc:
  11138. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  11139. continue
  11140. if parsed.path and parsed.path != "/":
  11141. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  11142. continue
  11143. if parsed.query or parsed.fragment:
  11144. _security_headers_logger.warning(
  11145. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  11146. )
  11147. continue
  11148. if "*" in parsed.netloc:
  11149. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  11150. continue
  11151. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  11152. if valid:
  11153. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  11154. return tuple(valid)
  11155. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  11156. def _frame_ancestors(default_value: str) -> str:
  11157. """Compose the ``frame-ancestors`` CSP directive (#1191).
  11158. ``default_value`` is the strict directive used when the operator has not
  11159. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  11160. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  11161. Settings URL builder's preview). When trusted origins
  11162. are configured, ``'self'`` is always included so same-origin embedding never
  11163. breaks even if an operator forgets to add their own origin to the list.
  11164. """
  11165. if _TRUSTED_FRAME_ORIGINS:
  11166. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  11167. return f"frame-ancestors {default_value};"
  11168. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  11169. # patterns are anchored on the exact emitted name so the relaxed policies
  11170. # below can never apply to any other asset.
  11171. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  11172. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  11173. # -> /assets/pdf.worker.min-<hash>.js
  11174. # Vite also emits a one-line chunk under the second name that only exports the
  11175. # worker's URL. The page imports it as a module, and a module script is run
  11176. # under the importing document's policy, never its own response's, so it
  11177. # matching as well changes nothing.
  11178. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  11179. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  11180. @app.middleware("http")
  11181. async def security_headers_middleware(request, call_next):
  11182. """Add standard HTTP security headers to every response."""
  11183. # Per-request nonce stamped into `script-src` (#1460). On its own this
  11184. # changes nothing for Bambuddy's own pages — index.html has no inline
  11185. # scripts since the SW registration moved to /sw-register.js. The reason
  11186. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  11187. # script injected into the HTML on the edge, with a fresh hash on every
  11188. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  11189. # it clones the same nonce onto its injected <script>, and the inline
  11190. # script passes the policy without us needing 'unsafe-inline'. See
  11191. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  11192. csp_nonce = secrets.token_urlsafe(16)
  11193. # Routes that render their own HTML need it too, or their inline script is
  11194. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  11195. # one that does: it submits its own form so a verdict still costs one tap.
  11196. request.state.csp_nonce = csp_nonce
  11197. response = await call_next(request)
  11198. response.headers["X-Content-Type-Options"] = "nosniff"
  11199. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  11200. # browsers honour CSP frame-ancestors instead, and the legacy
  11201. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  11202. # When operators have explicitly allowlisted trusted frame origins (#1191
  11203. # — typically Home Assistant on a different port), drop X-Frame-Options
  11204. # and let the CSP-side frame-ancestors directive govern embedding.
  11205. if not _TRUSTED_FRAME_ORIGINS:
  11206. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  11207. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  11208. # Content-Security-Policy for the React SPA.
  11209. # Notes:
  11210. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  11211. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  11212. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  11213. # - media-src blob:: timelapse video player uses Blob URLs.
  11214. # - font-src data:: some icon fonts are embedded as data URIs.
  11215. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  11216. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  11217. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  11218. # default CSP would render a blank page.
  11219. response.headers["Content-Security-Policy"] = (
  11220. "default-src 'self'; "
  11221. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  11222. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  11223. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  11224. "connect-src 'self'; "
  11225. "font-src 'self' data: https://fonts.gstatic.com; "
  11226. "worker-src 'self' blob:; "
  11227. "object-src 'none'; "
  11228. "base-uri 'self'; " + _frame_ancestors("'none'")
  11229. )
  11230. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  11231. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  11232. # its emscripten/embind glue generates invoker functions with `new
  11233. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  11234. # worker is governed by the policy delivered with the WORKER SCRIPT's
  11235. # own response — not the document's — so relaxing it here confines
  11236. # eval to that DOM-less worker context. The document policy below
  11237. # stays nonce-strict, and this response header has no effect when the
  11238. # file is merely fetched (a fetch's CSP is enforced against the
  11239. # requesting document, not the resource's own headers).
  11240. response.headers["Content-Security-Policy"] = (
  11241. "default-src 'self'; "
  11242. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  11243. "connect-src 'self'; "
  11244. "object-src 'none'; "
  11245. "base-uri 'self'; " + _frame_ancestors("'none'")
  11246. )
  11247. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  11248. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  11249. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  11250. # rule as the STEP worker above: the policy that governs a dedicated
  11251. # worker is the one delivered with its own script, so the wasm compile
  11252. # has to be permitted here rather than on the document. Unlike the STEP
  11253. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  11254. response.headers["Content-Security-Policy"] = (
  11255. "default-src 'self'; "
  11256. "script-src 'self' 'wasm-unsafe-eval'; "
  11257. "connect-src 'self'; "
  11258. "object-src 'none'; "
  11259. "base-uri 'self'; " + _frame_ancestors("'none'")
  11260. )
  11261. else:
  11262. # The streaming overlay is embedded same-origin by the URL builder's
  11263. # preview in Settings (#1422), so this branch allows 'self'.
  11264. # Embedding from anywhere else is still refused: 'self'
  11265. # only permits a framer on this origin, which is Bambuddy's own UI, so
  11266. # a clickjacking page on another host is blocked exactly as before.
  11267. # (The overlay draws status over a camera feed and its only interactive
  11268. # element is the logo link, so there is nothing to bait a click into
  11269. # even from a same-origin framer.) Cross-origin embedding of the
  11270. # overlay — Home Assistant on another port — remains what
  11271. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  11272. # allowlist in.
  11273. #
  11274. # The connected-app consent page (/connect/authorize) gets the same
  11275. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  11276. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  11277. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  11278. # requires every ancestor to be this origin, so a foreign page -- a
  11279. # sidebar link's site included -- still cannot frame the consent
  11280. # screen to bait a click.
  11281. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  11282. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  11283. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  11284. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  11285. # the policy served with their own script, so each gets it in its own
  11286. # branch above and the document policy stays as strict as it was.
  11287. response.headers["Content-Security-Policy"] = (
  11288. "default-src 'self'; "
  11289. f"script-src 'self' 'nonce-{csp_nonce}'; "
  11290. "style-src 'self' 'unsafe-inline'; "
  11291. "img-src 'self' data: blob:; "
  11292. "media-src 'self' blob:; "
  11293. "connect-src 'self' ws: wss:; "
  11294. "font-src 'self' data:; "
  11295. "object-src 'none'; "
  11296. "base-uri 'self'; "
  11297. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  11298. )
  11299. if request.url.scheme == "https":
  11300. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  11301. return response
  11302. @app.middleware("http")
  11303. async def auth_middleware(request, call_next):
  11304. """Enforce authentication on all API routes when auth is enabled.
  11305. This middleware provides defense-in-depth by checking auth at the API gateway level,
  11306. regardless of whether individual routes have auth dependencies.
  11307. """
  11308. from starlette.responses import JSONResponse
  11309. path = request.url.path
  11310. # Only apply to API routes
  11311. if not path.startswith("/api/"):
  11312. return await call_next(request)
  11313. # Allow public routes
  11314. if path in PUBLIC_API_ROUTES:
  11315. return await call_next(request)
  11316. # Allow public prefixes
  11317. for prefix in PUBLIC_API_PREFIXES:
  11318. if path.startswith(prefix):
  11319. return await call_next(request)
  11320. # Allow public patterns (read-only display data like thumbnails)
  11321. for pattern in PUBLIC_API_PATTERNS:
  11322. if pattern in path:
  11323. return await call_next(request)
  11324. # Check if auth is enabled. Fail CLOSED on any exception during the
  11325. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  11326. # an attacker who could force a DB exception (e.g. file-descriptor
  11327. # exhaustion via login flood) bypass auth on every protected endpoint.
  11328. # Only the probe is guarded: the request itself runs outside the try, so an
  11329. # error in a route surfaces as the 500 it is rather than as an auth outage.
  11330. try:
  11331. async with async_session() as db:
  11332. from backend.app.core.auth import is_auth_enabled
  11333. auth_enabled = await is_auth_enabled(db)
  11334. except Exception:
  11335. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  11336. return JSONResponse(
  11337. status_code=503,
  11338. content={"detail": "Authentication service temporarily unavailable"},
  11339. )
  11340. if not auth_enabled:
  11341. # Auth disabled, allow all requests
  11342. return await call_next(request)
  11343. # Auth is enabled - require valid token
  11344. auth_header = request.headers.get("Authorization")
  11345. x_api_key = request.headers.get("X-API-Key")
  11346. # Check for API key auth first
  11347. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  11348. # API key authentication - let the request through to be validated by route handler
  11349. # API keys are validated per-route since they have different permission levels
  11350. return await call_next(request)
  11351. # Check for JWT auth
  11352. if not auth_header or not auth_header.startswith("Bearer "):
  11353. return JSONResponse(
  11354. status_code=401,
  11355. content={"detail": "Authentication required"},
  11356. headers={"WWW-Authenticate": "Bearer"},
  11357. )
  11358. # Validate JWT token
  11359. import jwt
  11360. try:
  11361. from backend.app.core.auth import (
  11362. ALGORITHM,
  11363. SECRET_KEY,
  11364. _is_token_fresh,
  11365. get_user_by_username,
  11366. is_jti_revoked,
  11367. )
  11368. token = auth_header.replace("Bearer ", "")
  11369. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  11370. username = payload.get("sub")
  11371. if not username:
  11372. raise ValueError("No username in token")
  11373. jti = payload.get("jti")
  11374. if not jti:
  11375. raise ValueError("No jti in token")
  11376. iat = payload.get("iat")
  11377. # Verify user exists, is active, and token is still fresh (L-R8-A).
  11378. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  11379. # this session so the gateway adds a single pooled checkout, not two (#2572).
  11380. async with async_session() as db:
  11381. if await is_jti_revoked(jti, db):
  11382. return JSONResponse(
  11383. status_code=401,
  11384. content={"detail": "Token has been revoked"},
  11385. headers={"WWW-Authenticate": "Bearer"},
  11386. )
  11387. user = await get_user_by_username(db, username)
  11388. if not user or not user.is_active:
  11389. return JSONResponse(
  11390. status_code=401,
  11391. content={"detail": "User not found or inactive"},
  11392. headers={"WWW-Authenticate": "Bearer"},
  11393. )
  11394. if not _is_token_fresh(iat, user):
  11395. return JSONResponse(
  11396. status_code=401,
  11397. content={"detail": "Token no longer valid"},
  11398. headers={"WWW-Authenticate": "Bearer"},
  11399. )
  11400. except jwt.ExpiredSignatureError:
  11401. return JSONResponse(
  11402. status_code=401,
  11403. content={"detail": "Token has expired"},
  11404. headers={"WWW-Authenticate": "Bearer"},
  11405. )
  11406. except (jwt.InvalidTokenError, ValueError):
  11407. return JSONResponse(
  11408. status_code=401,
  11409. content={"detail": "Invalid token"},
  11410. headers={"WWW-Authenticate": "Bearer"},
  11411. )
  11412. except Exception:
  11413. # Not a bad token but a failure checking it (database, pool): refuse,
  11414. # as for the probe above, rather than answer 401 -- the frontend reads
  11415. # a 401 from /auth/me as final and signs the user out.
  11416. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  11417. return JSONResponse(
  11418. status_code=503,
  11419. content={"detail": "Authentication service temporarily unavailable"},
  11420. )
  11421. return await call_next(request)
  11422. @app.middleware("http")
  11423. async def trace_id_middleware(request, call_next):
  11424. """Stamp every HTTP request with a trace ID and echo it back.
  11425. Decorated AFTER auth_middleware on purpose: Starlette stacks
  11426. @app.middleware decorators LIFO, so the last-decorated runs first
  11427. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  11428. which means auth-middleware log lines (and every line emitted on the
  11429. way down to and back from the route handler) all carry the same
  11430. trace ID. If we put it before auth, auth's logs would be stamped
  11431. with the *previous* request's ID — useless for correlation.
  11432. Honours an inbound ``X-Trace-Id`` header so callers running their
  11433. own tracing can correlate their span IDs with our log lines, but
  11434. only if the value passes the whitelist gate in
  11435. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  11436. rejected (too long, contains control chars, etc.) silently triggers
  11437. a freshly minted server-side ID rather than failing the request.
  11438. The minted (or echoed) ID is set on a ContextVar so that every log
  11439. record emitted during the request — application logs *and* uvicorn's
  11440. access log — carries it via TraceIDFilter, and is also written to
  11441. the ``X-Trace-Id`` response header so clients can pin a server-side
  11442. log search to the exact request they made.
  11443. """
  11444. from backend.app.core.trace import (
  11445. generate_trace_id,
  11446. normalise_inbound_trace_id,
  11447. trace_id_var,
  11448. )
  11449. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  11450. trace_id = inbound if inbound is not None else generate_trace_id()
  11451. token = trace_id_var.set(trace_id)
  11452. try:
  11453. response = await call_next(request)
  11454. finally:
  11455. # Reset the ContextVar so a record emitted in a totally
  11456. # unrelated background task that just happens to inherit this
  11457. # context doesn't keep referencing this request's ID forever.
  11458. # In practice ContextVar.reset is best-effort under asyncio
  11459. # task-spawn semantics, but the cost is one attribute write so
  11460. # we may as well do it.
  11461. trace_id_var.reset(token)
  11462. response.headers["X-Trace-Id"] = trace_id
  11463. return response
  11464. # API routes
  11465. app.include_router(auth.router, prefix=app_settings.api_prefix)
  11466. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  11467. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  11468. app.include_router(users.router, prefix=app_settings.api_prefix)
  11469. app.include_router(groups.router, prefix=app_settings.api_prefix)
  11470. app.include_router(printers.router, prefix=app_settings.api_prefix)
  11471. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  11472. app.include_router(archives.router, prefix=app_settings.api_prefix)
  11473. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  11474. app.include_router(finance.router, prefix=app_settings.api_prefix)
  11475. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  11476. app.include_router(labels.router, prefix=app_settings.api_prefix)
  11477. app.include_router(label_templates.router, prefix=app_settings.api_prefix)
  11478. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  11479. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  11480. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  11481. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  11482. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  11483. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  11484. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  11485. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  11486. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  11487. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  11488. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  11489. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  11490. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  11491. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  11492. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  11493. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  11494. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  11495. app.include_router(updates.router, prefix=app_settings.api_prefix)
  11496. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  11497. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  11498. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  11499. app.include_router(camera.router, prefix=app_settings.api_prefix)
  11500. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  11501. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  11502. app.include_router(projects.router, prefix=app_settings.api_prefix)
  11503. app.include_router(library.router, prefix=app_settings.api_prefix)
  11504. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  11505. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  11506. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  11507. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  11508. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  11509. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  11510. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  11511. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  11512. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  11513. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  11514. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  11515. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  11516. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  11517. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  11518. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  11519. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  11520. app.include_router(system.router, prefix=app_settings.api_prefix)
  11521. app.include_router(support.router, prefix=app_settings.api_prefix)
  11522. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  11523. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  11524. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  11525. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  11526. app.include_router(bulk.router, prefix=app_settings.api_prefix)
  11527. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  11528. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  11529. app.include_router(obico.router, prefix=app_settings.api_prefix)
  11530. app.include_router(octoeverywhere.router, prefix=app_settings.api_prefix)
  11531. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  11532. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  11533. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  11534. # Serve static files (React build)
  11535. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  11536. # Compressed, and cached for good where Vite hashed the name (#3175).
  11537. app.mount(
  11538. "/assets",
  11539. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  11540. name="assets",
  11541. )
  11542. if (app_settings.static_dir / "img").exists():
  11543. app.mount(
  11544. "/img",
  11545. StaticFiles(directory=app_settings.static_dir / "img"),
  11546. name="img",
  11547. )
  11548. if (app_settings.static_dir / "icons").exists():
  11549. app.mount(
  11550. "/icons",
  11551. StaticFiles(directory=app_settings.static_dir / "icons"),
  11552. name="icons",
  11553. )
  11554. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  11555. # falls through to the SPA catch-all and returns index.html, which the
  11556. # browser's font sanitizer rejects ("downloadable font: rejected by
  11557. # sanitizer").
  11558. if (app_settings.static_dir / "fonts").exists():
  11559. app.mount(
  11560. "/fonts",
  11561. StaticFiles(directory=app_settings.static_dir / "fonts"),
  11562. name="fonts",
  11563. )
  11564. @app.get("/")
  11565. async def serve_frontend():
  11566. """Serve the React frontend."""
  11567. index_file = app_settings.static_dir / "index.html"
  11568. if index_file.exists():
  11569. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11570. return {
  11571. "message": "Bambuddy API",
  11572. "docs": "/docs",
  11573. "frontend": "Build and place React app in /static directory",
  11574. }
  11575. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  11576. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  11577. # forever, but the HTML wrapping it is the only file that knows which hash
  11578. # is current. Without explicit cache-control headers Chromium decides
  11579. # heuristically (typically 10% of the time since Last-Modified) and on
  11580. # long-running kiosks happily serves stale HTML across browser restarts.
  11581. # That stale HTML references an old bundle hash, the old bundle is also
  11582. # in the disk cache, and the user ends up running pre-update JS forever
  11583. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  11584. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  11585. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  11586. @app.get("/health")
  11587. async def health_check():
  11588. """Health check endpoint."""
  11589. return {"status": "healthy"}
  11590. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  11591. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  11592. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  11593. # in deployment debugging. One decorator per method, not api_route(methods=
  11594. # [...]): api_route gives both methods the same OpenAPI operation id.
  11595. @app.get("/manifest.json")
  11596. @app.head("/manifest.json")
  11597. async def serve_manifest():
  11598. """Serve PWA manifest."""
  11599. manifest_file = app_settings.static_dir / "manifest.json"
  11600. if manifest_file.exists():
  11601. return FileResponse(manifest_file, media_type="application/manifest+json")
  11602. return {"error": "Manifest not found"}
  11603. @app.get("/sw.js")
  11604. @app.head("/sw.js")
  11605. async def serve_service_worker():
  11606. """Serve service worker."""
  11607. sw_file = app_settings.static_dir / "sw.js"
  11608. if sw_file.exists():
  11609. return FileResponse(
  11610. sw_file,
  11611. media_type="application/javascript",
  11612. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  11613. )
  11614. return {"error": "Service worker not found"}
  11615. @app.get("/sw-register.js")
  11616. @app.head("/sw-register.js")
  11617. async def serve_sw_register():
  11618. """Serve the service-worker registration bootstrap script.
  11619. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  11620. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  11621. """
  11622. reg_file = app_settings.static_dir / "sw-register.js"
  11623. if reg_file.exists():
  11624. return FileResponse(reg_file, media_type="application/javascript")
  11625. return {"error": "sw-register.js not found"}
  11626. # ── GCode viewer static files ────────────────────────────────────────────────
  11627. # Catch-all route for React Router (must be last)
  11628. @app.get("/{full_path:path}")
  11629. async def serve_spa(full_path: str):
  11630. """Serve React app for client-side routing."""
  11631. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  11632. if full_path.startswith("api/"):
  11633. from fastapi import HTTPException
  11634. raise HTTPException(status_code=404, detail="Not found")
  11635. index_file = app_settings.static_dir / "index.html"
  11636. if index_file.exists():
  11637. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11638. return {"error": "Frontend not built"}