main.py 538 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123
  1. import asyncio
  2. import json
  3. import logging
  4. import math
  5. import os
  6. import posixpath
  7. import re
  8. import secrets
  9. import time
  10. from contextlib import asynccontextmanager
  11. from datetime import datetime, timedelta, timezone
  12. from logging.handlers import RotatingFileHandler
  13. from pathlib import Path, PurePosixPath
  14. from urllib.parse import urlparse
  15. from fastapi import FastAPI
  16. from fastapi.responses import FileResponse
  17. from fastapi.staticfiles import StaticFiles
  18. from sqlalchemy import delete, or_, select, text
  19. from backend.app.api.routes import (
  20. ams_history,
  21. announcements,
  22. api_keys,
  23. archive_purge,
  24. archives,
  25. auth,
  26. bug_report,
  27. camera,
  28. camwall,
  29. cloud,
  30. connected_apps,
  31. discovery,
  32. external_links,
  33. filaments,
  34. finance,
  35. firmware,
  36. github_backup,
  37. groups,
  38. ha_sensors,
  39. inventory,
  40. kprofiles,
  41. labels,
  42. library,
  43. library_tags,
  44. library_trash,
  45. library_variants,
  46. local_backup,
  47. local_presets,
  48. location_ha_sensors,
  49. maintenance,
  50. makerworld,
  51. manyfold,
  52. metrics,
  53. mfa,
  54. notification_templates,
  55. notifications,
  56. obico,
  57. orca_cloud,
  58. overlay_branding,
  59. pending_uploads,
  60. pipeline_runs,
  61. print_log,
  62. print_queue,
  63. printer_locations,
  64. printer_sensor_history,
  65. printers,
  66. projects,
  67. scheduled_dryings,
  68. settings as settings_routes,
  69. slice_jobs,
  70. slicer_pipelines,
  71. slicer_presets,
  72. smart_plugs,
  73. sponsor_prompt,
  74. spoolbuddy,
  75. spoolman,
  76. spoolman_inventory,
  77. support,
  78. system,
  79. updates,
  80. user_notifications,
  81. users,
  82. virtual_printers,
  83. webhook,
  84. websocket,
  85. )
  86. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  87. from backend.app.api.routes.support import init_debug_logging
  88. from backend.app.core.config import APP_VERSION, settings as app_settings
  89. from backend.app.core.database import async_session, engine, init_db
  90. from backend.app.core.static_assets import AssetStaticFiles
  91. from backend.app.core.tasks import spawn_background_task
  92. from backend.app.core.websocket import ws_manager
  93. from backend.app.services import kprofile_drift, print_dispatch_context, slot_unlink_grace
  94. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  95. from backend.app.services.archive_cost_estimate import (
  96. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  97. )
  98. from backend.app.services.archive_purge import archive_purge_service
  99. from backend.app.services.bambu_ftp import (
  100. FileNotOnPrinterError,
  101. cache_3mf_download,
  102. clear_3mf_cache,
  103. download_file_async,
  104. download_file_try_paths_async,
  105. ftps_handshake_blocked,
  106. get_cached_3mf,
  107. get_ftp_retry_settings,
  108. normalize_3mf_name,
  109. with_ftp_retry,
  110. )
  111. from backend.app.services.bambu_mqtt import PrinterState
  112. from backend.app.services.camera_light import camera_light
  113. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  114. from backend.app.services.github_backup import github_backup_service
  115. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  116. from backend.app.services.homeassistant import homeassistant_service
  117. from backend.app.services.library_trash import library_trash_service
  118. from backend.app.services.local_backup import local_backup_service
  119. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  120. from backend.app.services.mqtt_relay import mqtt_relay
  121. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  122. from backend.app.services.notification_service import notification_service
  123. from backend.app.services.obico_detection import obico_detection_service
  124. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  125. from backend.app.services.print_scheduler import scheduler as print_scheduler
  126. from backend.app.services.print_storage import (
  127. REASON_FTP_TRANSFER_FAILED,
  128. REASON_FTPS_COOLOFF,
  129. external_storage_present,
  130. ftp_probe_paths,
  131. print_file_reachable_over_ftp,
  132. )
  133. from backend.app.services.printer_manager import (
  134. init_printer_connections,
  135. parse_plate_id,
  136. printer_manager,
  137. printer_state_to_dict,
  138. resolve_plate_id,
  139. )
  140. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  141. from backend.app.services.slot_nozzle import (
  142. nozzle_diameter_for_extruder,
  143. nozzle_flow_for_extruder,
  144. resolve_slot_nozzle,
  145. )
  146. from backend.app.services.smart_plug_manager import smart_plug_manager
  147. from backend.app.services.spool_assignment_notifications import (
  148. notify_missing_spool_assignments_on_print_start,
  149. )
  150. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  151. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  152. from backend.app.services.spoolman_tracking import (
  153. cleanup_tracking as _cleanup_spoolman_tracking,
  154. report_usage as _report_spoolman_usage,
  155. store_print_data as _store_spoolman_print_data,
  156. )
  157. from backend.app.services.tasmota import tasmota_service
  158. from backend.app.services.telegram_reactions import telegram_reaction_poller
  159. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  160. from backend.app.utils.ams_humidity import ams_humidity_percent
  161. from backend.app.utils.filament_types import printer_filament_type
  162. from backend.app.utils.fts_routing import extruder_for_inlet
  163. from backend.app.utils.local_time import utcnow_naive
  164. from backend.app.utils.print_jobs import is_internal_printer_job
  165. # =============================================================================
  166. # Dependency Check - runs before other imports to give helpful error messages
  167. # =============================================================================
  168. def _start_error_server(missing_packages: list):
  169. """Start a minimal HTTP server to display dependency errors in browser."""
  170. import os
  171. import signal
  172. from http.server import BaseHTTPRequestHandler, HTTPServer
  173. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  174. html = f"""<!DOCTYPE html>
  175. <html>
  176. <head>
  177. <title>Bambuddy - Setup Required</title>
  178. <style>
  179. body {{
  180. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  181. background: #0f172a; color: #e2e8f0;
  182. display: flex; justify-content: center; align-items: center;
  183. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  184. }}
  185. .container {{
  186. background: #1e293b; border-radius: 12px; padding: 40px;
  187. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  188. }}
  189. h1 {{ color: #f87171; margin-bottom: 10px; }}
  190. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  191. .packages {{
  192. background: #0f172a; border-radius: 8px; padding: 20px;
  193. margin: 20px 0; text-align: left;
  194. }}
  195. .packages ul {{ margin: 0; padding-left: 20px; }}
  196. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  197. .command {{
  198. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  199. margin: 15px 0; font-family: monospace; color: #4ade80;
  200. text-align: left; overflow-x: auto;
  201. }}
  202. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  203. </style>
  204. </head>
  205. <body>
  206. <div class="container">
  207. <h1>Setup Required</h1>
  208. <h2>Missing Python packages</h2>
  209. <div class="packages"><ul>{packages_html}</ul></div>
  210. <p>To fix, run this command on your server:</p>
  211. <div class="command">pip install -r requirements.txt</div>
  212. <p>Or if using a virtual environment:</p>
  213. <div class="command">./venv/bin/pip install -r requirements.txt</div>
  214. <p class="note">After installing, restart Bambuddy:<br>
  215. <code>sudo systemctl restart bambuddy</code></p>
  216. </div>
  217. </body>
  218. </html>"""
  219. class ErrorHandler(BaseHTTPRequestHandler):
  220. def do_GET(self):
  221. self.send_response(503)
  222. self.send_header("Content-type", "text/html")
  223. self.end_headers()
  224. self.wfile.write(html.encode())
  225. def log_message(self, format, *args):
  226. print(f"[Error Server] {args[0]}")
  227. port = int(os.environ.get("PORT", 8000))
  228. print(f"\nStarting error server on http://0.0.0.0:{port}")
  229. print("Visit this URL in your browser to see the error details.\n")
  230. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  231. def shutdown(signum, frame):
  232. print("\nShutting down error server...")
  233. raise SystemExit(0)
  234. signal.signal(signal.SIGTERM, shutdown)
  235. signal.signal(signal.SIGINT, shutdown)
  236. server.serve_forever()
  237. def check_dependencies():
  238. """Check that all required packages are installed."""
  239. missing = []
  240. # Map of import name -> package name (for pip install)
  241. required = {
  242. "jwt": "PyJWT",
  243. "fastapi": "fastapi",
  244. "uvicorn": "uvicorn",
  245. "sqlalchemy": "sqlalchemy",
  246. "aiosqlite": "aiosqlite",
  247. "pydantic": "pydantic",
  248. "paho.mqtt": "paho-mqtt",
  249. }
  250. for module, package in required.items():
  251. try:
  252. __import__(module)
  253. except ImportError:
  254. missing.append(package)
  255. if missing:
  256. print("\n" + "=" * 60)
  257. print("ERROR: Missing required Python packages!")
  258. print("=" * 60)
  259. print(f"\nMissing packages: {', '.join(missing)}")
  260. print("\nTo fix, run:")
  261. print(" pip install -r requirements.txt")
  262. print("\nOr if using a virtual environment:")
  263. print(" ./venv/bin/pip install -r requirements.txt")
  264. print("=" * 60 + "\n")
  265. _start_error_server(missing)
  266. check_dependencies()
  267. # =============================================================================
  268. # Import settings first for logging configuration
  269. # Configure logging based on settings
  270. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  271. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  272. log_level = getattr(logging, log_level_str, logging.INFO)
  273. # Trace ID column ([-] when no request scope is active — startup, MQTT
  274. # callbacks, scheduled tasks not chained from a request — so the column
  275. # stays visually aligned and missing values are obvious in grep). See
  276. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  277. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  278. # Create root logger
  279. root_logger = logging.getLogger()
  280. root_logger.setLevel(log_level)
  281. # Trace-ID injection: this filter populates record.trace_id from the
  282. # per-request ContextVar so the format string above can reference it.
  283. # Attached to each HANDLER (not the root logger) because Python's
  284. # logging semantics only invoke a logger's filters on records that
  285. # *originated* at that logger — records propagated up from child
  286. # loggers (every named logger in the app) never trigger root's filter.
  287. # Putting it on the handlers means every record any handler emits gets
  288. # trace_id injected just before the formatter runs, regardless of which
  289. # logger created the record. Without this, the formatter raises
  290. # KeyError on every child-logger record and the record is silently
  291. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  292. # partially" bug we hit. See backend/app/core/trace.py for the
  293. # ContextVar the filter reads.
  294. from backend.app.core.trace import TraceIDFilter
  295. _trace_id_filter = TraceIDFilter()
  296. # Console handler - always enabled
  297. console_handler = logging.StreamHandler()
  298. console_handler.setLevel(log_level)
  299. console_handler.setFormatter(logging.Formatter(log_format))
  300. console_handler.addFilter(_trace_id_filter)
  301. root_logger.addHandler(console_handler)
  302. # File handler - only in production or if explicitly enabled
  303. if app_settings.log_to_file:
  304. log_file = app_settings.log_dir / "bambuddy.log"
  305. file_handler = RotatingFileHandler(
  306. log_file,
  307. maxBytes=app_settings.log_max_bytes,
  308. backupCount=app_settings.log_backup_count,
  309. encoding="utf-8",
  310. )
  311. file_handler.setLevel(log_level)
  312. file_handler.setFormatter(logging.Formatter(log_format))
  313. file_handler.addFilter(_trace_id_filter)
  314. root_logger.addHandler(file_handler)
  315. logging.info("Logging to file: %s", log_file)
  316. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  317. # access logger with propagate=False by default, so without this attach
  318. # there is no on-disk record of which endpoint triggered a server-state
  319. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  320. # for exactly this reason. Filtered to write methods only
  321. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  322. # frontend don't churn the rotation window faster than it's useful.
  323. from backend.app.core.logging_filters import (
  324. CancelledPoolNoiseFilter,
  325. WriteRequestsOnlyFilter,
  326. )
  327. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  328. uvicorn_access_logger.addHandler(file_handler)
  329. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  330. # Uvicorn's access logger has propagate=False (its own default), so the
  331. # root-attached TraceIDFilter never sees these records. Attach a
  332. # second instance directly so HTTP access lines carry the same trace
  333. # ID column as the application logs they correlate with.
  334. uvicorn_access_logger.addFilter(TraceIDFilter())
  335. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  336. # BaseHTTPMiddleware cancelling the inner task scope on client
  337. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  338. # underlying transaction leak; this filter only suppresses the residual
  339. # log records that pre-existing pools still emit during their cleanup.
  340. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  341. # Reduce noise from third-party libraries in production
  342. if not app_settings.debug:
  343. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  344. logging.getLogger("httpcore").setLevel(logging.WARNING)
  345. logging.getLogger("httpx").setLevel(logging.WARNING)
  346. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  347. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  348. # Track active prints: {(printer_id, filename): archive_id}
  349. _active_prints: dict[tuple[int, str], int] = {}
  350. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  351. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  352. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  353. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  354. # instead of running its own grab-now chain when present, so the finish photo
  355. # captures the better-framed pre-bed-drop moment without us having to force
  356. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  357. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  358. #
  359. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  360. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  361. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  362. # bank and the others are not — so the consumer can't tell them apart and
  363. # must not rotate again.
  364. _stage22_finish_frames: dict[int, bytes] = {}
  365. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  366. # `finally` block (whether it captured a frame or not). The consumer in
  367. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  368. # so the FINISH-state fallback path — where moment and completion are dispatched
  369. # back-to-back — doesn't race past the producer with an empty pop, and the
  370. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  371. # grab (Bambu printers allow only one RTSP client at a time).
  372. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  373. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  374. # layer-change and on print-progress advances (#2547) while the model is still
  375. # printing, then consumed by the FINISH-state finish-photo path when the
  376. # dispatcher recorded that it injected End G-code into this print. Bambu
  377. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  378. # plate-swap) has run, so a live grab there would capture the swapped/empty
  379. # plate.
  380. #
  381. # The load-bearing property: both drivers are print telemetry that stops before
  382. # the End G-code executes — no further layer_num increases, and mc_percent
  383. # freezes — so the last banked frame is always the finished print before the
  384. # swap. Anything added as a third driver must hold that same property.
  385. _inprint_frame_bank: dict[int, bytes] = {}
  386. # Monotonic timestamp of the last banked frame per printer — throttles banking
  387. # so tall prints don't add a camera grab on every layer.
  388. _inprint_frame_bank_ts: dict[int, float] = {}
  389. # Minimum seconds between banked frames, except the final object layer which
  390. # always refreshes for the best framing.
  391. _INPRINT_BANK_MIN_INTERVAL = 25.0
  392. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  393. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  394. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  395. # the first connected status update for that connection; transitions back
  396. # to False whenever we observe `state.connected = False` so the next
  397. # reconnect re-arms reconciliation. Keyed by printer_id.
  398. _printer_reconciled_since_connect: dict[int, bool] = {}
  399. # Same edge, same keying, for priming the printer's calibration table exactly
  400. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  401. # is otherwise filled only when someone opens the Profiles page or Configure
  402. # Slot, when a GitHub backup runs, or when the printer happens to answer
  403. # somebody else's query on the report topic. Until then the AMS slot card has
  404. # no K value to show on the printers whose trays carry none of their own
  405. # (#2854 — H2-series report cali_idx and nothing more).
  406. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  407. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  408. # {(printer_id, filename): archive_id}
  409. _expected_prints: dict[tuple[int, str], int] = {}
  410. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  411. # Used by usage tracker to map 3MF slots to physical AMS trays
  412. _print_ams_mappings: dict[int, list[int]] = {}
  413. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  414. _print_cost_center_ids: dict[int, int] = {}
  415. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  416. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  417. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  418. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  419. # for the queue path. Cleared on print completion or TTL eviction.
  420. _print_plate_ids: dict[int, int] = {}
  421. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  422. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  423. _last_progress_milestone: dict[int, int] = {}
  424. # Track whether first layer complete notification has been sent for current print
  425. _first_layer_notified: dict[int, bool] = {}
  426. # Track whether we already sent a kill-switch stop for the current unauthorized print
  427. _unauthorized_print_kill_sent: set[int] = set()
  428. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  429. # lookup briefly so an unknown active print does not query the database on
  430. # every status frame. A short TTL keeps settings changes responsive.
  431. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  432. _kill_switch_setting_cache: tuple[bool, float] | None = None
  433. # Provider notification started when the kill switch stops a print. The later
  434. # MQTT print-complete callback awaits this task and only sends its regular
  435. # provider notification when the immediate attempt failed.
  436. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  437. # HMS faults already notified, with when each was last seen:
  438. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  439. # fault that flickers beside a held notice was forgotten on every gap and
  440. # notified on every return (#3226). The window is long because the measured
  441. # gaps reach 64 s.
  442. _notified_hms_errors: dict[int, dict[str, float]] = {}
  443. _HMS_CLEAR_GRACE_SECONDS = 600.0
  444. # The print state each printer was last seen in, and the faults recorded before
  445. # it last changed, which are forgotten as soon as they are gone (see
  446. # _take_new_hms_faults).
  447. _hms_print_state: dict[int, str] = {}
  448. _hms_forget_when_gone: dict[int, set[str]] = {}
  449. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  450. # Used for snapshot-diff detection at print completion
  451. _timelapse_baselines: dict[int, set[str]] = {}
  452. # Track printers waiting for bed to cool after print completion.
  453. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  454. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  455. _bed_cool_waiters: dict[int, dict] = {}
  456. # Track printers where the user explicitly stopped the print from the queue UI.
  457. # When on_print_complete fires with status "failed" for these printers we treat it
  458. # as "cancelled" (stopped by user) so the correct notification email is sent.
  459. _user_stopped_printers: set[int] = set()
  460. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  461. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  462. # holds the previous observation so we only fire on the True → False edge (a
  463. # False → False repeat doesn't notify; an initial False at startup doesn't
  464. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  465. # holds the per-printer pending asyncio task that fires the notification
  466. # after a debounce window — cancelled if the printer reconnects before the
  467. # window elapses, so transient MQTT blips don't flood the user.
  468. _printer_last_connected: dict[int, bool] = {}
  469. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  470. # Debounce: a printer must stay offline this long before we notify. Sized
  471. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  472. # so a single stale-trigger cooldown isn't enough to fire — only a real
  473. # offline that survives one reconnect attempt notifies.
  474. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  475. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  476. # when status="failed" to label the print's failure_reason in archives.
  477. #
  478. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  479. # which is wrong on two counts:
  480. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  481. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  482. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  483. # the public wiki) as part of its user-cancel sequence. Matching on the module
  484. # alone caused user-cancellations to be archived as "Layer shift" failures.
  485. # We now match by full short code only — anything not in this map leaves
  486. # failure_reason=None rather than guessing.
  487. # Values are the canonical camelCase failure-reason keys, NOT display labels
  488. # (issue #2974). The vocabulary is enforced on writes by
  489. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  490. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  491. # Statistics breakdown. Storing a label here instead put a second spelling of
  492. # the same cause into one column: the Failure Analysis widget groups on the raw
  493. # value, so a print the backend classified and an identical one a user
  494. # classified counted as two different reasons, and the label form could never
  495. # be translated because there was no key for ``t()`` to resolve.
  496. _HMS_FAILURE_REASONS: dict[str, str] = {
  497. # Layer shift / step loss
  498. "0300_4057": "layerShift",
  499. "0300_4068": "layerShift",
  500. "0300_800C": "layerShift",
  501. # Filament runout (printer-side & per-AMS-slot)
  502. "0300_8004": "filamentRunout",
  503. "0700_8011": "filamentRunout",
  504. "0701_8011": "filamentRunout",
  505. "0702_8011": "filamentRunout",
  506. "0703_8011": "filamentRunout",
  507. "0704_8011": "filamentRunout",
  508. "0705_8011": "filamentRunout",
  509. "0706_8011": "filamentRunout",
  510. "0707_8011": "filamentRunout",
  511. "07FF_8011": "filamentRunout",
  512. # Clogged nozzle / extruder
  513. "0300_4006": "cloggedNozzle",
  514. "0300_8016": "cloggedNozzle",
  515. "0300_801C": "cloggedNozzle",
  516. "0700_8003": "cloggedNozzle",
  517. "0700_8007": "cloggedNozzle",
  518. "0700_8013": "cloggedNozzle",
  519. "0701_8003": "cloggedNozzle",
  520. "0701_8007": "cloggedNozzle",
  521. "0701_8013": "cloggedNozzle",
  522. "0702_8003": "cloggedNozzle",
  523. # AI print monitoring — spaghetti / the model coming off the plate.
  524. # `spaghettiDetached` is a key the archive editor already offers for this
  525. # failure mode, not a new one, so a derived reason opens the dropdown on
  526. # that option rather than blank — and survives the next save, which clears
  527. # any value the editor does not recognise.
  528. #
  529. # A module-0x0C row is safe here despite the warning above: that warning is
  530. # about matching on the module alone, and 0C00_8042 is a full short code
  531. # with a documented meaning ("The AI print monitor has detected a spaghetti
  532. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  533. # cannot collide.
  534. #
  535. # 0300_8003's own text ends "before continuing your print", but on an X2D
  536. # it arrives with the print already paused, offering only
  537. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  538. #
  539. # Two neighbours are left out on purpose, so this does not get re-derived:
  540. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  541. # reads as a warning about a print that is still running, not a halt.
  542. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  543. # the waste chute. That is not the print failing.
  544. #
  545. # That line is drawn from the text, not from `severity`, because severity
  546. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  547. # module/error word with no level in it, and bambu_mqtt.py gives every
  548. # print_error entry a flat severity=3. Matching on the short code alone is
  549. # the right shape for derive_failure_reason, not an omission.
  550. "0300_8003": "spaghettiDetached",
  551. "0C00_8042": "spaghettiDetached",
  552. }
  553. def _hms_short_code(attr: int, code: int | str) -> str:
  554. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  555. if isinstance(code, str):
  556. code_int = int(code.replace("0x", ""), 16) if code else 0
  557. else:
  558. code_int = int(code or 0)
  559. attr_int = int(attr or 0)
  560. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  561. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  562. """Derive the failure_reason key for an archived print.
  563. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  564. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  565. no HMS code matches (don't guess — null is honest). The keys are the
  566. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  567. translated at render time.
  568. """
  569. if status in ("aborted", "cancelled"):
  570. return "userCancelled"
  571. if status != "failed":
  572. return None
  573. for err in hms_errors or []:
  574. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  575. if short_code in _HMS_FAILURE_REASONS:
  576. return _HMS_FAILURE_REASONS[short_code]
  577. return None
  578. # Track created_by_id for expected prints so the user email can be sent even when
  579. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  580. # {(printer_id, filename): created_by_id}
  581. _expected_print_creators: dict[tuple[int, str], int] = {}
  582. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  583. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  584. # updates for the same printer in quick succession (~30 ms apart, observed in
  585. # the wild on H2D + dual AMS).
  586. #
  587. # Without this serialisation, two concurrent on_ams_change callbacks each read
  588. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  589. # the second commit hits
  590. # IntegrityError: duplicate key value violates unique constraint
  591. # "spool_assignment_printer_id_ams_id_tray_id_key"
  592. # SQLite's WAL serial-write semantics had been silently swallowing the race
  593. # until optional Postgres support landed (asyncpg allows true concurrent
  594. # transactions and surfaces the constraint violation).
  595. #
  596. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  597. # assign) are inside the lock. The Spoolman sync block further down stays
  598. # concurrent because it's network-bound and idempotent.
  599. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  600. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  601. """Return the per-printer assignment lock, creating it on first use."""
  602. lock = _ams_assignment_locks.get(printer_id)
  603. if lock is None:
  604. lock = asyncio.Lock()
  605. _ams_assignment_locks[printer_id] = lock
  606. return lock
  607. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  608. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  609. # tag tuple changes for the slot. Cleared when the slot is reported empty
  610. # so remove + reinsert reliably re-prompts the UI.
  611. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  612. async def _broadcast_unknown_tag(
  613. *,
  614. printer_id: int,
  615. ams_id: int,
  616. tray_id: int,
  617. tag_uid: str,
  618. tray_uuid: str,
  619. tray_type: str | None = None,
  620. tray_color: str | None = None,
  621. tray_sub_brands: str | None = None,
  622. tray_count: int | None = None,
  623. ) -> None:
  624. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  625. _logger = logging.getLogger(__name__)
  626. slot_key = (ams_id, tray_id)
  627. tag_key = (tag_uid or "", tray_uuid or "")
  628. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  629. if per_printer.get(slot_key) == tag_key:
  630. _logger.debug(
  631. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  632. printer_id,
  633. ams_id,
  634. tray_id,
  635. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  636. )
  637. return
  638. _logger.info(
  639. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  640. printer_id,
  641. ams_id,
  642. tray_id,
  643. tray_type,
  644. tray_color,
  645. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  646. )
  647. # Broadcast first; only commit the dedup if the WS write succeeds.
  648. # If broadcast raises, the next MQTT push retries instead of being
  649. # permanently silenced by a poisoned dedup entry.
  650. await ws_manager.broadcast(
  651. {
  652. "type": "unknown_tag",
  653. "printer_id": printer_id,
  654. "ams_id": ams_id,
  655. "tray_id": tray_id,
  656. "tag_uid": tag_uid,
  657. "tray_uuid": tray_uuid,
  658. "tray_type": tray_type,
  659. "tray_color": tray_color,
  660. "tray_sub_brands": tray_sub_brands,
  661. "tray_count": tray_count,
  662. }
  663. )
  664. per_printer[slot_key] = tag_key
  665. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  666. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  667. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  668. if per_printer is None:
  669. return
  670. per_printer.pop((ams_id, tray_id), None)
  671. # TTL for expected-print entries: evict registrations older than this to prevent
  672. # unbounded growth when a print is registered but never starts (e.g. printer
  673. # disconnect, app restart, print started from the printer panel).
  674. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  675. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  676. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  677. # Cleanup loop interval
  678. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  679. _expected_prints_cleanup_task: asyncio.Task | None = None
  680. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  681. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  682. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  683. possible_keys: list[tuple[int, str]] = []
  684. filename = (state.gcode_file or state.current_print or "").strip()
  685. subtask_name = (state.subtask_name or "").strip()
  686. if subtask_name:
  687. possible_keys.append((printer_id, subtask_name))
  688. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  689. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  690. if filename:
  691. base_name = filename.rsplit("/", 1)[-1]
  692. if base_name.endswith(".gcode.3mf"):
  693. root_name = base_name[: -len(".gcode.3mf")]
  694. possible_keys.append((printer_id, root_name))
  695. possible_keys.append((printer_id, base_name))
  696. possible_keys.append((printer_id, f"{root_name}.gcode"))
  697. possible_keys.append((printer_id, f"{root_name}.3mf"))
  698. elif base_name.endswith(".3mf"):
  699. root_name = base_name[: -len(".3mf")]
  700. possible_keys.append((printer_id, root_name))
  701. possible_keys.append((printer_id, base_name))
  702. elif base_name.endswith(".gcode"):
  703. root_name = base_name[: -len(".gcode")]
  704. possible_keys.append((printer_id, root_name))
  705. possible_keys.append((printer_id, f"{root_name}.3mf"))
  706. possible_keys.append((printer_id, base_name))
  707. else:
  708. possible_keys.append((printer_id, base_name))
  709. possible_keys.append((printer_id, f"{base_name}.3mf"))
  710. return possible_keys
  711. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  712. """Check the cheap, process-local print ownership signals."""
  713. if printer_manager.get_current_print_user(printer_id):
  714. return True
  715. return any(key in _expected_prints or key in _active_prints for key in _build_status_print_keys(printer_id, state))
  716. async def _is_printer_kill_switch_enabled_cached() -> bool:
  717. """Return the kill-switch setting without querying on every MQTT frame."""
  718. global _kill_switch_setting_cache
  719. now = time.monotonic()
  720. if _kill_switch_setting_cache is not None:
  721. enabled, expires_at = _kill_switch_setting_cache
  722. if now < expires_at:
  723. return enabled
  724. async with async_session() as db:
  725. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  726. enabled = await is_printer_kill_switch_enabled(db)
  727. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  728. return enabled
  729. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  730. """Resolve whether the current print was started by Bambuddy.
  731. ``None`` means identity is not yet safe to decide. The kill switch must
  732. defer in that case: stopping a print is irreversible, and the first status
  733. frames after a restart may arrive before all subtask fields are populated.
  734. """
  735. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  736. return True
  737. possible_keys = _build_status_print_keys(printer_id, state)
  738. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  739. # is on disk. subtask_id is minted per print and pins the answer to the job
  740. # actually running, rather than to an unrelated one that reuses a filename.
  741. raw_subtask_id = getattr(state, "subtask_id", None)
  742. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  743. if subtask_id in ("", "0"):
  744. return None
  745. from backend.app.models.archive import PrintArchive
  746. result = await db.execute(
  747. select(PrintArchive)
  748. .where(
  749. PrintArchive.printer_id == printer_id,
  750. PrintArchive.status == "printing",
  751. PrintArchive.subtask_id == subtask_id,
  752. )
  753. .order_by(PrintArchive.created_at.desc())
  754. .limit(1)
  755. )
  756. archive = result.scalar_one_or_none()
  757. # An archive row on its own proves nothing: `on_print_start` archives every
  758. # print it observes, including ones started from Bambu Studio or Handy, and
  759. # stamps them with the same status and subtask_id. Authorizing on its mere
  760. # existence would disable the kill switch the moment the 3MF finishes
  761. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  762. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  763. # (carried over from the queue item that started it).
  764. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  765. # Rehydrate the fast in-memory path for subsequent status frames. Include
  766. # both the archive filename and every normalized key reported by MQTT.
  767. _active_prints[(printer_id, archive.filename)] = archive.id
  768. for key in possible_keys:
  769. _active_prints[key] = archive.id
  770. return True
  771. # No dispatch marker. Before calling this someone else's print, check whether
  772. # Bambuddy has a job of its own running on this printer: a library-file
  773. # dispatch has no archive at send time, and an archive created seconds later
  774. # by `on_print_start` carries neither marker. The queue row, which the
  775. # scheduler commits to status="printing" before the MQTT send, is the one
  776. # durable record every Bambuddy print has. It cannot be tied to this
  777. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  778. # print is irreversible, and refusing to act costs nothing but a log line.
  779. from backend.app.models.print_queue import PrintQueueItem
  780. dispatched_here = await db.scalar(
  781. select(PrintQueueItem.id)
  782. .where(
  783. PrintQueueItem.printer_id == printer_id,
  784. PrintQueueItem.status == "printing",
  785. )
  786. .limit(1)
  787. )
  788. if dispatched_here is not None:
  789. return None
  790. return False
  791. async def _send_kill_switch_provider_notification(
  792. printer_id: int,
  793. printer_name: str,
  794. data: dict,
  795. ) -> bool:
  796. """Send the immediate print-stopped provider notification.
  797. Returning a success flag lets the normal MQTT completion path retry when
  798. this early notification could not be delivered.
  799. """
  800. logger = logging.getLogger(__name__)
  801. try:
  802. async with async_session() as db:
  803. await notification_service.on_print_complete(
  804. printer_id,
  805. printer_name,
  806. "stopped",
  807. data,
  808. db,
  809. )
  810. return True
  811. except Exception as e:
  812. logger.warning(
  813. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  814. printer_id,
  815. e,
  816. )
  817. return False
  818. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  819. """Wait for an immediate kill-switch notification, if one was scheduled."""
  820. if task is None:
  821. return False
  822. try:
  823. return await task
  824. except Exception as e:
  825. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  826. return False
  827. async def _get_plug_energy(plug, db) -> dict | None:
  828. """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
  829. For HA plugs, configures the service with current settings from DB.
  830. For MQTT plugs, returns data from the subscription service.
  831. For REST plugs, polls the status URL with JSON path extraction.
  832. """
  833. if plug.plug_type == "homeassistant":
  834. from backend.app.api.routes.settings import get_homeassistant_settings
  835. ha_settings = await get_homeassistant_settings(db)
  836. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  837. return await homeassistant_service.get_energy(plug)
  838. elif plug.plug_type == "mqtt":
  839. # MQTT plugs report "today" energy, not lifetime total
  840. # For per-print tracking, we use "today" as the counter (resets at midnight)
  841. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  842. if mqtt_data:
  843. return {
  844. "power": mqtt_data.power,
  845. "today": mqtt_data.energy,
  846. "total": mqtt_data.energy, # Use today as total for per-print calculations
  847. }
  848. return None
  849. elif plug.plug_type == "rest":
  850. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  851. return await rest_smart_plug_service.get_energy(plug)
  852. else:
  853. return await tasmota_service.get_energy(plug)
  854. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  855. """Capture the smart plug lifetime counter on the archive at print start.
  856. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  857. tracking survives a backend restart mid-print. The print-end handler reads
  858. this value back from the DB and computes the delta against the current
  859. plug counter.
  860. """
  861. _logger = logging.getLogger(__name__)
  862. try:
  863. candidates = await energy_plug_candidates(db, printer_id)
  864. if not candidates:
  865. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  866. return False
  867. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  868. if selected is None:
  869. # Naming the plugs matters here: with several linked to one printer
  870. # this is the difference between "the meter is offline" and "you
  871. # linked only accessories" (#2859).
  872. _logger.warning(
  873. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  874. printer_id,
  875. archive.id,
  876. ", ".join(plug.name for plug in candidates),
  877. )
  878. return False
  879. plug, energy = selected
  880. archive.energy_start_kwh = float(energy["total"])
  881. # With the plug's snapshots, what lets the cost follow the price over
  882. # the print rather than take the price at its end (#1251). A price that
  883. # can't be had must not cost the print its energy reading.
  884. archive.energy_start_at = utcnow_naive()
  885. archive.energy_start_plug_id = plug.id
  886. try:
  887. from backend.app.services.energy_price import current_price
  888. archive.energy_start_price = await current_price(db)
  889. except Exception as e:
  890. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  891. archive.energy_start_price = None
  892. await db.commit()
  893. _logger.info(
  894. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  895. f" ({context})" if context else "",
  896. archive.id,
  897. plug.name,
  898. energy["total"],
  899. )
  900. return True
  901. except Exception as e:
  902. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  903. return False
  904. def register_expected_print(
  905. printer_id: int,
  906. filename: str,
  907. archive_id: int,
  908. ams_mapping: list[int] | None = None,
  909. created_by_id: int | None = None,
  910. cost_center_id: int | None = None,
  911. plate_id: int | None = None,
  912. ):
  913. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  914. # Store with multiple filename variations to catch different naming patterns
  915. _expected_prints[(printer_id, filename)] = archive_id
  916. # Also store without .3mf extension if present
  917. if filename.endswith(".3mf"):
  918. base = filename[:-4]
  919. _expected_prints[(printer_id, base)] = archive_id
  920. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  921. # Store AMS mapping for usage tracking at print completion
  922. if ams_mapping is not None:
  923. _print_ams_mappings[archive_id] = ams_mapping
  924. if cost_center_id is not None:
  925. _print_cost_center_ids[archive_id] = cost_center_id
  926. # Store plate_id for usage tracking when this is a single-plate dispatch from
  927. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  928. # file's filament total to the spool instead of just the printed plate (#1697).
  929. if plate_id is not None:
  930. _print_plate_ids[archive_id] = plate_id
  931. # Store created_by_id so the user start email can be sent even when the archive
  932. # itself has no created_by_id (e.g. library-file-based queue prints)
  933. if created_by_id is not None:
  934. _expected_print_creators[(printer_id, filename)] = created_by_id
  935. if filename.endswith(".3mf"):
  936. base = filename[:-4]
  937. _expected_print_creators[(printer_id, base)] = created_by_id
  938. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  939. # Record registration time for TTL-based eviction
  940. _registered_at = time.monotonic()
  941. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  942. if filename.endswith(".3mf"):
  943. base = filename[:-4]
  944. _expected_print_registered_at[(printer_id, base)] = _registered_at
  945. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  946. logging.getLogger(__name__).info(
  947. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  948. )
  949. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  950. """Undo :func:`register_expected_print` when the print never went out.
  951. Registration has to happen *before* the MQTT print command, because the
  952. printer can report the print before the line after the send executes. So
  953. every path that registers and then fails to send — a cancel winning the
  954. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  955. between — leaves an expectation for a print that will never arrive.
  956. The TTL sweep evicts those after two hours, which is far longer than it
  957. takes a user to react to a failed dispatch by pressing print again: that
  958. reprint would be folded into the *old* archive and take the stale
  959. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  960. Mirrors the sweep's rules, including the one that is easy to get wrong:
  961. ``_print_ams_mappings`` / ``_print_plate_ids`` are keyed by archive, not by
  962. file, so they may only be dropped once no live key still points at that
  963. archive.
  964. """
  965. keys = [(printer_id, filename)]
  966. if filename.endswith(".3mf"):
  967. base = filename[:-4]
  968. keys.append((printer_id, base))
  969. keys.append((printer_id, f"{base}.gcode"))
  970. removed = False
  971. for key in keys:
  972. if _expected_prints.pop(key, None) is not None:
  973. removed = True
  974. _expected_print_creators.pop(key, None)
  975. _expected_print_registered_at.pop(key, None)
  976. if archive_id not in set(_expected_prints.values()):
  977. _print_ams_mappings.pop(archive_id, None)
  978. _print_plate_ids.pop(archive_id, None)
  979. if removed:
  980. logging.getLogger(__name__).info(
  981. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  982. printer_id,
  983. filename,
  984. archive_id,
  985. )
  986. def _compute_run_filament_grams(
  987. status: str,
  988. archive_filament_used_grams: float | None,
  989. progress: float | int | None,
  990. usage_results: list[dict] | None,
  991. ) -> float | None:
  992. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  993. Priority for every status:
  994. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  995. weight delta — same source that drives "Total Consumed" on the
  996. Inventory page, so Stats and Inventory totals stay aligned).
  997. 2. For ``completed``: the slicer estimate (no tracker available, fall
  998. back to the canonical "this print used X" value).
  999. 3. For partial statuses: ``estimate * progress%``.
  1000. 4. ``None`` if nothing is known.
  1001. """
  1002. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1003. if tracked_grams > 0:
  1004. return round(tracked_grams, 1)
  1005. if status == "completed":
  1006. return archive_filament_used_grams
  1007. if archive_filament_used_grams:
  1008. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1009. if scale > 0:
  1010. return round(archive_filament_used_grams * scale, 1)
  1011. return None
  1012. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  1013. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1014. stored_ams_mapping = data.get("ams_mapping")
  1015. if not stored_ams_mapping and archive_id:
  1016. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  1017. return stored_ams_mapping
  1018. def _get_start_plate_id(archive_id: int | None) -> int | None:
  1019. """Resolve plate_id for print start without consuming stored direct-Print state.
  1020. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1021. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1022. read it back at print-start without popping (the entry is popped on print
  1023. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1024. """
  1025. if archive_id is None:
  1026. return None
  1027. return _print_plate_ids.get(archive_id)
  1028. def _partial_progress_scale(progress: int | float | None) -> float:
  1029. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1030. Used by every site that multiplies a "would-have-used" slicer estimate
  1031. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1032. so the three sites in ``_background_notifications`` (and the per-plate
  1033. override helper) can't drift apart on the coercion shape.
  1034. """
  1035. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1036. def _scope_notification_archive_data_to_plate(
  1037. archive_data: dict,
  1038. archive_file_path: str | None,
  1039. plate_id: int | None,
  1040. print_status: str,
  1041. progress: int | float | None,
  1042. base_dir: Path,
  1043. ) -> dict:
  1044. """Override summed-across-plates totals in ``archive_data`` with the values
  1045. for ``plate_id`` so the completion notification reports what was actually
  1046. printed, not the whole project (#1785).
  1047. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1048. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1049. the archive card's "whole project" headline, wrong for the completion
  1050. notification of a single-plate print. The queue UI already re-reads the
  1051. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1052. notification payload (filament grams, time estimate, per-slot breakdown).
  1053. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1054. no per-plate values — in every fail case the original ``archive_data`` is
  1055. returned unchanged so the notification still sends.
  1056. """
  1057. if plate_id is None or not archive_file_path:
  1058. return archive_data
  1059. from backend.app.utils.threemf_tools import (
  1060. extract_filament_usage_from_3mf,
  1061. extract_print_time_from_3mf,
  1062. )
  1063. archive_path = base_dir / archive_file_path
  1064. if not archive_path.exists():
  1065. return archive_data
  1066. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1067. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1068. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1069. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1070. if plate_time:
  1071. archive_data["print_time_seconds"] = plate_time
  1072. # Gate both the grams headline AND the per-slot breakdown on the same
  1073. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1074. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1075. # to the project-level grams the archive columns already provide rather
  1076. # than ship a project-level headline next to an all-zero per-plate
  1077. # breakdown.
  1078. if plate_grams > 0:
  1079. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1080. archive_data["filament_slots"] = [
  1081. {
  1082. "slot_id": s.get("slot_id"),
  1083. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1084. "type": s.get("type", ""),
  1085. "color": s.get("color", ""),
  1086. }
  1087. for s in plate_slots
  1088. ]
  1089. return archive_data
  1090. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1091. """Best-effort filament metadata from the MQTT print-start snapshot.
  1092. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1093. file during print, see #1533) so the fallback PrintArchive still has
  1094. enough filament info to support the inventory views and AMS-expansion
  1095. planning the operator opens it for. Returns a dict with optional
  1096. ``filament_type`` and ``filament_color`` keys in the same
  1097. comma-separated format the 3MF extractor produces, so the rest of the
  1098. codebase treats the fallback archive identically to a normal one.
  1099. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1100. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1101. entries). When supplied, only the slots actually consumed by this
  1102. print contribute. Without it the function falls back to every loaded
  1103. AMS slot — less accurate but still useful.
  1104. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1105. that the unit tests pass directly, AND the on_print_start callback
  1106. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1107. bambu_mqtt service hands to main.py at runtime. The original
  1108. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1109. handled the inner shape and silently returned ``{}`` for every real
  1110. print start, leaving fallback archives' filament fields NULL — the
  1111. exact regression the fix was meant to close. Reported with a log
  1112. proving the AMS state was right there at
  1113. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1114. """
  1115. result: dict[str, str] = {}
  1116. # Look at the on_print_start wrapper first, then the inner shape.
  1117. raw_data = (data or {}).get("raw_data")
  1118. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1119. if not isinstance(ams_root, dict):
  1120. ams_root = (data or {}).get("ams") or {}
  1121. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1122. if not isinstance(ams_units, list) or not ams_units:
  1123. return result
  1124. # Map global tray id (unit * 4 + tray) → (type, color).
  1125. loaded: dict[int, tuple[str, str]] = {}
  1126. for unit in ams_units:
  1127. if not isinstance(unit, dict):
  1128. continue
  1129. try:
  1130. unit_id = int(unit.get("id", 0))
  1131. except (TypeError, ValueError):
  1132. continue
  1133. for tray in unit.get("tray") or []:
  1134. if not isinstance(tray, dict):
  1135. continue
  1136. try:
  1137. tray_id = int(tray.get("id", 0))
  1138. except (TypeError, ValueError):
  1139. continue
  1140. ttype = (tray.get("tray_type") or "").strip()
  1141. tcolor = (tray.get("tray_color") or "").strip().upper()
  1142. if not ttype:
  1143. continue # Empty / unloaded slot.
  1144. loaded[unit_id * 4 + tray_id] = (ttype, tcolor)
  1145. if not loaded:
  1146. return result
  1147. if ams_mapping:
  1148. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1149. filaments = [loaded[g] for g in used_ids if g in loaded]
  1150. if not filaments:
  1151. return result # Mapping points entirely at slots we have no data for.
  1152. else:
  1153. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1154. types_joined = ",".join(f[0] for f in filaments)
  1155. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1156. # Column limits per backend/app/models/archive.py: filament_type=50,
  1157. # filament_color=200.
  1158. if types_joined:
  1159. result["filament_type"] = types_joined[:50]
  1160. if colors_joined:
  1161. result["filament_color"] = colors_joined[:200]
  1162. return result
  1163. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1164. """Start a layer-timelapse session for *archive_id* when the printer has
  1165. an external camera configured. Returns True if a session was started.
  1166. Three call sites in on_print_start (expected-archive promotion, fallback
  1167. archive creation, fresh-archive creation) used to inline this same
  1168. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1169. on the first pass). Centralising the conditional + call here makes the
  1170. contract testable in isolation and keeps the three sites locked in step.
  1171. """
  1172. if not (printer.external_camera_enabled and printer.external_camera_url):
  1173. return False
  1174. from backend.app.services.layer_timelapse import start_session
  1175. start_session(
  1176. printer_id,
  1177. archive_id,
  1178. printer.external_camera_url,
  1179. printer.external_camera_type or "mjpeg",
  1180. snapshot_url=printer.external_camera_snapshot_url,
  1181. rotation=getattr(printer, "camera_rotation", 0),
  1182. )
  1183. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1184. return True
  1185. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1186. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1187. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1188. — since #2926 — the description the parser already resolved, which is preferred
  1189. when present so the queue's failure reason reads the same as the status
  1190. response. The short code still produces the bracketed label, and still
  1191. resolves the sentence for a caller whose entries predate the field. An entry
  1192. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1193. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1194. label when no description is on file. Returns None for an empty list so
  1195. callers can leave error_message unset.
  1196. """
  1197. if not hms_errors:
  1198. return None
  1199. from backend.app.services.hms_errors import get_error_description
  1200. parts: list[str] = []
  1201. for err in hms_errors:
  1202. try:
  1203. # `_hms_short_code` rather than a local derivation: this one used to
  1204. # format the error without masking it to 16 bits, so an `hms[]` entry
  1205. # whose code carries an alert-level group produced a five-digit label
  1206. # like "0500_3000A" — not a code the user can look up, and never a
  1207. # catalogue key, so the sentence was lost with it.
  1208. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1209. except (TypeError, ValueError):
  1210. continue
  1211. description = err.get("description") or get_error_description(short_code)
  1212. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1213. # groups and is not a code anyone can look up; its full code in the
  1214. # printer screen's four groups is (#2728).
  1215. full_code = str(err.get("full_code") or "")
  1216. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1217. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1218. return "; ".join(parts) if parts else None
  1219. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1220. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1221. print completes successfully. Gated to status=='completed': failed, cancelled
  1222. and aborted prints do not count as usage. Caller is responsible for committing
  1223. the session. No-op when the queue item has no linked library file (e.g. reprints
  1224. from an archive). See #1008."""
  1225. if queue_status != "completed" or item.library_file_id is None:
  1226. return
  1227. from backend.app.models.library import LibraryFile
  1228. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1229. if lib_file is None:
  1230. return
  1231. lib_file.print_count = (lib_file.print_count or 0) + 1
  1232. lib_file.last_printed_at = datetime.now(timezone.utc)
  1233. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1234. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1235. When on_print_complete fires with status 'failed' for a printer in this set we
  1236. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1237. rather than a 'print failed' notification.
  1238. """
  1239. _user_stopped_printers.add(printer_id)
  1240. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1241. _last_status_broadcast: dict[int, str] = {}
  1242. # Track printers where we've updated nozzle_count
  1243. _nozzle_count_updated: set[int] = set()
  1244. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1245. """Wait the debounce window then fire `on_printer_offline` if the printer
  1246. is still offline.
  1247. Scheduled by `on_printer_status_change` on the connected → disconnected
  1248. edge (#1752). Cancelled by the same handler if the printer reconnects
  1249. before the window elapses, so a single MQTT blip + recovery doesn't
  1250. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1251. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1252. route through the same status-change callback, so this covers both.
  1253. """
  1254. logger = logging.getLogger(__name__)
  1255. try:
  1256. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1257. still_offline = not printer_manager.is_connected(printer_id)
  1258. logger.info(
  1259. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1260. printer_id,
  1261. still_offline,
  1262. )
  1263. if not still_offline:
  1264. return
  1265. async with async_session() as db:
  1266. from backend.app.models.printer import Printer
  1267. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1268. printer = result.scalar_one_or_none()
  1269. if not printer:
  1270. logger.warning(
  1271. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1272. printer_id,
  1273. )
  1274. return
  1275. logger.info(
  1276. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1277. printer_id,
  1278. printer.name,
  1279. )
  1280. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1281. except asyncio.CancelledError:
  1282. raise
  1283. except Exception as e:
  1284. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1285. finally:
  1286. _printer_offline_notify_tasks.pop(printer_id, None)
  1287. def _hms_notify_key(error) -> str:
  1288. """What identifies a fault for notification de-duplication.
  1289. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1290. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1291. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1292. and -0006 together) shared a key and only the first was ever notified. An
  1293. entry without a full code falls back to attr and code together.
  1294. """
  1295. full_code = getattr(error, "full_code", "") or ""
  1296. if full_code:
  1297. return full_code.upper()
  1298. return f"{error.attr:08X}:{error.code}"
  1299. def _hms_fault_counts(error) -> bool:
  1300. """Whether a fault counts as a problem: the same rule the frontend's
  1301. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1302. It counts when Bambu publishes text for it or it offers action buttons, and
  1303. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1304. no actions does not count: those are things like "the top cover is open" or
  1305. "the chamber is hot, fan speed increased", which a printer can hold through
  1306. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1307. it always has; those are prompts such as "unable to start drying" (#2728).
  1308. """
  1309. if error.severity < 1:
  1310. return False
  1311. has_actions = bool(getattr(error, "actions", None))
  1312. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1313. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1314. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1315. """The new faults that count (see ``_hms_fault_counts``).
  1316. These go to the MQTT relay; the caller also needs a description before it
  1317. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1318. used to read ``severity >= 2`` when severity held the part byte; on the real
  1319. level that would drop the task-stopping errors (#2728).
  1320. """
  1321. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1322. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1323. """The faults on this printer not notified yet, and record them as notified.
  1324. Tracking is updated before anything is sent, so concurrent status callbacks
  1325. cannot notify the same fault twice. A notified fault is forgotten once it
  1326. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1327. and on is notified once (#3226), while one that clears and comes back much
  1328. later is notified again.
  1329. When ``print_state`` changes (a print resumed, started or finished), every
  1330. fault recorded so far is forgotten the first time it is gone, without the
  1331. wait: a runout fixed before resuming must be notified if it happens again a
  1332. few minutes later, while the printer sits paused. Not only the faults gone
  1333. at the change itself, because the update that flips the state can still
  1334. carry the old fault (a ``print_error`` entry stays until a payload brings
  1335. ``hms``).
  1336. """
  1337. now = time.time()
  1338. current = {_hms_notify_key(e) for e in errors}
  1339. seen = _notified_hms_errors.setdefault(printer_id, {})
  1340. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1341. if print_state is not None:
  1342. print_state = print_state.upper()
  1343. if _hms_print_state.get(printer_id, print_state) != print_state:
  1344. forget_when_gone.update(seen)
  1345. _hms_print_state[printer_id] = print_state
  1346. for key, last_seen in list(seen.items()):
  1347. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1348. del seen[key]
  1349. forget_when_gone.discard(key)
  1350. new = current - seen.keys()
  1351. for key in current:
  1352. seen[key] = now
  1353. if not seen:
  1354. _notified_hms_errors.pop(printer_id, None)
  1355. if not forget_when_gone:
  1356. _hms_forget_when_gone.pop(printer_id, None)
  1357. return _hms_errors_to_notify(errors, new)
  1358. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1359. # "Printing", -1 and 255 are "no stage" (#3211).
  1360. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1361. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1362. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1363. Records it as notified. Called only for a printing state with progress above 0.
  1364. Progress before the first layer is not progress through the print (#3211).
  1365. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1366. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1367. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1368. 75% notification together with Print Started, and since 75 was then on
  1369. record, 25 and 50 could never fire. So nothing counts while the printer
  1370. reports a layer count but has not started layer 1.
  1371. Without a layer count -- a print whose first frame carried no
  1372. ``total_layer_num``, until the pushall that asks for it is answered
  1373. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1374. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1375. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1376. reports neither keeps the old behaviour rather than never notifying.
  1377. """
  1378. if (state.layer_num or 0) < 1:
  1379. if (state.total_layers or 0) > 0:
  1380. return None
  1381. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1382. return None
  1383. progress = state.progress or 0
  1384. current_milestone = 0
  1385. if progress >= 75:
  1386. current_milestone = 75
  1387. elif progress >= 50:
  1388. current_milestone = 50
  1389. elif progress >= 25:
  1390. current_milestone = 25
  1391. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1392. _last_progress_milestone[printer_id] = current_milestone
  1393. return current_milestone
  1394. return None
  1395. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1396. """Handle printer status changes - broadcast via WebSocket."""
  1397. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1398. # transitions disconnected → connected — which covers both Bambuddy
  1399. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1400. # `reconcile_stale_active_prints` exactly once for this connection so
  1401. # any archive still in `status="printing"` that can't actually be
  1402. # running anymore (printer IDLE / different subtask / empty subtask)
  1403. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1404. # finished during a disconnect window + a smart-plug power cycle
  1405. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1406. # next boot. Reconciliation runs concurrently — it must not block the
  1407. # WebSocket dedup / broadcast logic below, and the connected edge is
  1408. # marked True BEFORE the await so concurrent status updates inside
  1409. # the same connection don't re-trigger reconciliation.
  1410. #
  1411. # Wait for a real push_status before reconciling (#1679): MQTT
  1412. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1413. # the connection, BEFORE `_request_push_all` round-trips. At that
  1414. # instant the `PrinterState` is still on construction defaults — most
  1415. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1416. # If reconcile spawns here, every in-flight archive falls through to
  1417. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1418. # creates a duplicate archive on the real PRINT COMPLETE and
  1419. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1420. # keeps the #1542 mechanism intact: once the first real push_status
  1421. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1422. # fires again with the flag still False — reconcile then runs against
  1423. # actual evidence.
  1424. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1425. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1426. _printer_reconciled_since_connect[printer_id] = True
  1427. spawn_background_task(
  1428. reconcile_stale_active_prints(printer_id),
  1429. name=f"reconcile-stale-prints-{printer_id}",
  1430. )
  1431. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1432. # Re-arm so the next reconnect triggers reconciliation again.
  1433. _printer_reconciled_since_connect[printer_id] = False
  1434. # Same edge, for the calibration table the AMS card reads its K values from.
  1435. #
  1436. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1437. # tables to ask for. A `state_known` gate alone is not enough: the first
  1438. # real push_status is what makes the state known, and the nozzle fields do
  1439. # not always arrive in it. Latching there would spend this connection's one
  1440. # attempt on a printer that could not yet say what was fitted.
  1441. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1442. if (
  1443. state.connected
  1444. and state_known
  1445. and nozzle_known
  1446. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1447. ):
  1448. _printer_kprofiles_primed_since_connect[printer_id] = True
  1449. spawn_background_task(
  1450. prime_kprofile_table(printer_id),
  1451. name=f"prime-kprofiles-{printer_id}",
  1452. )
  1453. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1454. _printer_kprofiles_primed_since_connect[printer_id] = False
  1455. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1456. # else in the AMS report changing -- a power cycle does it to every slot --
  1457. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1458. # while the printer is idle; needs_check is cheap and throttled per slot.
  1459. # Guarded: nothing here may stop the status broadcast below.
  1460. try:
  1461. if not state.connected:
  1462. kprofile_drift.forget_printer(printer_id)
  1463. elif kprofile_drift.needs_check(printer_id, state):
  1464. spawn_background_task(
  1465. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1466. name=f"reapply-kprofiles-{printer_id}",
  1467. )
  1468. except Exception:
  1469. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1470. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1471. # connected → disconnected. The "back online" channel is already covered
  1472. # by the print-failure notification (firmware reports gcode_state=FAILED
  1473. # on reconnect of an interrupted print), so we don't add a symmetric
  1474. # online event here.
  1475. prev_connected = _printer_last_connected.get(printer_id)
  1476. _printer_last_connected[printer_id] = state.connected
  1477. if prev_connected is True and not state.connected:
  1478. existing = _printer_offline_notify_tasks.get(printer_id)
  1479. if existing is None or existing.done():
  1480. logging.getLogger(__name__).info(
  1481. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1482. printer_id,
  1483. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1484. )
  1485. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1486. _maybe_notify_printer_offline(printer_id),
  1487. name=f"printer-offline-notify-{printer_id}",
  1488. )
  1489. elif state.connected:
  1490. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1491. if pending is not None and not pending.done():
  1492. logging.getLogger(__name__).info(
  1493. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1494. printer_id,
  1495. )
  1496. pending.cancel()
  1497. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1498. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1499. temps = state.temperatures or {}
  1500. nozzle_temp = round(temps.get("nozzle", 0))
  1501. bed_temp = round(temps.get("bed", 0))
  1502. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1503. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1504. # Auto-detect dual-nozzle printers from MQTT temperature data
  1505. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1506. _nozzle_count_updated.add(printer_id)
  1507. # Update nozzle_count in database
  1508. async with async_session() as db:
  1509. from backend.app.models.printer import Printer
  1510. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1511. printer = result.scalar_one_or_none()
  1512. if printer and printer.nozzle_count != 2:
  1513. printer.nozzle_count = 2
  1514. await db.commit()
  1515. logging.getLogger(__name__).info(
  1516. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1517. )
  1518. # Include target temps for heating phase detection
  1519. bed_target = round(temps.get("bed_target", 0))
  1520. nozzle_target = round(temps.get("nozzle_target", 0))
  1521. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1522. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1523. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1524. #
  1525. # dry_countdown_stalled rides along because it is the one drying signal the
  1526. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1527. # dry_time stopped moving, so on the frame that flips it every other member
  1528. # of this key is identical and the push would be deduplicated away. Mid-print
  1529. # a temperature would eventually break the tie, but a parked command on an
  1530. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1531. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1532. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1533. ams_dry_key = (
  1534. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1535. if state.raw_data
  1536. else ()
  1537. )
  1538. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1539. #
  1540. # The filament identity fields are here because Configure Slot writes
  1541. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1542. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1543. # matched, this function returned before broadcasting, and the card kept
  1544. # showing the old filament until the 30s fallback poll or a page reload —
  1545. # even though the configure route asks the printer for a fresh pushall and
  1546. # that push does carry the new values. Reset always worked, because it
  1547. # clears tray_type.
  1548. #
  1549. # These fields only change when someone configures a slot or swaps a spool,
  1550. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1551. ams_tray_key = (
  1552. tuple(
  1553. (
  1554. t.get("id"),
  1555. t.get("tray_type", ""),
  1556. t.get("state"),
  1557. t.get("tray_color", ""),
  1558. t.get("tray_info_idx", ""),
  1559. t.get("tray_sub_brands", ""),
  1560. t.get("cali_idx"),
  1561. )
  1562. for a in (state.raw_data.get("ams") or [])
  1563. for t in a.get("tray", [])
  1564. )
  1565. if state.raw_data
  1566. else ()
  1567. )
  1568. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1569. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1570. # in the AMS change-hash (tray fields only, and widening that would fire
  1571. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1572. # screen changed no key at all and the card's inlet badges sat stale until a
  1573. # reload. Like the filament-backup flag, these only move when someone
  1574. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1575. fts_key = (
  1576. state.fila_switch.installed if state.fila_switch else False,
  1577. tuple(sorted(state.ams_switch_inlet.items())),
  1578. # Which hotend holds which slot. Unlike the two above this does move
  1579. # mid-print, on every filament change — but only between discrete slots,
  1580. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1581. # it live: it decides which hotend the Load dialog may offer and whether
  1582. # Unload has anything to act on.
  1583. tuple(
  1584. sorted(
  1585. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1586. # Sort on the extruder id alone: the other members are nullable
  1587. # and comparing None with an int raises.
  1588. key=lambda entry: entry[0],
  1589. )
  1590. ),
  1591. )
  1592. status_key = (
  1593. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1594. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1595. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1596. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1597. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1598. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1599. )
  1600. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1601. if not is_active_print:
  1602. _unauthorized_print_kill_sent.discard(printer_id)
  1603. elif printer_id in _unauthorized_print_kill_sent:
  1604. # stop_print() was already sent for this print; avoid all further
  1605. # ownership and settings work until the printer leaves an active state.
  1606. pass
  1607. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1608. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1609. _unauthorized_print_kill_sent.discard(printer_id)
  1610. else:
  1611. kill_switch_enabled = False
  1612. authorization: bool | None = None
  1613. status_logger = logging.getLogger(__name__)
  1614. try:
  1615. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1616. if kill_switch_enabled:
  1617. async with async_session() as db:
  1618. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1619. except Exception as e:
  1620. # Fail safe: a database/reconciliation error must never turn into an
  1621. # irreversible stop of a print whose ownership is still unknown.
  1622. authorization = None
  1623. status_logger.warning(
  1624. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1625. )
  1626. if not kill_switch_enabled or authorization is True:
  1627. _unauthorized_print_kill_sent.discard(printer_id)
  1628. elif authorization is None:
  1629. _unauthorized_print_kill_sent.discard(printer_id)
  1630. status_logger.debug(
  1631. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1632. printer_id,
  1633. )
  1634. else:
  1635. try:
  1636. stopped = printer_manager.stop_print(printer_id)
  1637. if stopped:
  1638. _unauthorized_print_kill_sent.add(printer_id)
  1639. printer_info = printer_manager.get_printer(printer_id)
  1640. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1641. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1642. notification_data = {
  1643. "status": "stopped",
  1644. "filename": state.gcode_file or state.current_print or "",
  1645. "subtask_name": state.subtask_name or "",
  1646. "progress": state.progress,
  1647. "reason": "unauthorized_print",
  1648. }
  1649. status_logger.warning(
  1650. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1651. printer_id,
  1652. state.state,
  1653. )
  1654. try:
  1655. await ws_manager.broadcast(
  1656. {
  1657. "type": "kill_switch_triggered",
  1658. "printer_id": printer_id,
  1659. "printer_name": printer_name,
  1660. "filename": filename,
  1661. "reason": "unauthorized_print",
  1662. }
  1663. )
  1664. except Exception as e:
  1665. status_logger.warning(
  1666. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1667. )
  1668. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1669. if previous_task is not None and not previous_task.done():
  1670. previous_task.cancel()
  1671. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1672. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1673. name=f"kill-switch-notification-{printer_id}",
  1674. )
  1675. else:
  1676. status_logger.warning(
  1677. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1678. printer_id,
  1679. state.state,
  1680. )
  1681. except Exception as e:
  1682. status_logger.warning(
  1683. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1684. )
  1685. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1686. try:
  1687. printer_info = printer_manager.get_printer(printer_id)
  1688. if printer_info:
  1689. await mqtt_relay.on_printer_status(
  1690. printer_id,
  1691. state,
  1692. printer_info.name,
  1693. printer_info.serial_number,
  1694. printer_manager.is_awaiting_plate_clear(printer_id),
  1695. )
  1696. except Exception:
  1697. pass # Don't fail status callback if MQTT fails
  1698. if _last_status_broadcast.get(printer_id) == status_key:
  1699. return # No change, skip WebSocket broadcast
  1700. _last_status_broadcast[printer_id] = status_key
  1701. # Check for progress milestone notifications (25%, 50%, 75%)
  1702. progress = state.progress or 0
  1703. is_printing = state.state in ("RUNNING", "PRINTING")
  1704. if is_printing and progress > 0:
  1705. current_milestone = _progress_milestone_to_notify(printer_id, state)
  1706. if current_milestone is not None:
  1707. try:
  1708. from backend.app.models.printer import Printer
  1709. # Read the printer in a short session and release the connection
  1710. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1711. # pinned a pooled connection per milestone, per printer (issue #2572).
  1712. async with async_session() as db:
  1713. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1714. printer = result.scalar_one_or_none()
  1715. printer_name = printer.name if printer else f"Printer {printer_id}"
  1716. filename = state.subtask_name or state.gcode_file or "Unknown"
  1717. # remaining_time is in minutes, convert to seconds for notification
  1718. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1719. # Capture camera snapshot for notification image attachment (no DB held).
  1720. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1721. # Notification send needs a session (provider/template lookups).
  1722. async with async_session() as db:
  1723. await notification_service.on_print_progress(
  1724. printer_id,
  1725. printer_name,
  1726. filename,
  1727. current_milestone,
  1728. db,
  1729. remaining_time_seconds,
  1730. image_data=image_data,
  1731. )
  1732. except Exception as e:
  1733. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1734. elif progress < 5:
  1735. # Reset milestone tracking when print restarts or new print begins
  1736. _last_progress_milestone[printer_id] = 0
  1737. _first_layer_notified[printer_id] = False
  1738. # HMS error codes that should not trigger notifications even though they
  1739. # have known descriptions (e.g. user-initiated actions, not real errors).
  1740. _HMS_NOTIFICATION_SUPPRESS = {
  1741. "0500_400E", # Printing was cancelled (user action, not an error)
  1742. }
  1743. # Check for new HMS errors and send notifications
  1744. current_hms_errors = getattr(state, "hms_errors", []) or []
  1745. if current_hms_errors:
  1746. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  1747. if new_errors:
  1748. try:
  1749. from backend.app.models.printer import Printer
  1750. # Read the printer in a short session and release the connection
  1751. # BEFORE the ~15s camera snapshot below (issue #2572).
  1752. async with async_session() as db:
  1753. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1754. printer = result.scalar_one_or_none()
  1755. printer_name = printer.name if printer else f"Printer {printer_id}"
  1756. # Format error details for notification
  1757. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1758. module_names = {
  1759. 0x03: "Print/Task",
  1760. 0x05: "Nozzle/Extruder",
  1761. 0x07: "AMS/Filament",
  1762. 0x0C: "Motion Controller",
  1763. 0x12: "Chamber",
  1764. }
  1765. # Capture camera snapshot once for all error notifications (no DB held).
  1766. error_image_data = await _capture_snapshot_for_notification(
  1767. printer_id, printer, logging.getLogger(__name__)
  1768. )
  1769. # Notification sends need a session (provider/template lookups).
  1770. async with async_session() as db:
  1771. sent_count = 0
  1772. for error in new_errors:
  1773. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  1774. # Build short code like "0700_8010"
  1775. # Mask to 16 bits to handle printers that send larger values
  1776. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  1777. error_code_masked = error_code_int & 0xFFFF
  1778. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  1779. # Only notify for errors Bambu publishes text for — printers
  1780. # send undocumented codes that aren't real errors, and Bambu
  1781. # lists some with empty text. Resolved at parse time (#2926);
  1782. # short_code is still needed for the suppression set below.
  1783. description = error.description
  1784. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  1785. continue
  1786. error_type = f"{module_name} Error"
  1787. error_detail = description
  1788. await notification_service.on_printer_error(
  1789. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  1790. )
  1791. sent_count += 1
  1792. if sent_count:
  1793. logging.getLogger(__name__).info(
  1794. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  1795. )
  1796. # Also publish to MQTT relay (no DB): every new fault that
  1797. # counts, with or without text, the same set the UI counts.
  1798. printer_info = printer_manager.get_printer(printer_id)
  1799. if printer_info:
  1800. errors_data = [
  1801. {
  1802. "code": e.code,
  1803. "attr": e.attr,
  1804. "module": e.module,
  1805. "severity": e.severity,
  1806. }
  1807. for e in new_errors
  1808. ]
  1809. await mqtt_relay.on_printer_error(
  1810. printer_id, printer_info.name, printer_info.serial_number, errors_data
  1811. )
  1812. except Exception as e:
  1813. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  1814. else:
  1815. # No HMS errors: nothing to send, but faults gone long enough (or gone
  1816. # across a print state change) are forgotten. Some codes, e.g. chamber
  1817. # temperature regulation during PETG prints, toggle every few seconds.
  1818. _take_new_hms_faults(printer_id, [], state.state)
  1819. await ws_manager.send_printer_status(
  1820. printer_id,
  1821. printer_state_to_dict(
  1822. state,
  1823. printer_id,
  1824. printer_manager.get_model(printer_id),
  1825. printer_manager.get_drying_targets(printer_id),
  1826. ),
  1827. )
  1828. def _is_bambu_uuid(tray_uuid: str) -> bool:
  1829. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  1830. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  1831. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  1832. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  1833. K-profiles are per-nozzle and the printer's calibration table is numbered
  1834. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  1835. switch's other inlet therefore silently invalidates every configured slot in
  1836. it: the index stays put and now resolves against the other nozzle's table.
  1837. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  1838. and 0.020 on the right kept the left profile after the move, and a manual
  1839. RFID re-read only re-asserted the same wrong one.
  1840. Configuring a slot is a deliberate preparation step, so this re-selects
  1841. rather than re-configures: only the calibration binding moves, and only for
  1842. slots whose spool already has a stored profile for the new nozzle. A slot
  1843. Bambuddy knows nothing about is left exactly as the operator left it.
  1844. """
  1845. logger = logging.getLogger(__name__)
  1846. target_extruder = extruder_for_inlet(inlet)
  1847. if target_extruder is None:
  1848. return
  1849. client = printer_manager.get_client(printer_id)
  1850. state = printer_manager.get_status(printer_id)
  1851. if not client or not state or not state.raw_data:
  1852. return
  1853. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  1854. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  1855. # the nozzle width, which changes both the K profile to select and the
  1856. # preset the slot should carry.
  1857. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  1858. ams_raw = state.raw_data.get("ams")
  1859. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  1860. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  1861. if not unit:
  1862. return
  1863. try:
  1864. async with async_session() as db:
  1865. for tray in unit.get("tray", []):
  1866. tray_id = int(tray.get("id", -1))
  1867. if tray_id < 0 or not tray.get("tray_type"):
  1868. continue
  1869. current_idx = tray.get("cali_idx")
  1870. profile = await find_slot_kprofile_for_extruder(
  1871. db,
  1872. printer_id,
  1873. ams_id,
  1874. tray_id,
  1875. target_extruder,
  1876. nozzle_diameter,
  1877. printer_manager.get_model(printer_id),
  1878. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  1879. )
  1880. if profile is None or profile.cali_idx is None:
  1881. continue
  1882. if current_idx == profile.cali_idx:
  1883. continue # Already on the right one.
  1884. logger.info(
  1885. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  1886. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  1887. printer_id,
  1888. ams_id,
  1889. tray_id,
  1890. inlet,
  1891. target_extruder,
  1892. profile.name,
  1893. current_idx,
  1894. profile.cali_idx,
  1895. profile.k_value,
  1896. )
  1897. client.extrusion_cali_sel(
  1898. ams_id=ams_id,
  1899. tray_id=tray_id,
  1900. cali_idx=profile.cali_idx,
  1901. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  1902. nozzle_diameter=nozzle_diameter,
  1903. )
  1904. except Exception as e:
  1905. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  1906. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  1907. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  1908. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  1909. from the delayed re-check -- which is why it takes the AMS data and print
  1910. state as arguments instead of reading them from the push (#3186).
  1911. """
  1912. logger = logging.getLogger(__name__)
  1913. from backend.app.utils.color_utils import colors_similar as _colors_similar
  1914. # Auto-unlink spool assignments with stale fingerprints. Under the
  1915. # per-printer assignment lock since #3186: the held-removal re-check runs
  1916. # this outside any MQTT push, so it can now overlap one.
  1917. try:
  1918. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  1919. from sqlalchemy.orm import selectinload
  1920. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  1921. from backend.app.models.spool import Spool as _Spool
  1922. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1923. from backend.app.services.ams_slot_presence import spool_present
  1924. from backend.app.services.inventory_mode import spoolman_owns_assignments
  1925. # Built-in assignments only. Since #2812 they survive a switch to
  1926. # Spoolman mode rather than being deleted by it, and this pass ends
  1927. # in ``db.delete`` — left ungated it would unlink them one slot at a
  1928. # time as the AMS contents changed under the other mode, undoing the
  1929. # preservation more slowly but just as completely.
  1930. assignments = []
  1931. if not await spoolman_owns_assignments(db):
  1932. result = await db.execute(
  1933. select(SA)
  1934. .where(SA.printer_id == printer_id)
  1935. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  1936. )
  1937. assignments = result.scalars().all()
  1938. # ``printing_now`` (top of this function) keeps a runout from
  1939. # unlinking the spool that fed the print — the next idle-time pass
  1940. # unlinks it if the user really did take it out.
  1941. stale = []
  1942. # Removals this pass is holding rather than unlinking (#3186).
  1943. held: set[tuple] = set()
  1944. for assignment in assignments:
  1945. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  1946. if assignment.ams_id == 255:
  1947. ps = printer_manager.get_status(printer_id)
  1948. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  1949. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  1950. current_tray = None
  1951. for vt in vt_tray_raw:
  1952. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  1953. current_tray = vt
  1954. break
  1955. if not current_tray:
  1956. # vt_tray data may not have arrived yet — keep assignment
  1957. continue
  1958. else:
  1959. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  1960. if not current_tray:
  1961. if printing_now:
  1962. logger.info(
  1963. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  1964. assignment.spool_id,
  1965. assignment.ams_id,
  1966. assignment.tray_id,
  1967. )
  1968. continue
  1969. # A whole AMS unit can drop out of one push and come back in
  1970. # the next; only a slot that stays gone is a removal (#3186).
  1971. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  1972. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  1973. held.add(hold_key)
  1974. logger.info(
  1975. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  1976. "unlinking if it is still gone in %ds",
  1977. assignment.spool_id,
  1978. assignment.ams_id,
  1979. assignment.tray_id,
  1980. int(slot_unlink_grace.GRACE_SECONDS),
  1981. )
  1982. continue
  1983. logger.info(
  1984. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  1985. assignment.spool_id,
  1986. assignment.ams_id,
  1987. assignment.tray_id,
  1988. )
  1989. stale.append(assignment) # Slot empty
  1990. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  1991. # A Bambu Lab spool is in this slot — check if it's the same spool
  1992. # that's currently assigned. If yes, keep the assignment (avoids
  1993. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  1994. # the printer's filament preset on every startup).
  1995. tray_uuid = current_tray.get("tray_uuid", "")
  1996. tag_uid = current_tray.get("tag_uid", "")
  1997. spool = assignment.spool
  1998. spool_matches = False
  1999. if spool:
  2000. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2001. spool.tag_uid
  2002. and tag_uid
  2003. and tag_uid != "0000000000000000"
  2004. and spool.tag_uid.upper() == tag_uid.upper()
  2005. ):
  2006. spool_matches = True
  2007. if spool_matches:
  2008. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2009. cur_color = current_tray.get("tray_color", "")
  2010. cur_type = current_tray.get("tray_type", "")
  2011. fp_color = assignment.fingerprint_color or ""
  2012. fp_type = assignment.fingerprint_type or ""
  2013. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2014. assignment.fingerprint_color = cur_color
  2015. assignment.fingerprint_type = cur_type
  2016. logger.debug(
  2017. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2018. assignment.spool_id,
  2019. assignment.ams_id,
  2020. assignment.tray_id,
  2021. )
  2022. continue
  2023. # Different BL spool or unrecognized — unlink so auto-assign can match
  2024. logger.info(
  2025. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2026. assignment.spool_id,
  2027. assignment.ams_id,
  2028. assignment.tray_id,
  2029. tray_uuid,
  2030. )
  2031. stale.append(assignment)
  2032. else:
  2033. cur_color = current_tray.get("tray_color", "")
  2034. cur_type = current_tray.get("tray_type", "")
  2035. cur_state = current_tray.get("state")
  2036. fp_color = assignment.fingerprint_color or ""
  2037. fp_type = assignment.fingerprint_type or ""
  2038. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2039. # the slot was empty when the user pre-assigned via SpoolBuddy
  2040. # (the firmware drops ams_filament_setting on empty slots, so
  2041. # MQTT was deferred). The moment any filament gets inserted
  2042. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2043. # reconfigured spool — fire the deferred configuration.
  2044. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2045. # extruder" code) OR, on firmwares that don't use the state
  2046. # enum meaningfully, a non-empty tray_type when state is
  2047. # NOT one of the firmware's explicit empty signals (9, 10).
  2048. # state-only was wrong for firmwares that never set 11 — A1
  2049. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2050. # always report state=3 — so the replay never fired for them
  2051. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2052. # explicit "empty" signals authoritative over any stale
  2053. # tray_type that might survive the relay's auto-clearing.
  2054. #
  2055. # tray_exist_bits comes first because that guard cannot tell
  2056. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2057. # writes state=9 when the bit is 0 and leaves it there when the
  2058. # bit returns. A non-RFID spool inserted into a pre-assigned
  2059. # slot brings no tray_type with it, so the stale 9 made this
  2060. # expression false forever and the deferred config never fired
  2061. # — the deadlock #1322 removed from the assign path, still in
  2062. # place here (#3084, #3100).
  2063. loaded = spool_present(current_tray) is True or (
  2064. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2065. )
  2066. if not fp_type.strip() and loaded and assignment.spool:
  2067. try:
  2068. from backend.app.api.routes.inventory import (
  2069. apply_spool_to_slot_via_mqtt,
  2070. )
  2071. await apply_spool_to_slot_via_mqtt(
  2072. db=db,
  2073. current_user=None,
  2074. spool=assignment.spool,
  2075. printer_id=printer_id,
  2076. ams_id=assignment.ams_id,
  2077. tray_id=assignment.tray_id,
  2078. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2079. current_tray_type=cur_type,
  2080. )
  2081. logger.info(
  2082. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2083. assignment.spool_id,
  2084. printer_id,
  2085. assignment.ams_id,
  2086. assignment.tray_id,
  2087. )
  2088. except Exception:
  2089. logger.exception(
  2090. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2091. assignment.spool_id,
  2092. printer_id,
  2093. assignment.ams_id,
  2094. assignment.tray_id,
  2095. )
  2096. assignment.fingerprint_color = cur_color
  2097. assignment.fingerprint_type = cur_type
  2098. continue
  2099. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2100. # Blank tray data mid-print is a runout, not a swap: the
  2101. # firmware clears colour and type when it unloads a spool
  2102. # it just emptied. Unlinking here would erase the record
  2103. # of which spool fed the print so far.
  2104. if printing_now and not cur_color.strip() and not cur_type.strip():
  2105. logger.info(
  2106. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2107. "(runout?)",
  2108. assignment.spool_id,
  2109. assignment.ams_id,
  2110. assignment.tray_id,
  2111. )
  2112. continue
  2113. # Same reasoning off the print, on firmware's own say-so:
  2114. # a blank tray report from a slot whose tray_exist_bits
  2115. # bit is set describes a spool the AMS cannot identify —
  2116. # a non-RFID one, or one whose slot was reset — not a
  2117. # spool that was taken out. Deleting the assignment there
  2118. # threw away the identity the user had supplied, which is
  2119. # the only place it existed (#3100). A slot the bit calls
  2120. # empty, or one that carries no bit at all, still unlinks.
  2121. #
  2122. # Unless the slot was reported empty first: a removal
  2123. # already held means a spool came out and another went
  2124. # in, so the blank report keeps the hold running below
  2125. # rather than cancelling it (#3186).
  2126. if (
  2127. spool_present(current_tray) is True
  2128. and not cur_color.strip()
  2129. and not cur_type.strip()
  2130. and not slot_unlink_grace.is_held(
  2131. printer_id,
  2132. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2133. )
  2134. ):
  2135. logger.info(
  2136. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2137. "tray reports no filament data yet",
  2138. assignment.spool_id,
  2139. assignment.ams_id,
  2140. assignment.tray_id,
  2141. )
  2142. continue
  2143. # A blank report the presence bit does not vouch for is
  2144. # still only one push. An idle X1C cleared a whole AMS
  2145. # unit's bits, colour and type for a moment and lost
  2146. # four saved assignments that way (#3186); unlink only
  2147. # if the slot is still blank after the grace period.
  2148. if not cur_color.strip() and not cur_type.strip():
  2149. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2150. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2151. held.add(hold_key)
  2152. logger.info(
  2153. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2154. "unlinking if it is still blank in %ds",
  2155. assignment.spool_id,
  2156. assignment.ams_id,
  2157. assignment.tray_id,
  2158. int(slot_unlink_grace.GRACE_SECONDS),
  2159. )
  2160. continue
  2161. # Fingerprint mismatch — but check if tray now matches the
  2162. # assigned spool (e.g. auto-configure changed the tray).
  2163. # Both sides are reduced to the type the slot can carry
  2164. # before comparing: the assign path writes that rather
  2165. # than the spool's raw material (#2902), so a spool whose
  2166. # material is a product line — "PLA+", "HTPLA" — reports
  2167. # back as "PLA" and would otherwise fail this check and
  2168. # be auto-unlinked from the slot it was just assigned to.
  2169. # Reducing the printer's side too keeps slots configured
  2170. # by an older Bambuddy, still reporting "PLA+", matching.
  2171. spool = assignment.spool
  2172. if spool:
  2173. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2174. # Two ways the assign path can have arrived at the
  2175. # slot's type, so both count as "we wrote this".
  2176. # The material column is one; the spool's preset is
  2177. # the other, and it outranks the material when the
  2178. # spool has one -- a spool whose material says PLA
  2179. # and whose preset is "Bambu PLA Aero" puts
  2180. # PLA-AERO in the slot (#2902). Read from the stored
  2181. # preset name rather than resolving the preset,
  2182. # because this runs on every AMS push and a cloud
  2183. # lookup here would be both slow and unavailable on
  2184. # the unauthenticated replay path.
  2185. spool_types = {printer_filament_type(spool.material).upper()}
  2186. if spool.slicer_filament_name:
  2187. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2188. # An imported local preset stores its type outright,
  2189. # which is what the assign path used -- and the name
  2190. # above may be unset. One keyed read, and only on a
  2191. # mismatch, which is rare.
  2192. #
  2193. # slicer_filament is free text up to fifty characters,
  2194. # so the digits have to be checked against the range
  2195. # of the integer primary key they are about to be
  2196. # compared with. Postgres raises on an out-of-range
  2197. # integer rather than simply not matching, and that
  2198. # would poison this session and abandon the rest of
  2199. # the cleanup pass.
  2200. lp_ref = (spool.slicer_filament or "").strip()
  2201. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2202. from backend.app.models.local_preset import LocalPreset as _LP
  2203. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2204. if lp_type:
  2205. spool_types.add(printer_filament_type(lp_type).upper())
  2206. if (
  2207. _colors_similar(cur_color, spool_color)
  2208. and printer_filament_type(cur_type).upper() in spool_types
  2209. ):
  2210. logger.info(
  2211. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2212. assignment.spool_id,
  2213. assignment.ams_id,
  2214. assignment.tray_id,
  2215. )
  2216. assignment.fingerprint_color = cur_color
  2217. assignment.fingerprint_type = cur_type
  2218. continue
  2219. logger.info(
  2220. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2221. assignment.spool_id,
  2222. assignment.ams_id,
  2223. assignment.tray_id,
  2224. cur_color,
  2225. cur_type,
  2226. fp_color,
  2227. fp_type,
  2228. spool.rgba if spool else "?",
  2229. spool.material if spool else "?",
  2230. )
  2231. stale.append(assignment) # Spool changed
  2232. slot_unlink_grace.settle(printer_id, "inventory", held)
  2233. # Snapshot slots before delete — ORM attribute access after the
  2234. # commit would refresh against a deleted row.
  2235. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2236. for a in stale:
  2237. await db.delete(a)
  2238. if stale:
  2239. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2240. # Commit any changes (stale deletions and/or fingerprint updates)
  2241. await db.commit()
  2242. # Tell open browsers the assignment is gone (#2575). Only the manual
  2243. # REST assign/unassign endpoints broadcast this event; without it the
  2244. # frontend's spool-assignments cache keeps rendering the unlinked
  2245. # spool on the slot until an unrelated refetch — which reads exactly
  2246. # like "the fix didn't work" (reporter verified: a browser refresh
  2247. # after the swap showed the correct state all along).
  2248. for ams_id, tray_id in unlinked_slots:
  2249. await ws_manager.broadcast(
  2250. {
  2251. "type": "spool_assignment_changed",
  2252. "printer_id": printer_id,
  2253. "ams_id": ams_id,
  2254. "tray_id": tray_id,
  2255. }
  2256. )
  2257. except Exception as e:
  2258. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2259. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2260. """Delete Spoolman slot rows whose held removal has run its grace period.
  2261. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2262. talks to Spoolman for every tray; this only needs the local rows, so it
  2263. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2264. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2265. not in a slot the presence bit calls occupied -- and nothing else.
  2266. """
  2267. logger = logging.getLogger(__name__)
  2268. try:
  2269. async with async_session() as db:
  2270. from backend.app.api.routes.settings import get_setting
  2271. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2272. from backend.app.services.ams_slot_presence import spool_present
  2273. enabled = await get_setting(db, "spoolman_enabled")
  2274. if not enabled or enabled.lower() != "true":
  2275. return
  2276. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2277. if sync_mode and sync_mode != "auto":
  2278. return
  2279. trays: dict[tuple[int, int], dict] = {}
  2280. for ams_unit in ams_data or []:
  2281. if not isinstance(ams_unit, dict):
  2282. continue
  2283. for tray in ams_unit.get("tray", []):
  2284. if isinstance(tray, dict):
  2285. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2286. rows = (
  2287. (
  2288. await db.execute(
  2289. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2290. )
  2291. )
  2292. .scalars()
  2293. .all()
  2294. )
  2295. held: set[tuple] = set()
  2296. expired: list[tuple[int, int]] = []
  2297. for row in rows:
  2298. tray = trays.get((row.ams_id, row.tray_id))
  2299. if tray is None or printing_now:
  2300. continue
  2301. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2302. continue
  2303. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2304. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2305. continue
  2306. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2307. expired.append((row.ams_id, row.tray_id))
  2308. else:
  2309. held.add(hold_key)
  2310. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2311. if not expired:
  2312. return
  2313. # A statement rather than ORM deletes, like the sync pass: the two
  2314. # can overlap, and a row the other already removed must not fail
  2315. # this commit.
  2316. for ams_id, tray_id in expired:
  2317. await db.execute(
  2318. delete(SpoolmanSlotAssignment).where(
  2319. SpoolmanSlotAssignment.printer_id == printer_id,
  2320. SpoolmanSlotAssignment.ams_id == ams_id,
  2321. SpoolmanSlotAssignment.tray_id == tray_id,
  2322. )
  2323. )
  2324. await db.commit()
  2325. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2326. for ams_id, tray_id in expired:
  2327. await ws_manager.broadcast(
  2328. {
  2329. "type": "spool_assignment_changed",
  2330. "printer_id": printer_id,
  2331. "ams_id": ams_id,
  2332. "tray_id": tray_id,
  2333. }
  2334. )
  2335. except Exception as e:
  2336. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2337. async def _recheck_held_unlinks(printer_id: int) -> None:
  2338. """Re-run just the slot cleanup against the printer's current AMS state.
  2339. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2340. passes otherwise run only when the AMS hash changes, and a slot that went
  2341. empty and stayed empty may never change it again.
  2342. """
  2343. status = printer_manager.get_status(printer_id)
  2344. # A disconnected printer's state is its last report, not a new one: acting
  2345. # on it would "confirm" a removal nobody has seen for the whole grace
  2346. # period. Leave the holds; the first push after reconnecting decides.
  2347. if status is None or not status.connected:
  2348. return
  2349. ams_raw = status.raw_data.get("ams")
  2350. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2351. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2352. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2353. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2354. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2355. async def on_ams_change(printer_id: int, ams_data: list):
  2356. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2357. logger = logging.getLogger(__name__)
  2358. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  2359. # on_print_complete may pop _active_sessions during our awaits (#880).
  2360. from backend.app.services.usage_tracker import _active_sessions
  2361. _print_active = printer_id in _active_sessions
  2362. # A slot that reports empty while a print is running is a filament runout,
  2363. # not a spool swap: the spool is still physically in the AMS, just
  2364. # consumed. Dropping either inventory backend's slot link there loses the
  2365. # only record of which spool fed the print, so the completion path can't
  2366. # charge the runout segment to anything. Both cleanup passes below consult
  2367. # this; computed once, up front, so neither depends on the other having run.
  2368. _unlink_state = printer_manager.get_status(printer_id)
  2369. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2370. # MQTT relay - publish AMS change
  2371. try:
  2372. printer_info = printer_manager.get_printer(printer_id)
  2373. if printer_info:
  2374. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2375. except Exception:
  2376. pass # Don't fail AMS callback if MQTT fails
  2377. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2378. # This ensures frontend gets immediate updates when AMS slots are configured
  2379. try:
  2380. state = printer_manager.get_status(printer_id)
  2381. if state:
  2382. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2383. await ws_manager.send_printer_status(
  2384. printer_id,
  2385. printer_state_to_dict(
  2386. state,
  2387. printer_id,
  2388. printer_manager.get_model(printer_id),
  2389. printer_manager.get_drying_targets(printer_id),
  2390. ),
  2391. )
  2392. except Exception as e:
  2393. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2394. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2395. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2396. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  2397. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2398. # "no existing assignment" for the same (printer, ams, tray) and race to
  2399. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2400. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2401. # bug stayed latent there. See _ams_assignment_locks comment for details.
  2402. try:
  2403. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2404. from sqlalchemy.orm import selectinload
  2405. from backend.app.api.routes.settings import get_setting
  2406. from backend.app.models.spool import Spool
  2407. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2408. from backend.app.services.spool_tag_matcher import (
  2409. auto_assign_spool,
  2410. create_spool_from_tray,
  2411. find_matching_untagged_spool,
  2412. get_spool_by_tag,
  2413. is_bambu_tag,
  2414. is_valid_tag,
  2415. link_tag_to_inventory_spool,
  2416. )
  2417. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2418. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2419. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2420. if not _spoolman_on or _spoolman_on.lower() != "true":
  2421. for ams_unit in ams_data:
  2422. if not isinstance(ams_unit, dict):
  2423. continue
  2424. ams_id = int(ams_unit.get("id", 0))
  2425. for tray in ams_unit.get("tray", []):
  2426. if not isinstance(tray, dict):
  2427. continue
  2428. tray_id = int(tray.get("id", 0))
  2429. tag_uid = tray.get("tag_uid", "")
  2430. tray_uuid = tray.get("tray_uuid", "")
  2431. tray_info_idx = tray.get("tray_info_idx", "")
  2432. if not tray.get("tray_type"):
  2433. # Slot reported empty — drop any cached unknown-tag
  2434. # broadcast so reinserting the same spool re-prompts.
  2435. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2436. continue # Empty slot
  2437. # Check if assignment already exists for this slot
  2438. existing = await db.execute(
  2439. select(SA)
  2440. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2441. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2442. )
  2443. existing_assignment = existing.scalar_one_or_none()
  2444. if existing_assignment:
  2445. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2446. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2447. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2448. # Skip during active prints: the usage tracker handles deduction
  2449. # precisely via 3MF data on print completion. Without this guard the
  2450. # AMS remain% SET and the usage tracker ADD both fire from the same
  2451. # MQTT message, doubling the deduction (#880).
  2452. if _print_active:
  2453. continue
  2454. remain_raw = tray.get("remain")
  2455. if (
  2456. remain_raw is not None
  2457. and existing_assignment.spool
  2458. and not existing_assignment.spool.weight_locked
  2459. ):
  2460. try:
  2461. remain_val = int(remain_raw)
  2462. except (TypeError, ValueError):
  2463. remain_val = -1
  2464. if 1 <= remain_val <= 100:
  2465. lw = existing_assignment.spool.label_weight or 1000
  2466. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2467. current_used = existing_assignment.spool.weight_used or 0
  2468. if new_used > current_used + 1:
  2469. logger.info(
  2470. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2471. existing_assignment.spool_id,
  2472. current_used,
  2473. new_used,
  2474. remain_val,
  2475. )
  2476. existing_assignment.spool.weight_used = new_used
  2477. await db.commit()
  2478. # Re-apply stored K-profile when the live tray's
  2479. # cali_idx drifted from the spool's stored profile.
  2480. # This catches "reset slot → re-read" and any other
  2481. # path where the firmware loses the user's K-profile
  2482. # selection while the SpoolAssignment row persists.
  2483. # Per the maintainer's rule: any time a spool tag is
  2484. # identified and matches inventory, the slot must be
  2485. # configured with the spool's stored settings. Without
  2486. # this block the existing-assignment branch only ran
  2487. # weight-sync and let the firmware-default cali_idx win.
  2488. try:
  2489. spool = existing_assignment.spool
  2490. if (
  2491. spool is not None
  2492. and is_bambu_tag(tag_uid, tray_uuid, tray_info_idx)
  2493. and spool.k_profiles
  2494. ):
  2495. state = printer_manager.get_status(printer_id)
  2496. slot_nozzle = resolve_slot_nozzle(
  2497. state, ams_id, tray_id, printer_manager.get_model(printer_id)
  2498. )
  2499. nozzle_diameter = slot_nozzle.diameter
  2500. slot_extruder = slot_nozzle.extruder
  2501. # Prefer exact extruder match, fall back to
  2502. # extruder-agnostic kp for the same printer +
  2503. # nozzle. Avoids hard-skipping when the AMS is
  2504. # mapped differently than at calibration time.
  2505. matching_kp = None
  2506. fallback_kp = None
  2507. for kp in spool.k_profiles:
  2508. if (
  2509. kp.printer_id != printer_id
  2510. or kp.nozzle_diameter != nozzle_diameter
  2511. or kp.cali_idx is None
  2512. or not slot_nozzle.flow_matches(kp.nozzle_type)
  2513. ):
  2514. continue
  2515. if (
  2516. slot_extruder is not None
  2517. and kp.extruder is not None
  2518. and kp.extruder == slot_extruder
  2519. ):
  2520. matching_kp = kp
  2521. break
  2522. if fallback_kp is None:
  2523. fallback_kp = kp
  2524. chosen_kp = matching_kp or fallback_kp
  2525. if chosen_kp is not None:
  2526. live_cali_idx = tray.get("cali_idx")
  2527. # Only fire MQTT when the printer's live
  2528. # cali_idx differs from the stored value.
  2529. # Avoids spamming the broker on every
  2530. # MQTT push during steady-state operation.
  2531. if live_cali_idx != chosen_kp.cali_idx:
  2532. client = printer_manager.get_client(printer_id)
  2533. if client:
  2534. cali_filament_id = spool.slicer_filament or tray_info_idx or ""
  2535. client.extrusion_cali_sel(
  2536. ams_id=ams_id,
  2537. tray_id=tray_id,
  2538. cali_idx=chosen_kp.cali_idx,
  2539. filament_id=cali_filament_id,
  2540. nozzle_diameter=nozzle_diameter,
  2541. )
  2542. logger.info(
  2543. "Re-applied K-profile cali_idx=%d for spool %d "
  2544. "on printer %d AMS%d-T%d (live=%s drift detected)",
  2545. chosen_kp.cali_idx,
  2546. spool.id,
  2547. printer_id,
  2548. ams_id,
  2549. tray_id,
  2550. live_cali_idx,
  2551. )
  2552. except Exception:
  2553. logger.exception(
  2554. "K-profile re-apply failed for printer %d AMS%d-T%d",
  2555. printer_id,
  2556. ams_id,
  2557. tray_id,
  2558. )
  2559. continue
  2560. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2561. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2562. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2563. if not spool:
  2564. # Try matching an untagged inventory spool (same material/color)
  2565. spool = await find_matching_untagged_spool(db, tray)
  2566. if spool:
  2567. await link_tag_to_inventory_spool(db, spool, tray)
  2568. elif _auto_add_unknown:
  2569. spool = await create_spool_from_tray(db, tray)
  2570. else:
  2571. # Auto-add disabled: surface the slot so the
  2572. # user can add it manually via the UI.
  2573. await _broadcast_unknown_tag(
  2574. printer_id=printer_id,
  2575. ams_id=ams_id,
  2576. tray_id=tray_id,
  2577. tag_uid=tag_uid,
  2578. tray_uuid=tray_uuid,
  2579. tray_type=tray.get("tray_type"),
  2580. tray_color=tray.get("tray_color"),
  2581. tray_sub_brands=tray.get("tray_sub_brands"),
  2582. tray_count=len(ams_unit.get("tray", [])),
  2583. )
  2584. continue
  2585. # Slot matched (existing tag, untagged inventory
  2586. # match, or freshly auto-created spool) — drop any
  2587. # stale dedup so a future tag swap re-prompts.
  2588. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2589. await auto_assign_spool(
  2590. printer_id,
  2591. ams_id,
  2592. tray_id,
  2593. spool,
  2594. printer_manager,
  2595. db,
  2596. tray_info_idx=tray_info_idx,
  2597. )
  2598. await db.commit()
  2599. await ws_manager.broadcast(
  2600. {
  2601. "type": "spool_auto_assigned",
  2602. "printer_id": printer_id,
  2603. "ams_id": ams_id,
  2604. "tray_id": tray_id,
  2605. "spool_id": spool.id,
  2606. }
  2607. )
  2608. logger.info(
  2609. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2610. spool.id,
  2611. printer_id,
  2612. ams_id,
  2613. tray_id,
  2614. )
  2615. elif is_valid_tag(tag_uid, tray_uuid):
  2616. # Non-BL spool with some tag — let user choose
  2617. await _broadcast_unknown_tag(
  2618. printer_id=printer_id,
  2619. ams_id=ams_id,
  2620. tray_id=tray_id,
  2621. tag_uid=tag_uid,
  2622. tray_uuid=tray_uuid,
  2623. tray_type=tray.get("tray_type"),
  2624. tray_color=tray.get("tray_color"),
  2625. tray_sub_brands=tray.get("tray_sub_brands"),
  2626. tray_count=len(ams_unit.get("tray", [])),
  2627. )
  2628. # No-tag slots (generic non-RFID filament) are left alone:
  2629. # nothing to identify, prompting "+ Add" would just create
  2630. # ghost spools with empty tags on every confirm.
  2631. except Exception as e:
  2632. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2633. try:
  2634. async with async_session() as db:
  2635. from backend.app.api.routes.settings import get_setting
  2636. from backend.app.models.printer import Printer
  2637. # Check if Spoolman is enabled
  2638. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2639. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2640. return
  2641. # Check sync mode
  2642. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2643. if sync_mode and sync_mode != "auto":
  2644. return # Only sync on auto mode
  2645. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2646. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2647. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2648. # always owned by per-print tracking, never by AMS auto-sync. The
  2649. # setting is still read by the settings UI for backwards compat but
  2650. # has no effect on the sync path here.
  2651. # Get Spoolman URL
  2652. spoolman_url = await get_setting(db, "spoolman_url")
  2653. if not spoolman_url:
  2654. return
  2655. # Get or create Spoolman client
  2656. client = await get_spoolman_client()
  2657. if not client:
  2658. try:
  2659. client = await init_spoolman_client(spoolman_url)
  2660. except ValueError as exc:
  2661. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2662. return
  2663. # Check if Spoolman is reachable
  2664. if not await client.health_check():
  2665. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2666. return
  2667. # Get printer name for location
  2668. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2669. printer = result.scalar_one_or_none()
  2670. printer_name = printer.name if printer else f"Printer {printer_id}"
  2671. # OPTIMIZATION: Fetch all spools once before processing trays
  2672. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2673. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2674. try:
  2675. cached_spools = await client.get_spools()
  2676. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2677. except Exception as e:
  2678. logger.error(
  2679. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2680. printer_id,
  2681. e,
  2682. )
  2683. return
  2684. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2685. from sqlalchemy.orm import selectinload
  2686. from backend.app.models.spool_assignment import SpoolAssignment
  2687. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2688. from backend.app.services.ams_slot_presence import spool_present
  2689. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2690. # Built-in remaining weight, used by sync_ams_tray only when the
  2691. # firmware reports an unusable remain%/tray_weight for a slot.
  2692. #
  2693. # Left empty since #2812. This block runs in Spoolman mode only,
  2694. # and until then the built-in table was emptied on the switch, so
  2695. # there was never anything here to read and the fallback was inert.
  2696. # Preserving those rows makes it live again, and it is keyed by slot
  2697. # rather than by spool: after a mode switch the tray may well hold
  2698. # different filament, and ``create_spool`` writes ``remaining_weight``
  2699. # unconditionally, so a stale figure would be seeded into a brand new
  2700. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  2701. # intent survives for whoever revisits the cross-mode fallback.
  2702. inventory_weights: dict[tuple[int, int], float] = {}
  2703. if not await spoolman_owns_assignments(db):
  2704. try:
  2705. assign_result = await db.execute(
  2706. select(SpoolAssignment)
  2707. .options(selectinload(SpoolAssignment.spool))
  2708. .where(SpoolAssignment.printer_id == printer_id)
  2709. )
  2710. for assignment in assign_result.scalars().all():
  2711. spool = assignment.spool
  2712. if spool and spool.label_weight > 0:
  2713. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2714. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2715. except Exception as e:
  2716. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2717. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2718. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2719. try:
  2720. slot_result = await db.execute(
  2721. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2722. )
  2723. for slot in slot_result.scalars().all():
  2724. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2725. except Exception as e:
  2726. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2727. # Sync each AMS tray and collect slot changes for DB persistence
  2728. synced = 0
  2729. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2730. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2731. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  2732. for ams_unit in ams_data:
  2733. if not isinstance(ams_unit, dict):
  2734. continue
  2735. ams_id = int(ams_unit.get("id", 0))
  2736. trays = ams_unit.get("tray", [])
  2737. for tray_data in trays:
  2738. if not isinstance(tray_data, dict):
  2739. continue
  2740. tray_id_raw = int(tray_data.get("id", 0))
  2741. tray = client.parse_ams_tray(ams_id, tray_data)
  2742. if not tray:
  2743. # Empty tray slot — record for local assignment cleanup
  2744. # and drop any cached unknown-tag broadcast so a
  2745. # reinserted spool re-prompts.
  2746. #
  2747. # Not during a running print: a slot that empties there
  2748. # is a filament runout, and the spool is still in the
  2749. # AMS. `spoolman_slot_assignments` is how a tag-less
  2750. # spool assigned through the Bambuddy UI is resolved at
  2751. # completion (#1459), so deleting the row mid-print
  2752. # loses the runout segment's usage — the same failure
  2753. # the internal inventory's auto-unlink had.
  2754. #
  2755. # Nor when firmware's presence bit says the slot is
  2756. # occupied. parse_ams_tray calls a tray with no type or
  2757. # no colour empty, and a spool the AMS cannot read has
  2758. # neither until something configures it — so a tag-less
  2759. # spool assigned through the UI had its row deleted by
  2760. # the first idle push after it was inserted. Same
  2761. # deletion as the internal inventory's in #3100, same
  2762. # answer, so the two modes stay in step.
  2763. #
  2764. # And only once the slot has stayed empty for the grace
  2765. # period -- the internal inventory's #3186 answer, for
  2766. # the same one-push blank.
  2767. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  2768. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  2769. if not printing_now and (
  2770. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  2771. ):
  2772. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2773. empty_slots.append((ams_id, tray_id_raw))
  2774. else:
  2775. spoolman_held.add(hold_key)
  2776. logger.info(
  2777. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  2778. "unlinking if it is still empty in %ds",
  2779. ams_id,
  2780. tray_id_raw,
  2781. linked_spool,
  2782. int(slot_unlink_grace.GRACE_SECONDS),
  2783. )
  2784. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2785. continue
  2786. spool_tag = (
  2787. tray.tray_uuid
  2788. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2789. else tray.tag_uid
  2790. )
  2791. # Provide the hint only when no RFID is available
  2792. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2793. try:
  2794. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2795. result = await client.sync_ams_tray(
  2796. tray,
  2797. printer_name,
  2798. db,
  2799. # Per-print tracking is the only weight writer (#1119).
  2800. # AMS auto-sync still maintains spool metadata / slot
  2801. # assignments but no longer touches remaining_weight.
  2802. disable_weight_sync=True,
  2803. cached_spools=cached_spools,
  2804. inventory_remaining=inv_remaining,
  2805. spoolman_spool_id_hint=hint,
  2806. auto_add_unknown_rfid=auto_add_unknown_rfid,
  2807. )
  2808. if result is None and spool_tag and not auto_add_unknown_rfid:
  2809. # Spoolman skipped auto-create per user setting — surface
  2810. # the slot so the UI can offer "+ Add to inventory".
  2811. await _broadcast_unknown_tag(
  2812. printer_id=printer_id,
  2813. ams_id=ams_id,
  2814. tray_id=tray.tray_id,
  2815. tag_uid=tray.tag_uid or "",
  2816. tray_uuid=tray.tray_uuid or "",
  2817. tray_type=tray.tray_type,
  2818. tray_color=tray.tray_color,
  2819. tray_sub_brands=tray.tray_sub_brands,
  2820. tray_count=len(trays),
  2821. )
  2822. elif result:
  2823. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  2824. if result:
  2825. synced += 1
  2826. if result.get("id"):
  2827. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  2828. # If a new spool was created, add it to the cache
  2829. # so subsequent trays can find it if they reference the same tag
  2830. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  2831. if not spool_exists:
  2832. cached_spools.append(result)
  2833. logger.debug(
  2834. "[Printer %s] Added newly created spool %s to cache",
  2835. printer_id,
  2836. result["id"],
  2837. )
  2838. # Reconcile slot_preset_mappings (the same row internal
  2839. # mode keeps in sync via inventory + spool_tag_matcher).
  2840. # Without this the slot card surfaces the previous spool's
  2841. # preset name — same bug shape, different inventory mode.
  2842. from backend.app.services.slot_preset_writer import (
  2843. upsert_slot_preset_for_spoolman_spool,
  2844. )
  2845. await upsert_slot_preset_for_spoolman_spool(
  2846. db=db,
  2847. spoolman_spool=result,
  2848. tray_info_idx=tray.tray_info_idx or "",
  2849. tray_sub_brands=tray.tray_sub_brands or "",
  2850. tray_type=tray.tray_type or "",
  2851. printer_id=printer_id,
  2852. ams_id=ams_id,
  2853. tray_id=tray.tray_id,
  2854. )
  2855. except Exception as e:
  2856. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  2857. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  2858. if synced > 0:
  2859. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  2860. # Persist slot assignment changes to the local table
  2861. if slot_changes or empty_slots:
  2862. try:
  2863. for ams_id, tray_id, spool_id in slot_changes:
  2864. await db.execute(
  2865. text(
  2866. "INSERT INTO spoolman_slot_assignments"
  2867. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  2868. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  2869. " ON CONFLICT(printer_id, ams_id, tray_id)"
  2870. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  2871. ),
  2872. {
  2873. "printer_id": printer_id,
  2874. "ams_id": ams_id,
  2875. "tray_id": tray_id,
  2876. "spool_id": spool_id,
  2877. },
  2878. )
  2879. for ams_id, tray_id in empty_slots:
  2880. await db.execute(
  2881. delete(SpoolmanSlotAssignment).where(
  2882. SpoolmanSlotAssignment.printer_id == printer_id,
  2883. SpoolmanSlotAssignment.ams_id == ams_id,
  2884. SpoolmanSlotAssignment.tray_id == tray_id,
  2885. )
  2886. )
  2887. await db.commit()
  2888. except Exception as e:
  2889. await db.rollback()
  2890. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  2891. else:
  2892. # Tell open browsers the slot changed. This loop rewrites
  2893. # slot_preset_mappings via upsert_slot_preset_for_spoolman_spool
  2894. # above, and the AMS slot card reads that row ahead of the
  2895. # live tray_info_idx -- so with no event the card keeps
  2896. # showing the previous spool's preset name. Internal mode
  2897. # raises spool_auto_assigned for the same reason; this loop
  2898. # broadcast nothing at all, which made Spoolman mode the
  2899. # worse half of the same bug. On the else branch so a
  2900. # failed commit stays silent and a broadcast failure cannot
  2901. # roll back rows that are already committed.
  2902. for ams_id, tray_id, *_ in (*slot_changes, *empty_slots):
  2903. await ws_manager.broadcast(
  2904. {
  2905. "type": "spool_assignment_changed",
  2906. "printer_id": printer_id,
  2907. "ams_id": ams_id,
  2908. "tray_id": tray_id,
  2909. }
  2910. )
  2911. except Exception as e:
  2912. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  2913. # Largest finish photo attached to a notification; a bigger one is still linked.
  2914. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  2915. async def _finish_photo_for_notification(
  2916. db, archive, archive_id: int, filename: str
  2917. ) -> tuple[str | None, bytes | None]:
  2918. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  2919. With authentication off the link is the archive's own photo route, as it
  2920. always was: it opens without a login and doesn't expire. With
  2921. authentication on that route needs a media token, which nothing tapping a
  2922. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  2923. link only ever answered 401. The photo is then saved as a notification
  2924. photo as well (utils/notification_photos.py) and the link points there: an
  2925. unguessable name that opens this one photo and nothing else, for 3 days.
  2926. The link is relative when no External URL is set. Bytes over
  2927. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  2928. ``(None, None)`` when the photo can't be found.
  2929. """
  2930. from backend.app.api.routes.settings import get_setting
  2931. from backend.app.core.auth import is_auth_enabled
  2932. from backend.app.utils.archive_paths import find_archive_photo
  2933. from backend.app.utils.notification_photos import save_notification_photo
  2934. log = logging.getLogger(__name__)
  2935. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  2936. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  2937. photo_bytes: bytes | None = None
  2938. try:
  2939. photo_path = find_archive_photo(archive, filename)
  2940. if photo_path is not None:
  2941. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  2942. except Exception as e:
  2943. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  2944. try:
  2945. auth_on = await is_auth_enabled(db)
  2946. except Exception:
  2947. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  2948. if auth_on:
  2949. url = None
  2950. if photo_bytes:
  2951. try:
  2952. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  2953. url = f"{base}/api/v1/notifications/photos/{name}"
  2954. except Exception as e:
  2955. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  2956. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  2957. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  2958. return url, None
  2959. if photo_bytes:
  2960. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  2961. return url, photo_bytes
  2962. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  2963. """Capture a camera snapshot for notification image attachment.
  2964. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  2965. Uses: external camera > buffered frame > fresh capture.
  2966. Turns the chamber light on for the picture when the printer asks for it
  2967. (#1655). ``light=False`` is for callers that capture all through a print,
  2968. where the light would flash with every frame.
  2969. """
  2970. if not printer:
  2971. return None
  2972. async with camera_light(printer if light else None):
  2973. return await _capture_snapshot_frame(printer_id, printer, logger)
  2974. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  2975. """The capture behind ``_capture_snapshot_for_notification``."""
  2976. try:
  2977. from backend.app.api.routes.settings import get_setting
  2978. async with async_session() as db:
  2979. capture_enabled = await get_setting(db, "capture_finish_photo")
  2980. if capture_enabled is not None and capture_enabled.lower() != "true":
  2981. return None
  2982. # Try external camera first
  2983. if printer.external_camera_enabled and printer.external_camera_url:
  2984. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  2985. from backend.app.api.routes.camera import live_frame_for_capture
  2986. from backend.app.services.external_camera import capture_frame
  2987. # An external camera allows one reader, so capturing while a viewer
  2988. # is attached fails (#2707). A None here falls through to the paths
  2989. # below exactly as a failed capture did.
  2990. defer, buffered = live_frame_for_capture(printer_id)
  2991. if defer:
  2992. frame_data = buffered
  2993. else:
  2994. frame_data = await capture_frame(
  2995. printer.external_camera_url,
  2996. printer.external_camera_type or "mjpeg",
  2997. snapshot_url=printer.external_camera_snapshot_url,
  2998. )
  2999. if frame_data and len(frame_data) <= 2_500_000:
  3000. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3001. return _apply_camera_rotation(frame_data, printer, logger)
  3002. # Try buffered frame from active stream
  3003. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3004. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3005. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3006. buffered_frame = get_buffered_frame(printer_id)
  3007. if (active_for_printer or active_chamber) and buffered_frame:
  3008. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3009. if len(buffered_frame) <= 2_500_000:
  3010. return _apply_camera_rotation(buffered_frame, printer, logger)
  3011. # Fresh capture from printer camera
  3012. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3013. from backend.app.services.camera import capture_camera_frame_bytes
  3014. frame_data = await capture_camera_frame_bytes(
  3015. printer.ip_address, printer.access_code, printer.model, timeout=15
  3016. )
  3017. if frame_data and len(frame_data) <= 2_500_000:
  3018. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3019. return _apply_camera_rotation(frame_data, printer, logger)
  3020. except Exception as e:
  3021. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3022. return None
  3023. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3024. """#1867: bank a recent in-print camera frame for the finish photo.
  3025. Called on every layer change and (#2547) on every print-progress advance.
  3026. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3027. path has a pre-End-G-code image for prints that end with a plate swap.
  3028. Both drivers are print telemetry that stops the instant printing ends: no
  3029. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3030. plate swap) executes. So the last banked frame is always the finished print,
  3031. never the swapped plate — that property is what the #1867 path relies on and
  3032. it must survive any change to the throttle below.
  3033. Layer changes alone were not enough: they stop when the *final* layer
  3034. begins, which on a three-minute last layer left the bank stale by the whole
  3035. length of that layer (#2547). Progress keeps ticking through it.
  3036. Best-effort: any failure just leaves the previous banked frame.
  3037. """
  3038. logger = logging.getLogger(__name__)
  3039. client = printer_manager.get_client(printer_id)
  3040. state = client.state if client else None
  3041. if not state or state.state != "RUNNING":
  3042. return
  3043. # Only during actual extrusion — firmware ticks layer_num during the
  3044. # pre-print calibration sequence, whose sub-stages are non-zero.
  3045. if state.mc_print_sub_stage not in (None, 0):
  3046. return
  3047. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3048. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3049. # now that progress advances also drive banking, that exemption would fire a
  3050. # camera grab on every percent tick of the last layer. Bambu printers accept
  3051. # one RTSP client at a time, so each grab contends with the live view.
  3052. now = time.monotonic()
  3053. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3054. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3055. return
  3056. total = state.total_layers or 0
  3057. try:
  3058. async with async_session() as db:
  3059. from backend.app.models.printer import Printer
  3060. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3061. printer = result.scalar_one_or_none()
  3062. if not printer:
  3063. return
  3064. # Reuses the notification snapshot path, which honours the
  3065. # `capture_finish_photo` setting (returns None when disabled) so we
  3066. # don't bank frames the user never asked for. Without the chamber light
  3067. # (#1655): this runs every 25 seconds for the whole print.
  3068. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3069. if frame:
  3070. _inprint_frame_bank[printer_id] = frame
  3071. _inprint_frame_bank_ts[printer_id] = now
  3072. logger.debug(
  3073. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3074. printer_id,
  3075. layer_num,
  3076. total,
  3077. len(frame),
  3078. )
  3079. except Exception as e:
  3080. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3081. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3082. """Apply camera rotation to snapshot image if configured."""
  3083. from backend.app.services.camera import apply_camera_rotation
  3084. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3085. async def _send_print_start_notification(
  3086. printer_id: int,
  3087. data: dict,
  3088. archive_data: dict | None = None,
  3089. logger=None,
  3090. ):
  3091. """Helper to send print start notification with optional archive data."""
  3092. if logger is None:
  3093. logger = logging.getLogger(__name__)
  3094. try:
  3095. async with async_session() as db:
  3096. from backend.app.models.printer import Printer
  3097. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3098. printer = result.scalar_one_or_none()
  3099. printer_name = printer.name if printer else f"Printer {printer_id}"
  3100. # Capture camera snapshot for notification image attachment
  3101. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3102. if image_data:
  3103. if archive_data is None:
  3104. archive_data = {}
  3105. archive_data["image_data"] = image_data
  3106. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3107. # Send user-specific email notification for print start
  3108. if archive_data and archive_data.get("created_by_id"):
  3109. await notification_service.send_user_print_email(
  3110. event_type="user_print_start",
  3111. created_by_id=archive_data["created_by_id"],
  3112. printer_name=printer_name,
  3113. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3114. db=db,
  3115. )
  3116. except Exception as e:
  3117. logger.warning("Notification on_print_start failed: %s", e)
  3118. async def _dispatch_user_print_email(
  3119. status: str,
  3120. created_by_id: int | None,
  3121. printer_name: str,
  3122. filename: str,
  3123. db,
  3124. image_data: bytes | None = None,
  3125. finish_photo_url: str | None = None,
  3126. ) -> None:
  3127. """Send a user-specific print-completion email based on print status.
  3128. Maps the normalised print status to the correct event type and delegates
  3129. to :meth:`NotificationService.send_user_print_email`. A single helper
  3130. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3131. "stopped"`` dispatch block at every call site.
  3132. Does nothing if *created_by_id* is ``None``.
  3133. """
  3134. if created_by_id is None:
  3135. return
  3136. if status == "completed":
  3137. event_type = "user_print_complete"
  3138. elif status == "failed":
  3139. event_type = "user_print_failed"
  3140. elif status in ("stopped", "aborted", "cancelled"):
  3141. event_type = "user_print_stopped"
  3142. else:
  3143. return
  3144. await notification_service.send_user_print_email(
  3145. event_type=event_type,
  3146. created_by_id=created_by_id,
  3147. printer_name=printer_name,
  3148. filename=filename,
  3149. db=db,
  3150. image_data=image_data,
  3151. finish_photo_url=finish_photo_url,
  3152. )
  3153. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3154. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3155. try:
  3156. from backend.app.services.archive import extract_printable_objects_from_archive
  3157. client = printer_manager.get_client(printer_id)
  3158. if not client:
  3159. return
  3160. # Extract with positions for UI overlay, scoped to the plate that
  3161. # is printing — resolve_plate_id is the same resolver /cover uses,
  3162. # so the object list can't disagree with the thumbnail it is drawn
  3163. # over (#2522).
  3164. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3165. app_settings.base_dir / archive.file_path,
  3166. plate_number=resolve_plate_id(client.state),
  3167. )
  3168. if printable_objects:
  3169. client.state.printable_objects = printable_objects
  3170. client.state.printable_objects_bbox_all = bbox_all
  3171. client.state.skipped_objects = []
  3172. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3173. except Exception as e:
  3174. logger.debug("Failed to extract printable objects from archive: %s", e)
  3175. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3176. """Put the skip-objects list back after a restart mid-print.
  3177. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3178. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3179. which the #1304 guard suppresses on the first RUNNING push after startup.
  3180. Everything else this hook restores (the archive, the usage-tracking session,
  3181. the timelapse baseline) was already handled; the object list was not, so a
  3182. restart mid-print took skip-objects away for the rest of that print.
  3183. Nothing recovered it either: the printer card gates its Skip button on the
  3184. object count, and the one endpoint that can rebuild the list is reachable
  3185. only from the modal that button opens.
  3186. Anchored on ``subtask_id``, which the firmware mints per print, so a
  3187. leftover ``status="printing"`` row from a completion we never saw cannot
  3188. hand this print someone else's objects. Without one, nothing is loaded
  3189. rather than guessed — the reload path on ``GET /print/objects`` covers that
  3190. case on demand.
  3191. """
  3192. client = printer_manager.get_client(printer_id)
  3193. if client is None or client.state.printable_objects:
  3194. return
  3195. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  3196. if subtask_id in ("", "0"):
  3197. return
  3198. from backend.app.models.archive import PrintArchive
  3199. archive = await db.scalar(
  3200. select(PrintArchive)
  3201. .where(
  3202. PrintArchive.printer_id == printer_id,
  3203. PrintArchive.status == "printing",
  3204. PrintArchive.subtask_id == subtask_id,
  3205. )
  3206. .order_by(PrintArchive.created_at.desc())
  3207. .limit(1)
  3208. )
  3209. if archive is not None:
  3210. _load_objects_from_archive(archive, printer_id, logger)
  3211. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3212. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3213. # past it; the second covers a handshake that failed again on the way back and
  3214. # armed a fresh one. Module-level so tests can shrink them.
  3215. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3216. # Retry ladder for the other temporary give-up: the file service answered and
  3217. # the transfer still did not finish, which at print start is usually the printer
  3218. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3219. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3220. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3221. # two cover a printer that stays busy well into the print.
  3222. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3223. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3224. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3225. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3226. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3227. # by view, so two views race), the cool-off retry task, and print completion.
  3228. # Without this they each read file_path == "" and each run a full copy, so the row
  3229. # ends up pointing at one timestamped directory while the others sit orphaned.
  3230. #
  3231. # Keyed by printer rather than archive because a printer runs one print at a time,
  3232. # which makes the two equally strong here — and it bounds the dict by printer
  3233. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3234. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3235. # resuming, so "no waiters" is not a question this API can answer.
  3236. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3237. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3238. """Fill in a no-3MF archive from a 3MF that turned up later.
  3239. Returns True when the row was upgraded. Safe to call speculatively: it
  3240. verifies the archive still exists, is still a fallback, and that the file
  3241. is a readable 3MF before touching anything.
  3242. Serialised per printer — see ``_fallback_recovery_locks``.
  3243. """
  3244. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3245. async with lock:
  3246. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id)
  3247. async def _recover_fallback_archive_locked(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3248. """The body of :func:`_recover_fallback_archive`, under its per-printer lock."""
  3249. import zipfile
  3250. from backend.app.models.archive import PrintArchive
  3251. from backend.app.services.archive import ArchiveService
  3252. logger = logging.getLogger(__name__)
  3253. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3254. return False
  3255. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3256. # A truncated or half-written download is worse than no download: it
  3257. # would replace an honest empty archive with wrong metadata.
  3258. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3259. return False
  3260. async with async_session() as db:
  3261. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3262. if archive is None or archive.deleted_at is not None:
  3263. return False
  3264. if archive.file_path:
  3265. # Already recovered, or never was a fallback. Either way there is a
  3266. # real 3MF attached and overwriting it is not this function's job.
  3267. return False
  3268. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3269. service = ArchiveService(db)
  3270. recovered = await service.archive_print(
  3271. printer_id=printer_id,
  3272. source_file=source_3mf,
  3273. print_data={**print_data, "status": archive.status or "printing"},
  3274. subtask_id=archive.subtask_id,
  3275. update_archive_id=archive.id,
  3276. )
  3277. if recovered is None:
  3278. return False
  3279. logger.info(
  3280. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3281. archive_id,
  3282. source_3mf,
  3283. recovered.file_size,
  3284. )
  3285. # `archive_updated`, not `archive_created` — the row was already on the
  3286. # Archives page as an empty card and is now filled in, not new.
  3287. await ws_manager.send_archive_updated(
  3288. {
  3289. "id": recovered.id,
  3290. "printer_id": recovered.printer_id,
  3291. "filename": recovered.filename,
  3292. "print_name": recovered.print_name,
  3293. "status": recovered.status,
  3294. }
  3295. )
  3296. return True
  3297. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path) -> bool:
  3298. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3299. Called from the paths that pull a 3MF for a print that is already under way
  3300. — chiefly the cover endpoint, which downloads the very file the archive flow
  3301. could not get and, before #2957, used it for a thumbnail and nothing else.
  3302. The bytes are already local, so this costs a parse and a row update.
  3303. No-op when the running print has a real archive, which is the common case.
  3304. """
  3305. from backend.app.models.archive import PrintArchive
  3306. logger = logging.getLogger(__name__)
  3307. # `_active_prints` is keyed on the raw names seen at print start — the
  3308. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3309. # Callers here arrive with whichever variant their own path produced, so
  3310. # match on the same normalization the download cache uses rather than on an
  3311. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3312. # endpoint find an archive registered under "Desktop_Goose".
  3313. wanted = normalize_3mf_name(name)
  3314. archive_id = None
  3315. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3316. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3317. archive_id = value
  3318. break
  3319. if archive_id is None:
  3320. return False
  3321. async with async_session() as db:
  3322. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3323. # Cheap pre-check so the common case (a normal archive) does no work.
  3324. if archive is None or archive.file_path or archive.deleted_at is not None:
  3325. return False
  3326. try:
  3327. return await _recover_fallback_archive(archive_id, path, printer_id)
  3328. except Exception as e:
  3329. # Recovery is opportunistic. A failure here must never take down the
  3330. # caller, which is usually just trying to render a thumbnail.
  3331. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3332. return False
  3333. def _schedule_fallback_3mf_retry(
  3334. printer_id: int,
  3335. archive_id: int,
  3336. filenames: list[str],
  3337. delays: tuple[float, ...] | None = None,
  3338. reason: str = REASON_FTPS_COOLOFF,
  3339. ) -> None:
  3340. """Re-attempt the 3MF download after a temporary give-up.
  3341. ``reason`` says which give-up this is, and picks the default ladder: an
  3342. FTPS cool-off has to be waited out, while a transfer that timed out under
  3343. contention is worth asking about again straight away (#3063). It is only
  3344. read for the ladder and the log line -- the retry itself is identical, since
  3345. in both cases the file is on the printer and the last attempt at it failed
  3346. for a reason that does not last.
  3347. """
  3348. logger = logging.getLogger(__name__)
  3349. if delays is None:
  3350. delays = (
  3351. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3352. if reason == REASON_FTP_TRANSFER_FAILED
  3353. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3354. )
  3355. async def _retry() -> None:
  3356. from backend.app.models.archive import PrintArchive
  3357. from backend.app.models.printer import Printer
  3358. for delay in delays:
  3359. await asyncio.sleep(delay)
  3360. async with async_session() as db:
  3361. archive = (
  3362. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3363. ).scalar_one_or_none()
  3364. if archive is None or archive.deleted_at is not None or archive.file_path:
  3365. return
  3366. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3367. if printer is None:
  3368. return
  3369. # Read the fields while the session is open rather than touching
  3370. # a detached instance minutes later, mid-download.
  3371. printer_ip = printer.ip_address
  3372. printer_code = printer.access_code
  3373. printer_model = printer.model
  3374. # Someone else may have fetched it in the meantime — the cover
  3375. # endpoint routinely does, and its copy is the same bytes.
  3376. for name in filenames:
  3377. cached = get_cached_3mf(printer_id, name)
  3378. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3379. return
  3380. if ftps_handshake_blocked(printer_ip):
  3381. logger.info(
  3382. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3383. printer_id,
  3384. archive_id,
  3385. )
  3386. continue
  3387. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3388. for candidate in filenames:
  3389. # Bare name only. These come from the print-start flow, which
  3390. # already strips the path, but the local temp write must not
  3391. # depend on that holding for every future caller — a name that
  3392. # is absolute or contains ".." would otherwise escape the data
  3393. # volume via the `/` operator.
  3394. name = Path(candidate).name
  3395. if not name or name in (".", ".."):
  3396. continue
  3397. if not name.endswith(".3mf"):
  3398. name = f"{name}.3mf"
  3399. temp_path = app_settings.archive_dir / "temp" / name
  3400. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3401. try:
  3402. hit = await download_file_try_paths_async(
  3403. printer_ip,
  3404. printer_code,
  3405. ftp_probe_paths(name),
  3406. temp_path,
  3407. socket_timeout=ftp_timeout,
  3408. printer_model=printer_model,
  3409. )
  3410. except Exception as e:
  3411. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3412. continue
  3413. if not hit:
  3414. continue
  3415. cache_3mf_download(printer_id, name, temp_path)
  3416. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3417. return
  3418. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3419. async def _guarded() -> None:
  3420. try:
  3421. await _retry()
  3422. except asyncio.CancelledError:
  3423. raise
  3424. except Exception as e:
  3425. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3426. finally:
  3427. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3428. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3429. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3430. if existing and not existing.done():
  3431. existing.cancel()
  3432. task = asyncio.create_task(_guarded())
  3433. _fallback_3mf_retry_tasks[printer_id] = task
  3434. logger.info(
  3435. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3436. archive_id,
  3437. reason,
  3438. printer_id,
  3439. ", ".join(f"{d:g}s" for d in delays),
  3440. )
  3441. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3442. """Whether an archive created here should ask for the print's outcome (#1898).
  3443. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3444. branches below: a queued job already has its archive and takes the
  3445. expected-print branch, where the queue item's own ``confirm_outcome``
  3446. decides. The queue is still consulted, because a restart mid-print empties
  3447. ``_expected_prints`` — without the check the setting could override a queue
  3448. item that deliberately has the flag off. Any failure answers "don't ask":
  3449. an unwanted prompt is worse than a missing one, and this must never be the
  3450. reason a print goes unarchived.
  3451. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3452. leaves one behind when a completion cannot be matched to it
  3453. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3454. only takes it back once the printer has sat connected and terminal for
  3455. minutes. Until then every screen-started print on that printer would
  3456. silently lose its prompt, so the row is held against ``observed_name`` by
  3457. the same comparison a completion uses: a positive disagreement means the row
  3458. is about some other run and this print is external after all.
  3459. """
  3460. logger = logging.getLogger(__name__)
  3461. try:
  3462. # A savepoint rather than a rollback of the caller's transaction on
  3463. # failure: a failed statement leaves the transaction unusable, but a
  3464. # full rollback also expires every object the caller has loaded (the
  3465. # printer, the archive it just created), and on an async session the
  3466. # next attribute read then raises instead of reloading. Everything here
  3467. # is a read, so undoing the savepoint loses nothing.
  3468. async with db.begin_nested():
  3469. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3470. except Exception as e:
  3471. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3472. return False
  3473. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3474. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3475. from backend.app.api.routes.settings import get_setting, setting_is_true
  3476. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3477. return False
  3478. from backend.app.models.print_queue import PrintQueueItem
  3479. dispatched_here = await db.scalar(
  3480. select(PrintQueueItem)
  3481. .where(
  3482. PrintQueueItem.printer_id == printer_id,
  3483. PrintQueueItem.status == "printing",
  3484. )
  3485. .limit(1)
  3486. )
  3487. if dispatched_here is None:
  3488. return True
  3489. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3490. observed = (observed_name or "").strip()
  3491. if not expected or not observed or _subtask_names_match(expected, observed):
  3492. logger.info(
  3493. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3494. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3495. printer_id,
  3496. dispatched_here.id,
  3497. )
  3498. return False
  3499. logger.info(
  3500. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3501. "%r; treating this as an externally started print.",
  3502. dispatched_here.id,
  3503. printer_id,
  3504. expected,
  3505. observed,
  3506. )
  3507. return True
  3508. async def _dispatch_outcome_confirmation_safely(
  3509. db,
  3510. printer_id: int,
  3511. printer_name: str,
  3512. data: dict,
  3513. archive_id: int,
  3514. archive_data: dict | None = None,
  3515. ) -> None:
  3516. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  3517. The completion task sends the per-user print email on the same session
  3518. right after the prompt. A failed statement in the prompt leaves that
  3519. session needing a rollback, and without one the email step fails with
  3520. PendingRollbackError; the prompt is the optional part, so it must not be
  3521. the reason the email never goes out.
  3522. """
  3523. try:
  3524. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data)
  3525. except Exception as e:
  3526. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  3527. try:
  3528. await db.rollback()
  3529. except Exception:
  3530. pass
  3531. async def dispatch_outcome_confirmation(
  3532. db,
  3533. printer_id: int,
  3534. printer_name: str,
  3535. data: dict,
  3536. archive_id: int,
  3537. archive_data: dict | None = None,
  3538. ) -> bool:
  3539. """Emit the post-print outcome prompt for a completed archive (#1898).
  3540. Gated on the archive itself: ``confirm_requested`` is the opt-in (from the
  3541. queue item, or from ``confirm_outcome_external_prints`` for a print
  3542. Bambuddy did not start) and ``user_verdict`` being unset is what makes the
  3543. question still open. Mints the per-archive capability token the one-tap
  3544. verdict links carry.
  3545. Lives here rather than inline in ``on_print_complete``'s notification task
  3546. because that task swallows every exception: extracted, the gate and the two
  3547. emissions can be driven by a test, which is the only thing standing between
  3548. a regression here and a farm that quietly stops asking.
  3549. Returns whether a prompt was sent.
  3550. """
  3551. logger = logging.getLogger(__name__)
  3552. from backend.app.models.archive import PrintArchive
  3553. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3554. if not (confirm_archive and confirm_archive.confirm_requested and confirm_archive.user_verdict is None):
  3555. return False
  3556. import secrets as _secrets
  3557. # A spent token stays on the row so the one-tap route can recognise it, so
  3558. # "has a token" no longer means "answerable". A prompt going out now needs a
  3559. # live one: mint a new token whenever the stored one is already spent, or
  3560. # every button in the new message would land on the already-answered page.
  3561. if not confirm_archive.confirm_token or confirm_archive.confirm_token_used_at is not None:
  3562. confirm_archive.confirm_token = _secrets.token_urlsafe(32)
  3563. confirm_archive.confirm_token_used_at = None
  3564. await db.commit()
  3565. from backend.app.api.routes.settings import get_external_base_url, get_setting
  3566. base = await get_external_base_url(db)
  3567. if not await get_setting(db, "external_url"):
  3568. # Both the Telegram inline keyboard and the ntfy action buttons need an
  3569. # absolute URL, so an unconfigured install used to get a message body
  3570. # with two unusable relative paths and no buttons at all. The shared
  3571. # fallback at least produces tappable links; say which setting makes
  3572. # them resolve from a phone.
  3573. logger.warning(
  3574. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  3575. "Set Settings → External URL so they resolve away from this host.",
  3576. base,
  3577. )
  3578. token = confirm_archive.confirm_token
  3579. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  3580. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  3581. confirm_url = f"{base}/archives?confirm={archive_id}"
  3582. await ws_manager.send_print_confirm_request(
  3583. printer_id,
  3584. {
  3585. "archive_id": archive_id,
  3586. "print_name": confirm_archive.print_name or confirm_archive.filename,
  3587. },
  3588. )
  3589. await notification_service.on_print_confirm_request(
  3590. printer_id,
  3591. printer_name,
  3592. data,
  3593. db,
  3594. archive_data=archive_data,
  3595. good_url=good_url,
  3596. reject_url=reject_url,
  3597. confirm_url=confirm_url,
  3598. archive_id=archive_id,
  3599. )
  3600. return True
  3601. async def on_print_start(printer_id: int, data: dict):
  3602. """Handle print start - archive the 3MF file immediately."""
  3603. logger = logging.getLogger(__name__)
  3604. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  3605. # Clear any stale user-stopped flag from previous print cycles
  3606. _user_stopped_printers.discard(printer_id)
  3607. # A new print starts its milestones from zero (#3211). The status path only
  3608. # resets on progress below 5 while not printing, which a printer that goes
  3609. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  3610. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  3611. # or on resume from pause, so it cannot repeat a milestone mid-print.
  3612. _last_progress_milestone[printer_id] = 0
  3613. _kill_switch_notification_tasks.pop(printer_id, None)
  3614. # #1721: drop any leftover pre-captured finish frame from a prior print
  3615. # so a never-consumed cache entry can't bleed into the new print's photo.
  3616. _stage22_finish_frames.pop(printer_id, None)
  3617. # #1867: same for the in-print frame bank — a queued print must not reuse
  3618. # the previous job's banked frame.
  3619. _inprint_frame_bank.pop(printer_id, None)
  3620. _inprint_frame_bank_ts.pop(printer_id, None)
  3621. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  3622. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  3623. # print's flag instead of inheriting it.
  3624. print_dispatch_context.adopt(printer_id)
  3625. # Cancel any active bed cooldown waiter for this printer
  3626. if _bed_cool_waiters.pop(printer_id, None):
  3627. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  3628. # Clear cached cover images so the new print's thumbnail is fetched fresh
  3629. from backend.app.api.routes.printers import clear_cover_cache
  3630. clear_cover_cache(printer_id)
  3631. await ws_manager.send_print_start(printer_id, data)
  3632. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  3633. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  3634. # MQTT relay - publish print start
  3635. try:
  3636. printer_info = printer_manager.get_printer(printer_id)
  3637. if printer_info:
  3638. await mqtt_relay.on_print_start(
  3639. printer_id,
  3640. printer_info.name,
  3641. printer_info.serial_number,
  3642. data.get("filename", ""),
  3643. data.get("subtask_name", ""),
  3644. )
  3645. except Exception:
  3646. pass # Don't fail print start callback if MQTT fails
  3647. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  3648. # and mapping, and the seeded tray-change log.
  3649. #
  3650. # Unconditional, for both inventory backends. This only *captures* — the
  3651. # writing is still split, with the internal tracker skipped at completion
  3652. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  3653. # carries its plate-scoped 3MF figures and stored mapping, but not the
  3654. # tray-change log, and that log is the only record of which spool fed
  3655. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  3656. # it on one side only would leave Spoolman users with the mid-print
  3657. # restart bug this fixes for everyone else.
  3658. try:
  3659. async with async_session() as db:
  3660. from backend.app.api.routes.settings import get_setting
  3661. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  3662. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3663. await usage_on_print_start(
  3664. printer_id,
  3665. data,
  3666. printer_manager,
  3667. db=db,
  3668. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  3669. )
  3670. except Exception as e:
  3671. logger.warning("Usage tracker on_print_start failed: %s", e)
  3672. # Track if notification was sent (to avoid sending twice)
  3673. notification_sent = False
  3674. # Smart plug automation: turn on plug when print starts
  3675. try:
  3676. async with async_session() as db:
  3677. await smart_plug_manager.on_print_start(printer_id, db)
  3678. except Exception as e:
  3679. logger.warning("Smart plug on_print_start failed: %s", e)
  3680. async with async_session() as db:
  3681. from backend.app.models.printer import Printer
  3682. from backend.app.services.bambu_ftp import list_files_async
  3683. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3684. printer = result.scalar_one_or_none()
  3685. # Plate detection check - pause if objects detected on build plate
  3686. logger.info(
  3687. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  3688. )
  3689. if printer and printer.plate_detection_enabled:
  3690. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  3691. # Release the pooled DB connection before the plate-detection camera
  3692. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  3693. # printer SELECT has run so far — nothing to persist — so this commit
  3694. # is a data-noop that ends the read transaction and returns the
  3695. # connection to the pool during the I/O (issue #2572). expire_on_commit
  3696. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  3697. # archive lookups below re-acquire a fresh connection on next execute.
  3698. await db.commit()
  3699. try:
  3700. from backend.app.services.plate_detection import check_plate_empty
  3701. # Build ROI tuple from printer settings if available
  3702. roi = None
  3703. if all(
  3704. [
  3705. printer.plate_detection_roi_x is not None,
  3706. printer.plate_detection_roi_y is not None,
  3707. printer.plate_detection_roi_w is not None,
  3708. printer.plate_detection_roi_h is not None,
  3709. ]
  3710. ):
  3711. roi = (
  3712. printer.plate_detection_roi_x,
  3713. printer.plate_detection_roi_y,
  3714. printer.plate_detection_roi_w,
  3715. printer.plate_detection_roi_h,
  3716. )
  3717. # Auto-turn on chamber light if it's off for better detection
  3718. light_was_off = False
  3719. client = printer_manager.get_client(printer_id)
  3720. if client and client.state:
  3721. light_was_off = not client.state.chamber_light
  3722. if light_was_off:
  3723. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  3724. client.set_chamber_light(True)
  3725. # Wait for light to physically turn on and camera to adjust exposure
  3726. await asyncio.sleep(2.5)
  3727. plate_photo_data = None
  3728. objects_detected = False
  3729. try:
  3730. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  3731. plate_result = await check_plate_empty(
  3732. printer_id=printer_id,
  3733. ip_address=printer.ip_address,
  3734. access_code=printer.access_code,
  3735. model=printer.model,
  3736. include_debug_image=False,
  3737. external_camera_url=printer.external_camera_url,
  3738. external_camera_type=printer.external_camera_type,
  3739. use_external=printer.external_camera_enabled,
  3740. roi=roi,
  3741. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  3742. )
  3743. objects_detected = not plate_result.needs_calibration and not plate_result.is_empty
  3744. if objects_detected:
  3745. # Objects detected - pause the print!
  3746. logger.warning(
  3747. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  3748. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  3749. )
  3750. pause_client = printer_manager.get_client(printer_id)
  3751. if pause_client:
  3752. pause_client.pause_print()
  3753. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  3754. # Snapshot while the light's still on — restoring it first
  3755. # would leave the notification with a dark photo.
  3756. try:
  3757. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3758. except Exception as snap_err:
  3759. logger.warning(
  3760. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  3761. )
  3762. finally:
  3763. # Restore chamber light to original state as soon as the
  3764. # camera is done with it, whatever happened above.
  3765. if light_was_off and client:
  3766. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  3767. try:
  3768. client.set_chamber_light(False)
  3769. except Exception as light_err:
  3770. logger.warning(
  3771. "[PLATE CHECK] Failed to restore chamber light for printer %s: %s",
  3772. printer_id,
  3773. light_err,
  3774. )
  3775. if objects_detected:
  3776. # Send notification about plate not empty
  3777. await ws_manager.broadcast(
  3778. {
  3779. "type": "plate_not_empty",
  3780. "printer_id": printer_id,
  3781. "printer_name": printer.name,
  3782. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  3783. }
  3784. )
  3785. # Also send push notification
  3786. try:
  3787. await notification_service.on_plate_not_empty(
  3788. printer_id=printer_id,
  3789. printer_name=printer.name,
  3790. db=db,
  3791. difference_percent=plate_result.difference_percent,
  3792. image_data=plate_photo_data,
  3793. )
  3794. except Exception as notif_err:
  3795. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  3796. else:
  3797. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  3798. except Exception as plate_err:
  3799. # Don't block print on plate detection errors
  3800. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  3801. if not printer:
  3802. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  3803. if not notification_sent:
  3804. await _send_print_start_notification(printer_id, data, logger=logger)
  3805. return
  3806. if not printer.auto_archive:
  3807. # auto-archive disabled — check if there's an expected print (dispatched
  3808. # by BamBuddy via queue/reprint) that already has an archive to promote.
  3809. # If so, fall through to the expected-print handling below so the archive
  3810. # is tracked in _active_prints and usage tracking works at completion.
  3811. _fn = data.get("filename", "")
  3812. _sn = data.get("subtask_name", "")
  3813. _check_keys: list[tuple[int, str]] = []
  3814. if _sn:
  3815. _check_keys += [
  3816. (printer_id, _sn),
  3817. (printer_id, f"{_sn}.3mf"),
  3818. (printer_id, f"{_sn}.gcode.3mf"),
  3819. ]
  3820. if _fn:
  3821. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  3822. _check_keys.append((printer_id, _base_fn))
  3823. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  3824. _check_keys += [
  3825. (printer_id, _no_archive_base),
  3826. (printer_id, f"{_no_archive_base}.3mf"),
  3827. ]
  3828. _has_expected = any(k in _expected_prints for k in _check_keys)
  3829. if not _has_expected:
  3830. # No expected print — truly external print (started from slicer/touchscreen)
  3831. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  3832. if not notification_sent:
  3833. _no_archive_creator: int | None = None
  3834. for _key in _check_keys:
  3835. _expected_prints.pop(_key, None)
  3836. _expected_print_registered_at.pop(_key, None)
  3837. popped_creator = _expected_print_creators.pop(_key, None)
  3838. if _no_archive_creator is None:
  3839. _no_archive_creator = popped_creator
  3840. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  3841. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  3842. return
  3843. else:
  3844. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  3845. # Get the filename and subtask_name
  3846. filename = data.get("filename", "")
  3847. subtask_name = data.get("subtask_name", "")
  3848. # MQTT subtask_id uniquely identifies a print job on the printer. When
  3849. # present, it lets us match an archive across a backend restart (#972):
  3850. # same id → same print → resume the existing row instead of cancelling
  3851. # it and recreating from scratch (which loses started_at). Treat "0"
  3852. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  3853. raw_mqtt = data.get("raw_data") or {}
  3854. subtask_id = raw_mqtt.get("subtask_id")
  3855. if subtask_id is not None:
  3856. subtask_id = str(subtask_id).strip()
  3857. if subtask_id in ("", "0"):
  3858. subtask_id = None
  3859. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  3860. # Skip the printer's own jobs — a calibration run is not a user's print.
  3861. # See is_internal_printer_job for what counts and why both fields are
  3862. # tested; the pressure-advance line reports as a subtask name with no
  3863. # /usr/ path, which the old prefix-only test here missed entirely.
  3864. #
  3865. # No notification either. The event describes the printer calibrating
  3866. # itself, so "Print started" is as wrong as the archive was, and the
  3867. # matching completion is suppressed in on_print_complete for the same
  3868. # reason.
  3869. if is_internal_printer_job(filename, subtask_name):
  3870. logger.info(
  3871. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  3872. filename,
  3873. subtask_name,
  3874. )
  3875. return
  3876. if not filename and not subtask_name:
  3877. # Send notification without archive data (no filename)
  3878. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  3879. if not notification_sent:
  3880. await _send_print_start_notification(printer_id, data, logger=logger)
  3881. return
  3882. # Check if this is an expected print from reprint/scheduled
  3883. # Build list of possible keys to check
  3884. expected_keys = []
  3885. if subtask_name:
  3886. expected_keys.append((printer_id, subtask_name))
  3887. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  3888. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  3889. if filename:
  3890. fname = filename.split("/")[-1] if "/" in filename else filename
  3891. expected_keys.append((printer_id, fname))
  3892. # Strip extensions to match
  3893. base = fname.replace(".gcode", "").replace(".3mf", "")
  3894. expected_keys.append((printer_id, base))
  3895. expected_keys.append((printer_id, f"{base}.3mf"))
  3896. expected_archive_id = None
  3897. for key in expected_keys:
  3898. expected_archive_id = _expected_prints.pop(key, None)
  3899. _expected_print_registered_at.pop(key, None)
  3900. if expected_archive_id:
  3901. # Clean up other possible keys for this print
  3902. for other_key in expected_keys:
  3903. _expected_prints.pop(other_key, None)
  3904. _expected_print_registered_at.pop(other_key, None)
  3905. break
  3906. if expected_archive_id:
  3907. # This is a reprint/scheduled print - use existing archive, don't create new one
  3908. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  3909. from backend.app.models.archive import PrintArchive
  3910. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  3911. archive = result.scalar_one_or_none()
  3912. if archive:
  3913. # Update archive status to printing
  3914. archive.status = "printing"
  3915. archive.started_at = datetime.now(timezone.utc)
  3916. # The previous run's answer is still on this row and the
  3917. # completion prompt is gated on ``user_verdict is None`` (#1898),
  3918. # so without a reset the second run inherits the first run's
  3919. # verdict: no prompt at all, and a green "good" badge on a run
  3920. # nobody ever judged.
  3921. if archive.confirm_requested:
  3922. archive.user_verdict = None
  3923. archive.user_verdict_source = None
  3924. archive.user_verdict_at = None
  3925. archive.confirm_token = None
  3926. archive.confirm_token_used_at = None
  3927. # Reprint of an archive reuses the source row. Without resetting
  3928. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  3929. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  3930. # extracts the *original* print's last frame, which then ships in
  3931. # the completion notification (#1707). Clear the path so the
  3932. # scanner runs fresh; also unlink the old video file so reprints
  3933. # don't accumulate orphans in the archive directory. Photos list
  3934. # is left alone — accumulating one finish photo per run is fine.
  3935. # The print-start baseline (#2704) is stale for the same reason:
  3936. # it describes the printer before the previous run. The capture
  3937. # below overwrites it, but clear it here too so an early failure
  3938. # can't leave the scan diffing against the wrong snapshot.
  3939. archive.timelapse_baseline = None
  3940. stale_timelapse_relpath = archive.timelapse_path
  3941. if stale_timelapse_relpath:
  3942. archive.timelapse_path = None
  3943. try:
  3944. stale_path = app_settings.base_dir / stale_timelapse_relpath
  3945. if stale_path.is_file():
  3946. stale_path.unlink()
  3947. logger.info(
  3948. "Deleted stale timelapse %s on reprint of archive %s",
  3949. stale_timelapse_relpath,
  3950. expected_archive_id,
  3951. )
  3952. except OSError as e:
  3953. logger.warning(
  3954. "Failed to delete stale timelapse %s on reprint: %s",
  3955. stale_timelapse_relpath,
  3956. e,
  3957. )
  3958. # Persist a restart-stable id so a later restart resumes this
  3959. # archive by subtask_id instead of name-matching + duplicating
  3960. # it (#1485). The printer often hasn't echoed subtask_id back
  3961. # this soon after dispatch, so fall back to the id Bambuddy
  3962. # minted when it sent the print command. Scoped to this
  3963. # expected-print branch on purpose: an expected match means
  3964. # Bambuddy dispatched this exact print in this process, so the
  3965. # client's last-dispatch id genuinely belongs to it — using it
  3966. # for an externally-started print could mis-tag the archive.
  3967. effective_subtask_id = subtask_id
  3968. if not effective_subtask_id:
  3969. _client = printer_manager.get_client(printer_id)
  3970. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  3971. if _dispatched:
  3972. effective_subtask_id = str(_dispatched).strip() or None
  3973. # Update on first-set OR on reprint (the queue dispatcher mints
  3974. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  3975. # the rewrite for reprints leaves the archive holding the FIRST
  3976. # run's id; if MQTT then reconnects mid-print, the reconciler
  3977. # (#1542) compares the stale stored id against the printer's
  3978. # live id, sees a mismatch, and synthesises a bogus PRINT
  3979. # COMPLETE — exactly the false-positive "Print Stopped" reported
  3980. # in #1807. Inequality check preserves the noop-on-stable-push
  3981. # behaviour the earlier `not archive.subtask_id` guard provided.
  3982. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  3983. archive.subtask_id = effective_subtask_id
  3984. # #1403 follow-up: VP-queue archives are created with
  3985. # printer_id=None at queue-add time (we don't know which
  3986. # printer will run the job yet). When the print actually
  3987. # starts on a specific printer the expected-archive lookup
  3988. # used to skip this assignment, leaving printer_id=None
  3989. # forever — which then disables the "Scan for timelapse"
  3990. # button in ArchivesPage (gated on !archive.printer_id).
  3991. if archive.printer_id != printer_id:
  3992. archive.printer_id = printer_id
  3993. await db.commit()
  3994. # Track as active print
  3995. _active_prints[(printer_id, archive.filename)] = archive.id
  3996. if subtask_name:
  3997. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  3998. # Start timelapse session if external camera is enabled (#1353).
  3999. # Queue / VP-dispatched prints land here in the expected-archive
  4000. # branch and used to skip start_session entirely — frames were
  4001. # never captured and the post-print stitch silently returned None.
  4002. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4003. # Inject ams_mapping into usage tracker session — the session was created
  4004. # before expected-print promotion, so it may have ams_mapping=None when
  4005. # the MQTT request topic subscription failed (common on P1S/A1).
  4006. _stored_map = _print_ams_mappings.get(expected_archive_id)
  4007. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  4008. if _stored_map or _stored_plate_id is not None:
  4009. try:
  4010. from backend.app.services.usage_tracker import _active_sessions
  4011. _ut_session = _active_sessions.get(printer_id)
  4012. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4013. _ut_session.ams_mapping = _stored_map
  4014. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4015. # plate_id injection covers direct-Print of plate N of a multi-plate
  4016. # 3MF — queue prints already capture it via the on_print_start queue
  4017. # lookup, but direct-Print never goes through the queue (#1697).
  4018. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4019. _ut_session.plate_id = _stored_plate_id
  4020. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4021. except Exception:
  4022. pass
  4023. # Set up energy tracking (#941: persist start on archive row)
  4024. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4025. await ws_manager.send_archive_updated(
  4026. {
  4027. "id": archive.id,
  4028. "status": "printing",
  4029. }
  4030. )
  4031. # Send notification with archive data (reprint/scheduled)
  4032. if not notification_sent:
  4033. # Use archive's created_by_id; fall back to the creator registered via
  4034. # register_expected_print (handles library-file-based queue items where
  4035. # the freshly-created archive has no created_by_id yet).
  4036. # Pop ALL matching keys so no stale entries remain in the dict.
  4037. fallback_creator = None
  4038. for key in expected_keys:
  4039. popped = _expected_print_creators.pop(key, None)
  4040. if fallback_creator is None:
  4041. fallback_creator = popped
  4042. archive_data = {
  4043. "print_time_seconds": archive.print_time_seconds,
  4044. "created_by_id": archive.created_by_id or fallback_creator,
  4045. }
  4046. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4047. # Extract printable objects from the archived 3MF file
  4048. _load_objects_from_archive(archive, printer_id, logger)
  4049. # Store Spoolman tracking data for per-filament usage reporting
  4050. try:
  4051. await _store_spoolman_print_data(
  4052. printer_id,
  4053. archive.id,
  4054. archive.file_path,
  4055. db,
  4056. printer_manager,
  4057. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4058. plate_id=_get_start_plate_id(archive.id),
  4059. )
  4060. except Exception as e:
  4061. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4062. # Price the print from its spools now rather than only at completion (#3261)
  4063. _schedule_archive_cost_estimate(
  4064. printer_id,
  4065. archive.id,
  4066. printer_manager,
  4067. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4068. plate_id=_get_start_plate_id(archive.id),
  4069. session_factory=async_session,
  4070. )
  4071. # Capture timelapse file baseline for snapshot-diff on completion
  4072. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4073. # hit this branch — without the baseline the completion-time scan
  4074. # falls into its "take baseline now" fallback, which snapshots
  4075. # AFTER the new MP4 already exists and never matches a diff
  4076. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4077. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4078. return # Skip creating a new archive
  4079. # Check if there's already a "printing" archive for this printer/file
  4080. # This prevents duplicates when backend restarts during an active print
  4081. from backend.app.models.archive import PrintArchive
  4082. existing_archive: PrintArchive | None = None
  4083. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4084. # across a backend restart for the same print, so this is the most
  4085. # reliable way to reattach. We also accept a previously stale-cancelled
  4086. # archive here so users upgrading mid-print get revived when the row
  4087. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  4088. if subtask_id:
  4089. by_id = await db.execute(
  4090. select(PrintArchive)
  4091. .where(PrintArchive.printer_id == printer_id)
  4092. .where(PrintArchive.subtask_id == subtask_id)
  4093. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  4094. .order_by(PrintArchive.created_at.desc())
  4095. .limit(1)
  4096. )
  4097. candidate = by_id.scalar_one_or_none()
  4098. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  4099. existing_archive = candidate
  4100. # Fallback match: name-based lookup. Kept as-is for prints whose
  4101. # subtask_id is missing ("0" / local / non-cloud prints).
  4102. if existing_archive is None:
  4103. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4104. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4105. # A print started from the printer's screen names its file in full,
  4106. # so the forms above double its extension. The file itself is the
  4107. # one exact match, and nothing looser is added (#3009).
  4108. if _subtask_is_the_file(subtask_name, filename):
  4109. archive_filenames.append(subtask_name)
  4110. existing = await db.execute(
  4111. select(PrintArchive)
  4112. .where(PrintArchive.printer_id == printer_id)
  4113. .where(PrintArchive.status == "printing")
  4114. .where(
  4115. or_(
  4116. PrintArchive.print_name == check_name,
  4117. PrintArchive.filename.in_(archive_filenames),
  4118. )
  4119. )
  4120. .order_by(PrintArchive.created_at.desc())
  4121. .limit(1)
  4122. )
  4123. existing_archive = existing.scalar_one_or_none()
  4124. if existing_archive:
  4125. # subtask_id match → always resume, regardless of age. Same print,
  4126. # just a backend restart. Revive if it was previously stale-cancelled.
  4127. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4128. if subtask_match:
  4129. if existing_archive.status == "cancelled":
  4130. logger.warning(
  4131. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  4132. existing_archive.id,
  4133. subtask_id,
  4134. )
  4135. existing_archive.status = "printing"
  4136. existing_archive.failure_reason = None
  4137. await db.commit()
  4138. else:
  4139. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4140. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4141. if existing_archive.energy_start_kwh is None:
  4142. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4143. if not notification_sent:
  4144. archive_data = {
  4145. "print_time_seconds": existing_archive.print_time_seconds,
  4146. "created_by_id": existing_archive.created_by_id,
  4147. }
  4148. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4149. _load_objects_from_archive(existing_archive, printer_id, logger)
  4150. return
  4151. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4152. # stale from the printer's *current* progress, not wall-clock age.
  4153. # A genuinely long print used to trip a blind 4h cutoff and have its
  4154. # live archive cancelled + duplicated on every backend restart
  4155. # (#1485). If the printer reports real progress, this name-matched
  4156. # 'printing' archive IS that ongoing print — resume it whatever its
  4157. # age. Only treat it as a stale leftover when the printer clearly
  4158. # shows a different, freshly-started print: near-0% progress on an
  4159. # archive far too old to still be at 0%. Unknown progress (printer
  4160. # not connected) never cancels — resuming is the safe default.
  4161. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4162. live_status = printer_manager.get_status(printer_id)
  4163. live_progress = getattr(live_status, "progress", None) if live_status else None
  4164. looks_stale = (
  4165. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4166. )
  4167. if looks_stale:
  4168. logger.warning(
  4169. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}, "
  4170. f"printer progress {live_progress:.0f}%) — marking cancelled and creating new archive"
  4171. )
  4172. existing_archive.status = "cancelled"
  4173. # Canonical key, not a sentence (issue #2974). "No status update
  4174. # received" is what both stale paths actually observed; which of
  4175. # the two it was is already carried by ``status`` -- cancelled
  4176. # here, the reconciled outcome at the reconnect site -- so one
  4177. # key loses no information and gives the Statistics breakdown a
  4178. # single bucket instead of two untranslatable prose strings.
  4179. existing_archive.failure_reason = "noStatusUpdate"
  4180. await db.commit()
  4181. # Fall through to create new archive (don't return)
  4182. else:
  4183. logger.info(
  4184. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4185. )
  4186. # Track this as the active print
  4187. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4188. # Attach subtask_id retroactively so future restarts can resume.
  4189. # Compare for inequality (not "is empty") to also pick up reprint
  4190. # dispatches that mint a fresh id — see #1807 for the bogus
  4191. # "Print Stopped" the strict-empty guard caused on reconnect.
  4192. if subtask_id and existing_archive.subtask_id != subtask_id:
  4193. existing_archive.subtask_id = subtask_id
  4194. await db.commit()
  4195. # Also set up energy tracking if not already tracked (#941: persisted column)
  4196. if existing_archive.energy_start_kwh is None:
  4197. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  4198. # Send notification with archive data (existing archive)
  4199. if not notification_sent:
  4200. archive_data = {
  4201. "print_time_seconds": existing_archive.print_time_seconds,
  4202. "created_by_id": existing_archive.created_by_id,
  4203. }
  4204. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4205. # Extract printable objects from the archived 3MF file
  4206. _load_objects_from_archive(existing_archive, printer_id, logger)
  4207. return
  4208. # Build list of possible 3MF filenames to try
  4209. possible_names = []
  4210. # Bambu printers typically store files as "Name.gcode.3mf"
  4211. # The subtask_name is usually the best source for the filename
  4212. if subtask_name:
  4213. if _subtask_is_the_file(subtask_name, filename):
  4214. # A print started from the printer's own screen reports the
  4215. # file's full name, extension included. That is the file, so
  4216. # no extension is appended to it (#3009).
  4217. possible_names.append(subtask_name)
  4218. else:
  4219. # Try common Bambu naming patterns
  4220. possible_names.append(f"{subtask_name}.gcode.3mf")
  4221. possible_names.append(f"{subtask_name}.3mf")
  4222. # Try original filename with .3mf extension
  4223. if filename:
  4224. # Extract just the filename part, not the full path
  4225. fname = filename.split("/")[-1] if "/" in filename else filename
  4226. if fname.endswith(".3mf"):
  4227. possible_names.append(fname)
  4228. elif fname.endswith(".gcode"):
  4229. base = fname.rsplit(".", 1)[0]
  4230. possible_names.append(f"{base}.gcode.3mf")
  4231. possible_names.append(f"{base}.3mf")
  4232. else:
  4233. possible_names.append(f"{fname}.gcode.3mf")
  4234. possible_names.append(f"{fname}.3mf")
  4235. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  4236. space_variants = []
  4237. for name in possible_names:
  4238. if " " in name:
  4239. space_variants.append(name.replace(" ", "_"))
  4240. possible_names.extend(space_variants)
  4241. # Remove duplicates while preserving order
  4242. seen = set()
  4243. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  4244. logger.info("Trying filenames: %s", possible_names)
  4245. # Release the pooled DB connection before the 3MF FTP download. Reaching
  4246. # here means none of the expected-/existing-archive write branches ran
  4247. # (they all return earlier) — only SELECTs have executed on this path, so
  4248. # this commit persists nothing; it ends the read transaction so the
  4249. # connection returns to the pool during the download. That download tries
  4250. # up to five remote paths per candidate filename with retry/backoff and
  4251. # can run for minutes under FTP contention; holding the session across it
  4252. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  4253. # work runs during the download — the new-archive writes below re-acquire
  4254. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  4255. await db.commit()
  4256. # Try to find and download the 3MF file
  4257. temp_path = None
  4258. downloaded_filename = None
  4259. # Cache check: cover endpoint may have already pulled this 3MF during
  4260. # the print (frontend opens the card and shows the thumbnail) — reuse
  4261. # that file instead of re-downloading 36MB over the same FTP link that
  4262. # just served it (#972). The cache keys on a normalized filename so
  4263. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  4264. for try_filename in possible_names:
  4265. if not try_filename.endswith(".3mf"):
  4266. continue
  4267. cached = get_cached_3mf(printer_id, try_filename)
  4268. if cached:
  4269. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  4270. temp_path = cached
  4271. downloaded_filename = try_filename
  4272. break
  4273. # Does this printer keep the sliced file somewhere FTPS can reach? On
  4274. # H2-series and P2S the answer is routinely no — the file stays on
  4275. # internal eMMC and port 990 only ever serves external storage — and
  4276. # then the whole sweep below (six filenames x five directories x four
  4277. # retries, then the directory walk) is ~110 connections that cannot
  4278. # succeed. Skip it and say why (#2780).
  4279. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  4280. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  4281. # running rather than because the file is somewhere unreachable. The
  4282. # distinction is the whole of #2957: one is permanent, the other clears
  4283. # in minutes with the file still sitting on the printer.
  4284. blocked_by_ftps_cooloff = False
  4285. # Set when a probe reached the printer and still came back without the
  4286. # file -- a timeout mid-transfer, a refused connection, anything that is
  4287. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  4288. # caught by name below, so a file that genuinely is not on the card
  4289. # leaves this False and schedules nothing. Anything else means the
  4290. # transfer, not the file, is what failed, and that does not last (#3063).
  4291. ftp_transfer_failed = False
  4292. # The print's name, for a fallback archive whose `subtask_name` the
  4293. # plate guard below had to disown. Display only, and deliberately kept
  4294. # apart from `subtask_name`: that variable is what every file lookup
  4295. # here is built from, and once a name has been shown to fetch another
  4296. # plate's 3MF it must not key `_active_prints` either, or the cover
  4297. # endpoint hands the same contradicted file to
  4298. # `_recover_fallback_archive` and fills the row in with it (#3126).
  4299. display_name_after_plate_reject: str | None = None
  4300. # Get FTP retry settings
  4301. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  4302. # ...but "the printer put it on eMMC" is where it went, not whether we
  4303. # can read it. An H2D with a card in mirrors the job to /cache and
  4304. # serves it happily, and skipping on the URL alone cost that reporter
  4305. # every archive for two days (#2856). So ask the printer instead of
  4306. # guessing: the dispatch named the exact file, which is one connection
  4307. # walking five paths rather than the sweep's ~110. Only when the probe
  4308. # comes back empty does the verdict's reason stand.
  4309. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  4310. if ftps_handshake_blocked(printer.ip_address):
  4311. # Deliberately NOT recorded as a cool-off give-up. This branch
  4312. # only runs on an unreachable verdict, and that verdict is the
  4313. # honest, permanent reason the archive is empty — the probe was
  4314. # a long shot on top of it. Blaming the cool-off here would
  4315. # schedule a retry for a file sitting on internal eMMC, which is
  4316. # the sweep #2780 removed (#2957).
  4317. logger.debug(
  4318. "Not probing for %s on printer %s: its file service is not answering over TLS",
  4319. storage.probe_filename,
  4320. printer_id,
  4321. )
  4322. else:
  4323. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  4324. probe_path.parent.mkdir(parents=True, exist_ok=True)
  4325. try:
  4326. probe_hit = await download_file_try_paths_async(
  4327. printer.ip_address,
  4328. printer.access_code,
  4329. ftp_probe_paths(storage.probe_filename),
  4330. probe_path,
  4331. socket_timeout=ftp_timeout,
  4332. printer_model=printer.model,
  4333. )
  4334. except Exception as e:
  4335. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  4336. probe_hit = False
  4337. if probe_hit:
  4338. downloaded_filename = storage.probe_filename
  4339. temp_path = probe_path
  4340. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  4341. # Naming the path, not just the file: a printer that keeps
  4342. # uploads around for weeks can serve a same-named copy of an
  4343. # earlier slice, and without the directory in the log that
  4344. # mismatch is invisible rather than merely rare (#1820).
  4345. logger.info(
  4346. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  4347. downloaded_filename,
  4348. probe_hit,
  4349. printer_id,
  4350. storage.reason,
  4351. )
  4352. if not storage.reachable and not downloaded_filename:
  4353. # Same opening words whether or not a probe ran, because that is
  4354. # the phrase support asks people to grep for — only the tail says
  4355. # which of the two happened.
  4356. logger.info(
  4357. "Skipping the 3MF lookup for printer %s: %s — %s",
  4358. printer_id,
  4359. storage.reason,
  4360. "no copy of it on external storage either"
  4361. if storage.probe_filename
  4362. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  4363. )
  4364. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  4365. if not try_filename.endswith(".3mf"):
  4366. continue
  4367. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  4368. # printers, so try it first — deferring it to last cost #972's reporter
  4369. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  4370. # landing on the path that actually had the file.
  4371. remote_paths = [
  4372. f"/{try_filename}",
  4373. f"/cache/{try_filename}",
  4374. f"/model/{try_filename}",
  4375. f"/data/{try_filename}",
  4376. f"/data/Metadata/{try_filename}",
  4377. ]
  4378. temp_path = app_settings.archive_dir / "temp" / try_filename
  4379. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4380. for remote_path in remote_paths:
  4381. if ftps_handshake_blocked(printer.ip_address):
  4382. # The printer's FTPS service is not completing a TLS
  4383. # handshake, so it has no path we could reach — walking the
  4384. # remaining candidates only re-runs the same failure
  4385. # (#2780). Fall through to the no-3MF archive now.
  4386. #
  4387. # Remember *why*, though. This is the one give-up that is
  4388. # temporary: the cool-off clears in minutes and the file was
  4389. # on the printer the whole time. The fallback archive is
  4390. # stamped with it so a retry can be scheduled, and so the
  4391. # Archives banner stops blaming storage (#2957).
  4392. blocked_by_ftps_cooloff = True
  4393. logger.warning(
  4394. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  4395. printer_id,
  4396. )
  4397. break
  4398. logger.debug("Trying FTP download: %s", remote_path)
  4399. try:
  4400. if ftp_retry_enabled:
  4401. downloaded = await with_ftp_retry(
  4402. download_file_async,
  4403. printer.ip_address,
  4404. printer.access_code,
  4405. remote_path,
  4406. temp_path,
  4407. timeout=ftp_timeout,
  4408. socket_timeout=ftp_timeout,
  4409. printer_model=printer.model,
  4410. max_retries=ftp_retry_count,
  4411. retry_delay=ftp_retry_delay,
  4412. operation_name=f"Download 3MF from {remote_path}",
  4413. cooloff_ip=printer.ip_address,
  4414. non_retry_exceptions=(FileNotOnPrinterError,),
  4415. )
  4416. else:
  4417. downloaded = await download_file_async(
  4418. printer.ip_address,
  4419. printer.access_code,
  4420. remote_path,
  4421. temp_path,
  4422. timeout=ftp_timeout,
  4423. socket_timeout=ftp_timeout,
  4424. printer_model=printer.model,
  4425. )
  4426. if downloaded:
  4427. downloaded_filename = try_filename
  4428. logger.info("Downloaded: %s", remote_path)
  4429. # Populate shared cache so the cover endpoint (if it
  4430. # runs next) doesn't refetch the same 36MB over FTP.
  4431. cache_3mf_download(printer_id, try_filename, temp_path)
  4432. break
  4433. # with_ftp_retry returns None once it has spent its budget,
  4434. # and download_file_async returns False on a timeout, so an
  4435. # exhausted transfer arrives here rather than as an
  4436. # exception (#3063).
  4437. ftp_transfer_failed = True
  4438. except FileNotOnPrinterError:
  4439. # 550 — file isn't at this path. Advance to next candidate
  4440. # without burning the retry budget.
  4441. logger.debug("3MF not at %s (550), trying next path", remote_path)
  4442. except Exception as e:
  4443. ftp_transfer_failed = True
  4444. logger.debug("FTP download failed for %s: %s", remote_path, e)
  4445. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  4446. break
  4447. # If still not found, try listing directories to find matching file
  4448. # Different printer models use different directory structures. Skipped
  4449. # when the printer's FTPS handshake is failing — the directory walk is
  4450. # five more connections that cannot get further than the download did.
  4451. if (
  4452. not downloaded_filename
  4453. and storage.reachable
  4454. and (filename or subtask_name)
  4455. and not ftps_handshake_blocked(printer.ip_address)
  4456. ):
  4457. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  4458. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  4459. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  4460. for search_dir in search_dirs:
  4461. if downloaded_filename:
  4462. break
  4463. try:
  4464. dir_files = await list_files_async(
  4465. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  4466. )
  4467. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  4468. if threemf_files:
  4469. logger.info(
  4470. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  4471. )
  4472. for f in dir_files:
  4473. if f.get("is_directory"):
  4474. continue
  4475. fname = f.get("name", "")
  4476. # Normalize both for comparison (spaces and underscores are equivalent)
  4477. fname_normalized = fname.lower().replace(" ", "_")
  4478. search_normalized = search_term.replace(" ", "_")
  4479. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  4480. logger.info("Found matching file in %s: %s", search_dir, fname)
  4481. temp_path = app_settings.archive_dir / "temp" / fname
  4482. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4483. remote_full_path = posixpath.join(search_dir, fname)
  4484. if ftp_retry_enabled:
  4485. downloaded = await with_ftp_retry(
  4486. download_file_async,
  4487. printer.ip_address,
  4488. printer.access_code,
  4489. remote_full_path,
  4490. temp_path,
  4491. timeout=ftp_timeout,
  4492. socket_timeout=ftp_timeout,
  4493. printer_model=printer.model,
  4494. max_retries=ftp_retry_count,
  4495. retry_delay=ftp_retry_delay,
  4496. operation_name=f"Download 3MF from {remote_full_path}",
  4497. cooloff_ip=printer.ip_address,
  4498. )
  4499. else:
  4500. downloaded = await download_file_async(
  4501. printer.ip_address,
  4502. printer.access_code,
  4503. remote_full_path,
  4504. temp_path,
  4505. timeout=ftp_timeout,
  4506. socket_timeout=ftp_timeout,
  4507. printer_model=printer.model,
  4508. )
  4509. if downloaded:
  4510. downloaded_filename = fname
  4511. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  4512. cache_3mf_download(printer_id, fname, temp_path)
  4513. break
  4514. # The listing named the file, so it is on the card;
  4515. # only the transfer failed (#3063).
  4516. ftp_transfer_failed = True
  4517. except Exception as e:
  4518. logger.debug("Failed to list %s: %s", search_dir, e)
  4519. # Validate the downloaded 3MF actually matches the plate that's running
  4520. # (#1204): subtask_name lags across consecutive plates of the same model,
  4521. # so the first FTP candidate (built from subtask_name) can land on the
  4522. # previous plate's still-resident upload. Cross-check the slice_info
  4523. # plate index against the plate parsed from gcode_file (always fresh —
  4524. # it's the field whose change triggered this callback).
  4525. if downloaded_filename and temp_path:
  4526. expected_plate = parse_plate_id(filename)
  4527. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  4528. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  4529. logger.warning(
  4530. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  4531. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  4532. downloaded_filename,
  4533. actual_plate,
  4534. expected_plate,
  4535. subtask_name,
  4536. )
  4537. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  4538. retry_succeeded = False
  4539. if corrected_subtask and corrected_subtask != subtask_name:
  4540. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  4541. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  4542. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  4543. for remote_path in (
  4544. f"/{try_filename}",
  4545. f"/cache/{try_filename}",
  4546. f"/model/{try_filename}",
  4547. f"/data/{try_filename}",
  4548. f"/data/Metadata/{try_filename}",
  4549. ):
  4550. try:
  4551. if ftp_retry_enabled:
  4552. downloaded = await with_ftp_retry(
  4553. download_file_async,
  4554. printer.ip_address,
  4555. printer.access_code,
  4556. remote_path,
  4557. retry_temp_path,
  4558. timeout=ftp_timeout,
  4559. socket_timeout=ftp_timeout,
  4560. printer_model=printer.model,
  4561. max_retries=ftp_retry_count,
  4562. retry_delay=ftp_retry_delay,
  4563. operation_name=f"Re-download 3MF from {remote_path}",
  4564. cooloff_ip=printer.ip_address,
  4565. non_retry_exceptions=(FileNotOnPrinterError,),
  4566. )
  4567. else:
  4568. downloaded = await download_file_async(
  4569. printer.ip_address,
  4570. printer.access_code,
  4571. remote_path,
  4572. retry_temp_path,
  4573. timeout=ftp_timeout,
  4574. socket_timeout=ftp_timeout,
  4575. printer_model=printer.model,
  4576. )
  4577. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  4578. logger.info(
  4579. "[CALLBACK] Re-download succeeded with corrected name %s "
  4580. "(plate %s) — replacing wrong file",
  4581. try_filename,
  4582. expected_plate,
  4583. )
  4584. try:
  4585. temp_path.unlink(missing_ok=True)
  4586. except OSError:
  4587. pass
  4588. temp_path = retry_temp_path
  4589. downloaded_filename = try_filename
  4590. subtask_name = corrected_subtask
  4591. cache_3mf_download(printer_id, try_filename, temp_path)
  4592. retry_succeeded = True
  4593. break
  4594. elif downloaded:
  4595. # Wrong plate again — discard and keep trying
  4596. try:
  4597. retry_temp_path.unlink(missing_ok=True)
  4598. except OSError:
  4599. pass
  4600. except FileNotOnPrinterError:
  4601. continue
  4602. except Exception as e:
  4603. logger.debug("Re-download failed for %s: %s", remote_path, e)
  4604. if retry_succeeded:
  4605. break
  4606. # If the retry didn't find a matching file, drop the wrong 3MF
  4607. # so the no-3MF fallback below creates an archive whose name
  4608. # at least reflects the right plate.
  4609. if not retry_succeeded:
  4610. logger.warning(
  4611. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  4612. expected_plate,
  4613. )
  4614. try:
  4615. temp_path.unlink(missing_ok=True)
  4616. except OSError:
  4617. pass
  4618. temp_path = None
  4619. downloaded_filename = None
  4620. # Whatever the sweep's transport did earlier, it is not why
  4621. # this archive ends up empty: a 3MF downloaded fine, it was
  4622. # just the wrong plate. Retrying would re-fetch that same
  4623. # contradicted file under the same stale names and hand it
  4624. # to _recover_fallback_archive, which checks that a
  4625. # candidate is a readable 3MF but not which plate it is --
  4626. # so the row would be filled in with another plate's
  4627. # filament and cost, the exact swap #2957 removed (#3063).
  4628. ftp_transfer_failed = False
  4629. # Disown the name for *lookups*: it has just been shown to
  4630. # fetch another plate's 3MF, and it keys `_active_prints`
  4631. # below, where the cover endpoint's own download of that
  4632. # same name would find this archive and fill it in with the
  4633. # file we are discarding here.
  4634. #
  4635. # Keep it for the *title*, which is a separate question.
  4636. # ``swap_plate_suffix`` returns None both for a name that
  4637. # carries no "- Plate N" / "_plate_N" suffix and for no
  4638. # name at all, and those are not the same situation: a name
  4639. # without a suffix holds no stale plate number to be wrong
  4640. # about. Blanking both uses at once dropped the project
  4641. # name too, and the row fell through to the gcode_file path
  4642. # titled "plate_1" though the real name was in hand.
  4643. # #1204's own premise is consecutive plates *of the same
  4644. # model*, so the project part is right either way (#3126).
  4645. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  4646. subtask_name = corrected_subtask or ""
  4647. if not downloaded_filename or not temp_path:
  4648. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  4649. # Create a fallback archive without 3MF data so the print is still tracked
  4650. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  4651. try:
  4652. from backend.app.models.archive import PrintArchive
  4653. # Why the card is empty. The two temporary causes outrank the
  4654. # storage verdict because they say the sweep never got a fair
  4655. # answer: a cool-off skipped it at the transport, and a failed
  4656. # transfer reached the printer but never finished. Either way
  4657. # the file is still on the card, so reporting where the printer
  4658. # files its jobs would describe a setting that is not the
  4659. # problem (#2957, #3063).
  4660. if blocked_by_ftps_cooloff:
  4661. no_3mf_reason = REASON_FTPS_COOLOFF
  4662. elif storage.reachable and ftp_transfer_failed:
  4663. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  4664. else:
  4665. no_3mf_reason = storage.reason
  4666. # Derive print name from subtask_name or filename. The
  4667. # plate guard's disowned name comes second: it is a real name
  4668. # for a real print, and only the gcode_file path is left
  4669. # otherwise -- which titles the row "plate_1" (#3126).
  4670. print_name = subtask_name or display_name_after_plate_reject or filename
  4671. if print_name:
  4672. # Clean up the name (remove extensions, path parts)
  4673. print_name = print_name.split("/")[-1]
  4674. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  4675. else:
  4676. print_name = "Unknown Print"
  4677. # Recover estimated print time from MQTT (best-effort for notifications)
  4678. fallback_print_time = None
  4679. mqtt_remaining = data.get("remaining_time")
  4680. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  4681. fallback_print_time = int(mqtt_remaining)
  4682. if fallback_print_time is None:
  4683. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  4684. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  4685. fallback_print_time = int(mc_remaining * 60)
  4686. # Best-effort filament metadata from MQTT — see
  4687. # _extract_filament_data_from_mqtt. Without this the fallback
  4688. # archive's filament fields stayed NULL even though the AMS
  4689. # state at print start was sitting right there in `data`.
  4690. # The slicer's ams_mapping (when present) narrows the result
  4691. # to slots actually used by the print (#1533).
  4692. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  4693. # Create minimal archive entry
  4694. fallback_archive = PrintArchive(
  4695. printer_id=printer_id,
  4696. filename=filename or f"{print_name}.3mf",
  4697. file_path="", # Empty - no 3MF file available
  4698. file_size=0,
  4699. print_name=print_name,
  4700. print_time_seconds=fallback_print_time,
  4701. status="printing",
  4702. started_at=datetime.now(timezone.utc),
  4703. subtask_id=subtask_id,
  4704. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  4705. filament_type=mqtt_filament_meta.get("filament_type"),
  4706. filament_color=mqtt_filament_meta.get("filament_color"),
  4707. extra_data={
  4708. "no_3mf_available": True,
  4709. # Why the card is empty, when we know -- see above. The
  4710. # banner reads this to stop telling H2/P2 owners to
  4711. # switch on a setting that is already on and would not
  4712. # have helped (#2780).
  4713. "no_3mf_reason": no_3mf_reason,
  4714. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  4715. "_print_data": data,
  4716. },
  4717. )
  4718. db.add(fallback_archive)
  4719. await db.commit()
  4720. await db.refresh(fallback_archive)
  4721. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  4722. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  4723. # Track as active print
  4724. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  4725. if filename:
  4726. _active_prints[(printer_id, filename)] = fallback_archive.id
  4727. if subtask_name:
  4728. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  4729. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  4730. # Record starting energy if smart plug available (#941: persisted column)
  4731. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  4732. # Send WebSocket notification
  4733. await ws_manager.send_archive_created(
  4734. {
  4735. "id": fallback_archive.id,
  4736. "printer_id": fallback_archive.printer_id,
  4737. "filename": fallback_archive.filename,
  4738. "print_name": fallback_archive.print_name,
  4739. "status": fallback_archive.status,
  4740. }
  4741. )
  4742. # MQTT relay - publish archive created
  4743. try:
  4744. await mqtt_relay.on_archive_created(
  4745. archive_id=fallback_archive.id,
  4746. print_name=fallback_archive.print_name,
  4747. printer_name=printer.name,
  4748. status=fallback_archive.status,
  4749. )
  4750. except Exception:
  4751. pass # Don't fail if MQTT fails
  4752. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  4753. try:
  4754. await _store_spoolman_print_data(
  4755. printer_id,
  4756. fallback_archive.id,
  4757. fallback_archive.file_path,
  4758. db,
  4759. printer_manager,
  4760. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  4761. plate_id=_get_start_plate_id(fallback_archive.id),
  4762. )
  4763. except Exception as e:
  4764. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  4765. # Both temporary give-ups are worth coming back for, and for
  4766. # the same reason: the file is on the printer and the last look
  4767. # failed at the transport rather than finding nothing. One waits
  4768. # out the handshake block (#2957), the other waits for the
  4769. # printer to stop being busy (#3063). Deliberately not scheduled
  4770. # for a storage verdict: a file on internal eMMC will not appear
  4771. # at any FTPS path however long we wait, and retrying it is
  4772. # exactly the sweep #2780 removed.
  4773. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  4774. # `possible_names`, not the raw MQTT strings: it is the exact
  4775. # list this flow just tried, already stripped of any path
  4776. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  4777. # some firmware) and deduped.
  4778. _schedule_fallback_3mf_retry(
  4779. printer_id=printer_id,
  4780. archive_id=fallback_archive.id,
  4781. filenames=list(possible_names),
  4782. reason=no_3mf_reason,
  4783. )
  4784. # Send notification without archive data (file not found)
  4785. if not notification_sent:
  4786. await _send_print_start_notification(printer_id, data, logger=logger)
  4787. # The same baseline the other two on_print_start branches take
  4788. # (#2704), and last for the same reason they are: it lists the
  4789. # printer's timelapse directory, so a slow card must not delay
  4790. # the _active_prints registration, the energy reading, the
  4791. # archive-created event or the start notification above it.
  4792. #
  4793. # This branch never took one, so every no-3MF archive reached
  4794. # completion with no baseline in memory and none on the row, and
  4795. # the completion scan fell into its "snapshot now" fallback --
  4796. # which runs after the printer has written the video, so the new
  4797. # file landed inside the baseline and no diff ever matched
  4798. # (#2957 follow-up).
  4799. #
  4800. # Skipped when the FTPS cool-off is what produced this fallback:
  4801. # the listing needs the same connection that just failed, so it
  4802. # could only record that the card was unreadable. The scan
  4803. # handles that case by refusing to choose between candidates.
  4804. if not blocked_by_ftps_cooloff:
  4805. await _capture_timelapse_baseline_at_start(
  4806. printer, printer_id, logger, archive_id=fallback_archive.id
  4807. )
  4808. return
  4809. except Exception as e:
  4810. logger.error("Failed to create fallback archive: %s", e)
  4811. # Send notification without archive data (file not found)
  4812. if not notification_sent:
  4813. await _send_print_start_notification(printer_id, data, logger=logger)
  4814. return
  4815. try:
  4816. # Archive the file with status "printing"
  4817. service = ArchiveService(db)
  4818. archive = await service.archive_print(
  4819. printer_id=printer_id,
  4820. source_file=temp_path,
  4821. print_data={**data, "status": "printing"},
  4822. subtask_id=subtask_id,
  4823. )
  4824. if archive:
  4825. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  4826. # Set on the row rather than passed to archive_print, which also
  4827. # serves the queue dispatcher — there the queue item decides.
  4828. # Guarded because this branch has no ``except``: an unhandled
  4829. # write error would take the _active_prints registration, the
  4830. # start notification, the energy reading and the timelapse
  4831. # baseline below it with it, and a missing prompt is by far the
  4832. # cheaper failure.
  4833. archive_id = archive.id
  4834. try:
  4835. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  4836. archive.confirm_requested = True
  4837. await db.commit()
  4838. except Exception as e:
  4839. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  4840. # The rollback expires every loaded object, and on an async
  4841. # session reading one afterwards raises instead of
  4842. # reloading, so the two this branch goes on to use are
  4843. # fetched again. The archive itself was committed by
  4844. # archive_print; only the flag is lost.
  4845. try:
  4846. await db.rollback()
  4847. archive = await db.get(PrintArchive, archive_id)
  4848. printer = await db.get(Printer, printer_id)
  4849. except Exception as reload_error:
  4850. logger.warning(
  4851. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  4852. )
  4853. # Track this active print (use both original filename and downloaded filename)
  4854. _active_prints[(printer_id, downloaded_filename)] = archive.id
  4855. if filename and filename != downloaded_filename:
  4856. _active_prints[(printer_id, filename)] = archive.id
  4857. if subtask_name:
  4858. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  4859. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  4860. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4861. # Record starting energy from smart plug if available (#941: persisted column)
  4862. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  4863. await ws_manager.send_archive_created(
  4864. {
  4865. "id": archive.id,
  4866. "printer_id": archive.printer_id,
  4867. "filename": archive.filename,
  4868. "print_name": archive.print_name,
  4869. "status": archive.status,
  4870. }
  4871. )
  4872. # MQTT relay - publish archive created
  4873. try:
  4874. await mqtt_relay.on_archive_created(
  4875. archive_id=archive.id,
  4876. print_name=archive.print_name,
  4877. printer_name=printer.name,
  4878. status=archive.status,
  4879. )
  4880. except Exception:
  4881. pass # Don't fail if MQTT fails
  4882. # Send notification with archive data (new archive created)
  4883. if not notification_sent:
  4884. archive_data = {
  4885. "print_time_seconds": archive.print_time_seconds,
  4886. "created_by_id": archive.created_by_id,
  4887. }
  4888. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4889. # Extract printable objects for skip object functionality
  4890. try:
  4891. from backend.app.services.archive import extract_printable_objects_from_3mf
  4892. client = printer_manager.get_client(printer_id)
  4893. if client:
  4894. with open(temp_path, "rb") as f:
  4895. threemf_data = f.read()
  4896. # Extract with positions for UI overlay, scoped to the
  4897. # plate that is printing — an all-plates 3MF carries
  4898. # every plate's objects (#2522).
  4899. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  4900. threemf_data,
  4901. plate_number=resolve_plate_id(client.state),
  4902. include_positions=True,
  4903. )
  4904. if printable_objects:
  4905. # Store objects in printer state
  4906. client.state.printable_objects = printable_objects
  4907. client.state.printable_objects_bbox_all = bbox_all
  4908. client.state.skipped_objects = [] # Reset skipped objects for new print
  4909. logger.info(
  4910. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  4911. )
  4912. except Exception as e:
  4913. logger.debug("Failed to extract printable objects: %s", e)
  4914. # Store Spoolman tracking data for per-filament usage reporting
  4915. try:
  4916. await _store_spoolman_print_data(
  4917. printer_id,
  4918. archive.id,
  4919. archive.file_path,
  4920. db,
  4921. printer_manager,
  4922. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4923. plate_id=_get_start_plate_id(archive.id),
  4924. )
  4925. except Exception as e:
  4926. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4927. # Price the print from its spools now rather than only at completion (#3261)
  4928. _schedule_archive_cost_estimate(
  4929. printer_id,
  4930. archive.id,
  4931. printer_manager,
  4932. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4933. plate_id=_get_start_plate_id(archive.id),
  4934. session_factory=async_session,
  4935. )
  4936. # Capture timelapse file baseline for snapshot-diff on completion
  4937. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4938. finally:
  4939. # Keep temp_path around until print completes so the cover endpoint
  4940. # can reuse it (#972). Cache eviction in on_print_complete deletes
  4941. # the file. If the cache entry was evicted early (file vanished),
  4942. # clean up any stragglers here to avoid leaking disk on retries.
  4943. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  4944. if temp_path and temp_path.exists() and cached_now != temp_path:
  4945. temp_path.unlink()
  4946. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  4947. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  4948. # tests can shrink them without waiting out real delays.
  4949. #
  4950. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  4951. # looking. Across 247 support bundles the attempt that found the video was #1
  4952. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  4953. # decaying one, which is the signature of a budget that expires while files are
  4954. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  4955. # prints make big videos and the printer writes them after the print ends, so
  4956. # the poll now runs for minutes and costs one FTP LIST per round.
  4957. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  4958. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  4959. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  4960. def _timelapse_scan_max_attempts() -> int:
  4961. """Round cap for the poll, derived from the wall-clock budget.
  4962. The deadline alone is not a sufficient bound: it assumes each round really
  4963. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  4964. and an FTP list that fails immediately would otherwise spin against the
  4965. printer at full speed for the whole window. Whichever bound is reached
  4966. first ends the poll.
  4967. """
  4968. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  4969. # A zero interval makes the wall-clock budget meaningless; fall back to
  4970. # the round count the production interval would have given.
  4971. return 32
  4972. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  4973. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  4974. """Video filenames already attached to some other archive of this printer.
  4975. Used to disambiguate when more than one file is new since the baseline —
  4976. which happens when a previous print's video landed after this print's
  4977. baseline was taken. Ordering the candidates would be the obvious fix and is
  4978. the wrong one: it can only be done on mtime or on the filename timestamp,
  4979. both of which come from the printer's own clock, and a LAN-only printer
  4980. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  4981. ``attach_timelapse`` saves the video into the archive directory under the
  4982. printer's original filename, and the later MP4 conversion keeps the stem,
  4983. so the stem of ``timelapse_path`` recovers what was claimed.
  4984. """
  4985. from backend.app.models.archive import PrintArchive
  4986. rows = await db.execute(
  4987. select(PrintArchive.timelapse_path).where(
  4988. PrintArchive.printer_id == printer_id,
  4989. PrintArchive.id != exclude_archive_id,
  4990. PrintArchive.timelapse_path.is_not(None),
  4991. )
  4992. )
  4993. return {Path(p).stem for p in rows.scalars().all() if p}
  4994. def _timelapse_listing_is_trustworthy(printer) -> bool:
  4995. """Whether an *empty* timelapse listing for *printer* can be believed.
  4996. ``list_files_async`` answers ``[]`` when its connect fails rather than
  4997. raising, so a card behind the FTPS handshake cool-off is indistinguishable
  4998. from one holding no videos. Everywhere that only wants to know "is there a
  4999. video yet" the difference does not matter — both mean "not yet, retry".
  5000. It matters where an empty listing is recorded as a *baseline*. Recording
  5001. "the card held nothing" for a card that was never read means every video on
  5002. it counts as new once the cool-off expires, and the completion scan then
  5003. attaches a stale video to this print and deletes it from the printer
  5004. (#2957 follow-up). Those two callers ask this first.
  5005. """
  5006. from backend.app.services.bambu_ftp import ftps_handshake_blocked
  5007. ip_address = getattr(printer, "ip_address", None)
  5008. if not ip_address:
  5009. return True
  5010. return not ftps_handshake_blocked(ip_address)
  5011. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  5012. """List video files from printer's timelapse directory.
  5013. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  5014. Returns (video_files, found_path) where video_files is a list of file dicts
  5015. and found_path is the directory where they were found, or ([], None).
  5016. An empty return does not distinguish "no videos" from "could not read the
  5017. card" — see :func:`_timelapse_listing_is_trustworthy`, which the two
  5018. baseline callers consult before believing one.
  5019. """
  5020. from backend.app.services.bambu_ftp import list_files_async
  5021. logger = logging.getLogger(__name__)
  5022. # No card in the slot means no /timelapse to walk — four connections that
  5023. # can only fail, on a path whose failures are swallowed and so would go on
  5024. # costing time silently forever (#2780).
  5025. #
  5026. # ``getattr`` rather than ``printer.id``: every dereference below happens
  5027. # inside the loop's own try/except, so a caller that passed something
  5028. # unexpected used to get an empty listing rather than an exception. Keep
  5029. # that, instead of making this gate the first thing that can raise here.
  5030. printer_id = getattr(printer, "id", None)
  5031. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5032. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  5033. return [], None
  5034. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  5035. try:
  5036. found_files = await list_files_async(
  5037. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5038. )
  5039. if found_files:
  5040. video_files = [
  5041. f
  5042. for f in found_files
  5043. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5044. ]
  5045. if video_files:
  5046. return video_files, timelapse_path
  5047. except Exception as e:
  5048. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  5049. continue
  5050. return [], None
  5051. async def _capture_timelapse_baseline_at_start(
  5052. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  5053. ) -> None:
  5054. """Snapshot the printer's timelapse directory at print start so the
  5055. completion-time scan can pick the new file by set-difference.
  5056. Must be called from every on_print_start path that proceeds to a real
  5057. print — both the new-archive branch and the expected-archive branch (which
  5058. queue / VP-dispatched prints take). Without a baseline,
  5059. _scan_for_timelapse_with_retries falls into its "take baseline now"
  5060. fallback that runs AFTER the new MP4 has already landed on the SD card,
  5061. so the new file ends up in the "baseline" set and no diff ever matches.
  5062. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  5063. unreliable — the snapshot-diff approach sidesteps that entirely.
  5064. When ``archive_id`` is known the baseline is also written to the archive
  5065. row, so it survives a restart and the manual "Scan for Timelapse" button
  5066. can run the same diff instead of falling back to clock-based matching
  5067. (#2704). Only baselines taken at print start are persisted — one taken at
  5068. completion already contains the new video and would poison a later scan.
  5069. """
  5070. names: set[str] | None = None
  5071. try:
  5072. if not _timelapse_listing_is_trustworthy(printer):
  5073. # Recorded anyway, deliberately. An empty baseline taken off a card
  5074. # we could not read is not authoritative, but it is still the right
  5075. # *default*: Bambuddy deletes each video from the printer once it is
  5076. # attached, so the usual card holds exactly one video at completion
  5077. # and an empty baseline resolves it correctly. Persisting NULL
  5078. # instead would send completion to take its own snapshot, by which
  5079. # point this print's video is on the card and would be swallowed by
  5080. # it. The ambiguity is handled where it actually bites — see
  5081. # ``require_unambiguous`` in the scan (#2957 follow-up).
  5082. logger.warning(
  5083. "[TIMELAPSE] Baseline for printer %s taken while its file service is in the FTPS "
  5084. "handshake cool-off, so the card could not be read — treating it as empty",
  5085. printer_id,
  5086. )
  5087. baseline_files, _ = await _list_timelapse_videos(printer)
  5088. names = {f.get("name", "") for f in baseline_files}
  5089. _timelapse_baselines[printer_id] = names
  5090. logger.info(
  5091. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  5092. len(names),
  5093. printer_id,
  5094. )
  5095. except Exception as e:
  5096. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  5097. if archive_id is None:
  5098. return
  5099. try:
  5100. async with async_session() as db:
  5101. from backend.app.models.archive import PrintArchive
  5102. archive = await db.get(PrintArchive, archive_id)
  5103. if archive is not None:
  5104. # Written even when the listing failed, and then as NULL. A
  5105. # reprint reuses the archive row, so leaving the previous run's
  5106. # baseline in place would have the scan diff this print against
  5107. # the state of the printer before the *last* one — and a stale
  5108. # baseline reads as authoritative, where NULL correctly falls
  5109. # back to a fresh snapshot.
  5110. archive.timelapse_baseline = sorted(names) if names is not None else None
  5111. await db.commit()
  5112. except Exception as e:
  5113. # In-memory baseline still covers the normal completion path.
  5114. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  5115. async def _scan_for_timelapse_with_retries(archive_id: int, baseline_names: set[str] | None = None):
  5116. """Poll the printer for this print's timelapse and attach it.
  5117. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  5118. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  5119. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  5120. (#2704). Comparing the current listing against the set of filenames that
  5121. existed when the print started needs no clock at all, because the printer
  5122. writes the video only once the print has ended.
  5123. Baseline precedence: the caller's in-memory set, then the one persisted on
  5124. the archive at print start, then a snapshot taken now. The last of those is
  5125. a poor substitute — by completion the new video may already be on the card,
  5126. in which case it lands in the "baseline" and no diff can ever match — but it
  5127. is all that is available for a print that began before Bambuddy started.
  5128. On success the video is deleted from the printer, which keeps ``/timelapse``
  5129. down to the unclaimed files and makes the next diff unambiguous.
  5130. """
  5131. logger = logging.getLogger(__name__)
  5132. # Cleared when the baseline had to be taken off a card we could not read, so
  5133. # the attach step refuses to choose between several candidates (#2957).
  5134. baseline_trusted = True
  5135. # --- Phase 1: establish the baseline -------------------------------------
  5136. try:
  5137. async with async_session() as db:
  5138. from backend.app.models.printer import Printer
  5139. service = ArchiveService(db)
  5140. archive = await service.get_archive(archive_id)
  5141. if not archive:
  5142. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  5143. return
  5144. if archive.timelapse_path:
  5145. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  5146. return
  5147. if not archive.printer_id:
  5148. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  5149. return
  5150. if baseline_names is not None:
  5151. logger.info(
  5152. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  5153. len(baseline_names),
  5154. archive_id,
  5155. )
  5156. elif archive.timelapse_baseline is not None:
  5157. # Persisted at print start — survives a restart mid-print.
  5158. baseline_names = set(archive.timelapse_baseline)
  5159. logger.info(
  5160. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  5161. len(baseline_names),
  5162. archive_id,
  5163. )
  5164. else:
  5165. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5166. printer = result.scalar_one_or_none()
  5167. if not printer:
  5168. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  5169. return
  5170. if not _timelapse_listing_is_trustworthy(printer):
  5171. # The card is unreadable at the one moment a baseline has to
  5172. # be taken, so the empty listing below means "we never
  5173. # looked", not "these are all new". Carry on with it anyway
  5174. # — the usual card holds exactly one video, which resolves
  5175. # correctly — but stop the poll from *choosing* between
  5176. # several, which is how a stale video got attached to this
  5177. # print and then deleted off the printer (#2957 follow-up).
  5178. baseline_trusted = False
  5179. logger.warning(
  5180. "[TIMELAPSE] Baseline for archive %s taken while printer %s is in the FTPS "
  5181. "handshake cool-off. A single new video still resolves; several will not be "
  5182. "guessed between — use Scan for Timelapse to pick one by hand",
  5183. archive_id,
  5184. archive.printer_id,
  5185. )
  5186. baseline_files, _ = await _list_timelapse_videos(printer)
  5187. baseline_names = {f.get("name", "") for f in baseline_files}
  5188. logger.info(
  5189. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  5190. len(baseline_names),
  5191. archive_id,
  5192. )
  5193. except Exception as e:
  5194. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  5195. return
  5196. # --- Phase 2: poll for a file that was not there when the print began -----
  5197. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  5198. max_attempts = _timelapse_scan_max_attempts()
  5199. seen_names: set[str] = set()
  5200. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  5201. attempt = 0
  5202. while True:
  5203. await asyncio.sleep(delay)
  5204. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  5205. attempt += 1
  5206. try:
  5207. from backend.app.models.printer import Printer
  5208. # Read phase: fetch archive + printer in a short session and release
  5209. # the pooled connection BEFORE the FTP list/download below. Holding it
  5210. # across the FTP round-trips left one connection idle-in-transaction per
  5211. # in-flight scan (issue #2572).
  5212. async with async_session() as db:
  5213. service = ArchiveService(db)
  5214. archive = await service.get_archive(archive_id)
  5215. if not archive:
  5216. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  5217. return
  5218. if archive.timelapse_path:
  5219. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  5220. return
  5221. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5222. printer = result.scalar_one_or_none()
  5223. if not printer:
  5224. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  5225. return
  5226. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  5227. # I/O phase (no DB connection held): FTP list + download.
  5228. video_files, found_path = await _list_timelapse_videos(printer)
  5229. # The poll can run for dozens of rounds, so only narrate a round
  5230. # that saw something change. Repeating the whole listing every 30 s
  5231. # would bury the one interesting line in the support bundle.
  5232. names_now = {f.get("name", "") for f in video_files}
  5233. changed = attempt == 1 or names_now != seen_names
  5234. seen_names = names_now
  5235. speak = logger.info if changed else logger.debug
  5236. if video_files:
  5237. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  5238. if changed:
  5239. for f in video_files[:5]:
  5240. logger.info("[TIMELAPSE] - %s", f.get("name"))
  5241. attached = await _attach_first_unclaimed_timelapse(
  5242. archive_id,
  5243. printer,
  5244. video_files,
  5245. baseline_names,
  5246. claimed,
  5247. attempt,
  5248. logger,
  5249. quiet=not changed,
  5250. require_unambiguous=not baseline_trusted,
  5251. )
  5252. if attached:
  5253. return
  5254. else:
  5255. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  5256. except Exception as e:
  5257. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  5258. if attempt >= max_attempts or time.monotonic() >= deadline:
  5259. break
  5260. # No name-match fallback: it compared the print name against the filename,
  5261. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  5262. # bundles it fired 159 times and matched zero times, so all it added was a
  5263. # misleading log line before giving up.
  5264. logger.warning(
  5265. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  5266. archive_id,
  5267. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  5268. )
  5269. async def _attach_first_unclaimed_timelapse(
  5270. archive_id: int,
  5271. printer,
  5272. video_files: list[dict],
  5273. baseline_names: set[str],
  5274. claimed: set[str],
  5275. attempt: int,
  5276. logger: logging.Logger,
  5277. *,
  5278. quiet: bool = False,
  5279. require_unambiguous: bool = False,
  5280. ) -> bool:
  5281. """Download and attach the one video that belongs to this print.
  5282. A candidate is any file absent from the print-start baseline. More than one
  5283. can qualify when a previous print's video landed late, after this print's
  5284. baseline was taken — those are filtered out by name, because they are
  5285. already attached to another archive. Sorting the candidates instead would
  5286. mean sorting on mtime or on the filename timestamp, both of which come from
  5287. the printer's unsynced clock.
  5288. Returns True once a video is attached. The printer's copy is deleted only
  5289. after the attach succeeds on bytes whose length matched the listing.
  5290. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  5291. already seen this exact listing — the poll runs for many rounds and only the
  5292. rounds where something changed are worth an INFO line.
  5293. """
  5294. from backend.app.services.bambu_ftp import (
  5295. delete_archived_timelapse,
  5296. download_file_bytes_async,
  5297. remote_file_settled,
  5298. )
  5299. speak = logger.debug if quiet else logger.info
  5300. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  5301. if not new_files:
  5302. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  5303. return False
  5304. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  5305. if not candidates:
  5306. speak(
  5307. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  5308. attempt,
  5309. len(new_files),
  5310. )
  5311. return False
  5312. if len(candidates) > 1:
  5313. if require_unambiguous:
  5314. # The baseline is not evidence -- it was taken off a card that could
  5315. # not be read -- so "new since the baseline" does not narrow these
  5316. # down at all. Taking the first would attach an arbitrary video to
  5317. # this print and then delete it from the printer.
  5318. logger.warning(
  5319. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  5320. "leaving all of them on the printer for manual selection",
  5321. attempt,
  5322. len(candidates),
  5323. ", ".join(str(f.get("name")) for f in candidates),
  5324. )
  5325. return False
  5326. logger.warning(
  5327. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  5328. "the rest stay on the printer for manual selection",
  5329. attempt,
  5330. len(candidates),
  5331. ", ".join(str(f.get("name")) for f in candidates),
  5332. )
  5333. target = candidates[0]
  5334. file_name = target.get("name")
  5335. remote_path = target.get("path") or f"/timelapse/{file_name}"
  5336. logger.info(
  5337. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  5338. attempt,
  5339. file_name,
  5340. archive_id,
  5341. )
  5342. # The listing always carries a size (`list_files` skips entries it can't
  5343. # parse), but read it explicitly: the delete below is destructive and must
  5344. # depend on a size we actually had, not on one we hoped was there.
  5345. expected_size = target.get("size")
  5346. timelapse_data = await download_file_bytes_async(
  5347. printer.ip_address,
  5348. printer.access_code,
  5349. remote_path,
  5350. printer_model=printer.model,
  5351. expected_size=expected_size,
  5352. )
  5353. if not timelapse_data:
  5354. # Short or failed transfer. The printer keeps its copy, so the next
  5355. # round can try again — which is exactly why the delete below is
  5356. # gated on a verified download.
  5357. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  5358. return False
  5359. # The length check above proves we got what the listing said, not that the
  5360. # printer had finished writing. A video still being written can be listed
  5361. # short, served short, and pass — so confirm it has stopped growing before
  5362. # committing to it and deleting the original (#2704).
  5363. if not await remote_file_settled(
  5364. printer.ip_address,
  5365. printer.access_code,
  5366. remote_path,
  5367. len(timelapse_data),
  5368. printer_model=printer.model,
  5369. ):
  5370. return False
  5371. # Write phase: attach in a fresh short-lived session.
  5372. async with async_session() as db:
  5373. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, file_name)
  5374. if not success:
  5375. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  5376. return False
  5377. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  5378. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  5379. await delete_archived_timelapse(
  5380. printer.ip_address,
  5381. printer.access_code,
  5382. remote_path,
  5383. verified=expected_size is not None,
  5384. printer_model=printer.model,
  5385. printer_name=printer.name,
  5386. )
  5387. return True
  5388. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  5389. # module-level so tests can monkeypatch them down to ~0 without timing out.
  5390. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  5391. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  5392. # How long the *background* upgrade keeps waiting after the notification has
  5393. # already gone out (#2704 follow-up). The short bound above exists so a slow
  5394. # printer can't hold up the print-complete notification; this one exists so the
  5395. # archive still ends up with the better frame afterwards.
  5396. #
  5397. # Measured across 261 attaches in the support bundles, the video lands a median
  5398. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  5399. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  5400. # was 546s. Every other model was inside 26s. The long budget is therefore
  5401. # almost entirely for P1-series users; on everything else the short wait already
  5402. # wins and this task never runs.
  5403. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  5404. async def _capture_finish_photo_from_timelapse(
  5405. archive_id: int,
  5406. archive_dir: Path,
  5407. timeout: float | None = None,
  5408. rotation: int = 0,
  5409. ) -> tuple[str | None, bool]:
  5410. """Wait for the per-print timelapse to land on the archive and extract its
  5411. last frame as the finish photo (#1397).
  5412. Bambu firmware stops timelapse recording after the toolhead parks but
  5413. before the bed-drop end-gcode runs, so the last frame frames the finished
  5414. print correctly. A live camera grab at gcode_state=FINISH captures the
  5415. bed already lowered.
  5416. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  5417. ``archive.timelapse_path`` when the file lands. This function polls for
  5418. that field.
  5419. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  5420. the wait ran out with no video on the archive yet — i.e. the video may
  5421. still be coming and a later attempt could succeed. It is False when the
  5422. video landed (whether or not extraction worked), because in that case
  5423. waiting longer changes nothing. The caller uses that to decide between
  5424. falling back permanently and scheduling a background upgrade.
  5425. ``rotation`` is the printer's camera_rotation, applied to the extracted
  5426. still (#2708) so this source agrees with every other finish-photo source.
  5427. The archived video itself is the printer's own file and is left alone —
  5428. rotating it would mean re-encoding it.
  5429. """
  5430. import uuid
  5431. from backend.app.models.archive import PrintArchive
  5432. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  5433. logger = logging.getLogger(__name__)
  5434. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  5435. deadline = asyncio.get_event_loop().time() + budget
  5436. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  5437. while True:
  5438. async with async_session() as db:
  5439. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5440. archive = result.scalar_one_or_none()
  5441. timelapse_relpath = archive.timelapse_path if archive else None
  5442. if timelapse_relpath:
  5443. video_path = app_settings.base_dir / timelapse_relpath
  5444. if video_path.exists() and video_path.stat().st_size > 0:
  5445. photos_dir = archive_dir / "photos"
  5446. photos_dir.mkdir(parents=True, exist_ok=True)
  5447. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5448. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  5449. output_path = photos_dir / filename
  5450. if await extract_video_last_frame(video_path, output_path):
  5451. await apply_camera_rotation_to_file(output_path, rotation, logger)
  5452. logger.info(
  5453. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  5454. video_path.name,
  5455. archive_id,
  5456. )
  5457. return filename, False
  5458. logger.warning(
  5459. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  5460. video_path.name,
  5461. archive_id,
  5462. )
  5463. return None, False
  5464. if asyncio.get_event_loop().time() >= deadline:
  5465. logger.info(
  5466. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  5467. archive_id,
  5468. budget,
  5469. )
  5470. return None, True
  5471. await asyncio.sleep(poll_interval)
  5472. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  5473. """Add the timelapse's last frame to an archive after the fact (#2704).
  5474. The print-complete notification waits only ~60s for the video, because
  5475. holding a notification for minutes is worse than sending it with a live
  5476. camera grab. On a P1-series printer the video often lands well after that,
  5477. so the archive used to be stuck with the live grab — which is taken at
  5478. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  5479. the worse photo of the two.
  5480. This keeps waiting in the background and, when the video arrives, extracts
  5481. the frame and puts it *first* in the archive's photo list, so opening the
  5482. gallery shows it. The live grab is deliberately kept: the notification that
  5483. already went out links to that exact file, and deleting it would leave a
  5484. broken image in Discord or Telegram.
  5485. """
  5486. logger = logging.getLogger(__name__)
  5487. filename, _ = await _capture_finish_photo_from_timelapse(
  5488. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  5489. )
  5490. if not filename:
  5491. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  5492. return
  5493. try:
  5494. async with async_session() as db:
  5495. from backend.app.models.archive import PrintArchive
  5496. archive = await db.get(PrintArchive, archive_id)
  5497. if archive is None:
  5498. return
  5499. photos = list(archive.photos or [])
  5500. if filename in photos:
  5501. return
  5502. # Front of the list: PhotoGalleryModal opens at index 0.
  5503. archive.photos = [filename, *photos]
  5504. await db.commit()
  5505. except Exception as e:
  5506. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  5507. return
  5508. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  5509. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  5510. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  5511. """Put the filament-attribution context back after a restart mid-print.
  5512. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  5513. both die with the process. The print keeps running, so at completion the
  5514. tracker would fall back to whatever the printer reports *now* — and AMS
  5515. filament backup makes "now" the substitute tray, charging the whole print
  5516. to the spool that only finished it.
  5517. The persisted row is only trusted when its print name still matches what
  5518. the printer says it is running: a row left behind by a completion we never
  5519. saw must not attach itself to the next print.
  5520. """
  5521. try:
  5522. from backend.app.api.routes.settings import get_setting
  5523. from backend.app.services.usage_tracker import (
  5524. clear_persisted_session,
  5525. get_persisted_print_name,
  5526. restore_session,
  5527. )
  5528. persisted_name = await get_persisted_print_name(db, printer_id)
  5529. current_name = (state.subtask_name or "").strip()
  5530. if persisted_name and current_name and persisted_name.strip() != current_name:
  5531. logger.info(
  5532. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  5533. printer_id,
  5534. persisted_name,
  5535. current_name,
  5536. )
  5537. await clear_persisted_session(db, printer_id)
  5538. # Fall through to seeding: the print on the printer is real, it just
  5539. # isn't the one the row described.
  5540. persisted_log = None
  5541. else:
  5542. # Spoolman users get the tray-change log back but no in-memory
  5543. # session — see ``on_print_start`` on why that dict is load-bearing
  5544. # for the remain%-sync guard.
  5545. _spoolman_on = await get_setting(db, "spoolman_enabled")
  5546. persisted_log = await restore_session(
  5547. db,
  5548. printer_id,
  5549. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  5550. )
  5551. if persisted_log:
  5552. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  5553. # Anything this process already observed goes after the persisted
  5554. # history — the log is ordered by layer, and a fresh process can
  5555. # only have seen changes from later in the print.
  5556. for entry in state.tray_change_log or []:
  5557. if tuple(entry) not in restored:
  5558. restored.append(tuple(entry))
  5559. state.tray_change_log = restored
  5560. tray_now = state.tray_now
  5561. if 0 <= tray_now <= 254:
  5562. if not state.tray_change_log:
  5563. # No persisted history — a print that started before this build,
  5564. # or before the row existed. Seed with the tray feeding right
  5565. # now so the remainder of the print is at least attributable to
  5566. # the right spool.
  5567. state.tray_change_log = [(tray_now, state.layer_num)]
  5568. logger.info(
  5569. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  5570. printer_id,
  5571. tray_now,
  5572. state.layer_num,
  5573. )
  5574. # The tray handler updates ``last_loaded_tray`` on every push
  5575. # regardless of whether it logged a change, so re-align it to avoid
  5576. # a duplicate entry on the next push. Only ever with a real tray:
  5577. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  5578. # 255" fallback, and writing 255 into it would defeat that.
  5579. state.last_loaded_tray = tray_now
  5580. except Exception:
  5581. # Never let attribution recovery cost the caller its timelapse
  5582. # baseline — that capture has to happen before the printer uploads
  5583. # the in-flight MP4 and there is no second chance at it.
  5584. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  5585. async def on_print_running_observed(printer_id: int, data: dict):
  5586. """Restart-recovery for a print that started before Bambuddy came up.
  5587. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  5588. after Bambuddy startup (#1304 guard, prevents duplicate archive
  5589. creation). This hook restores the persisted archive into ``_active_prints``
  5590. and captures the timelapse baseline that normally hangs off print start.
  5591. Fires once per session, in lieu of on_print_start when restart-recovery
  5592. kicks in. The printer doesn't upload the timelapse until after PRINT
  5593. COMPLETE, so a baseline captured any time during the print is still
  5594. pre-upload.
  5595. """
  5596. logger = logging.getLogger(__name__)
  5597. async with async_session() as db:
  5598. from backend.app.models.printer import Printer
  5599. state = printer_manager.get_status(printer_id)
  5600. if state is not None:
  5601. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  5602. if authorization is True:
  5603. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  5604. await _restore_usage_tracking_session(printer_id, state, db, logger)
  5605. await _restore_printable_objects(printer_id, state, db, logger)
  5606. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5607. printer = result.scalar_one_or_none()
  5608. if not printer:
  5609. logger.warning(
  5610. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  5611. printer_id,
  5612. )
  5613. return
  5614. # Avoid double-capture: ownership reconciliation above must still run when
  5615. # a baseline already exists, but the camera work itself is one-shot.
  5616. if printer_id in _timelapse_baselines:
  5617. logger.debug(
  5618. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  5619. printer_id,
  5620. )
  5621. return
  5622. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  5623. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  5624. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  5625. against the printer's current MQTT state.
  5626. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  5627. COMPLETE events, typically a print finishing during an MQTT disconnect
  5628. window followed by a smart-plug power cycle):
  5629. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  5630. provably not running anymore — only branch that should fire under
  5631. normal disconnect-then-reconnect timing.
  5632. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  5633. firmware mints a fresh ``subtask_id`` for each print, including the
  5634. ghost replay it runs after a power cycle from a leftover SD file —
  5635. so a mismatch unambiguously means the in-DB archive is no longer
  5636. the print on the printer.
  5637. 3. Printer is running but ``subtask_name`` is empty. The printer
  5638. doesn't know what it's running; the archive's reference to it is
  5639. already broken.
  5640. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  5641. with matching subtask_id+subtask_name is left alone. The cost of a false
  5642. positive is a duplicate archive on the next real PRINT COMPLETE — the
  5643. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  5644. clears on synthesis, so the real completion creates a fresh row instead
  5645. of overwriting the synthesised one (#1679). The cost of a false negative
  5646. is the ghost-print loop in #1542.
  5647. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  5648. MQTT has connected but the first ``push_status`` response hasn't been
  5649. applied yet — ``PrinterState`` is sitting on its construction defaults.
  5650. The reconcile caller in ``on_printer_status_change`` is already gated
  5651. on a real ``state.state``, so in normal operation this branch is
  5652. unreachable; it's kept as belt-and-braces for future callers and for
  5653. the narrow window where a partial state update could arrive
  5654. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  5655. ``not stale`` on degenerate input is strictly conservative: a real
  5656. stale archive will still be caught by the next push_status arriving
  5657. with terminal state.
  5658. """
  5659. current_state = (state.state or "").upper()
  5660. if current_state in ("", "UNKNOWN"):
  5661. # No real push_status yet — PrinterState defaults are not evidence.
  5662. return False, ""
  5663. if current_state in ("IDLE", "FINISH", "FAILED"):
  5664. return True, f"printer state {current_state}"
  5665. # Below here the printer is in a running / pre-running state (RUNNING /
  5666. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  5667. current_subtask_id = (state.subtask_id or "").strip()
  5668. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  5669. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  5670. current_subtask_name = (state.subtask_name or "").strip()
  5671. if not current_subtask_name:
  5672. return True, "printer subtask_name empty"
  5673. return False, ""
  5674. async def prime_kprofile_table(printer_id: int) -> int:
  5675. """Read the printer's calibration table once per connection.
  5676. The AMS slot card shows a K value per slot (#2854). On the printers whose
  5677. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  5678. report ``cali_idx`` and nothing else -- that number can only come from
  5679. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  5680. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  5681. backup, or the printer answering a query BambuStudio made on the report
  5682. topic we share. A Bambuddy that nobody visited showed a card with no K
  5683. values at all.
  5684. Only the diameters actually fitted are asked for, which is one request on a
  5685. single-nozzle printer and two on a dual. Probing the four sizes blind is
  5686. what the backup does, and it is both wasteful and the thing that used to
  5687. blank the table.
  5688. Returns the number of nozzles whose table was read.
  5689. """
  5690. client = printer_manager.get_client(printer_id)
  5691. state = printer_manager.get_status(printer_id)
  5692. if client is None or state is None or not state.connected:
  5693. return 0
  5694. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  5695. # ask once, and both entries are empty until the first push_status lands.
  5696. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  5697. if not diameters:
  5698. logging.getLogger(__name__).debug(
  5699. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  5700. printer_id,
  5701. )
  5702. return 0
  5703. primed = 0
  5704. for diameter in diameters:
  5705. try:
  5706. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  5707. except Exception as exc: # noqa: BLE001
  5708. # A printer that won't answer costs the card its K values, nothing
  5709. # more — never the connection this runs on the back of.
  5710. logging.getLogger(__name__).warning(
  5711. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  5712. )
  5713. continue
  5714. primed += 1
  5715. logging.getLogger(__name__).info(
  5716. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  5717. )
  5718. return primed
  5719. def _sd_files_in_use(state) -> set[str]:
  5720. """Names of the SD-card files the printer may be printing right now (#3009).
  5721. The post-print cleanup works out what to delete from the finished archive,
  5722. not from the printer. When reconciliation closes an old archive because the
  5723. printer has moved on to a new job, and that job is the same file reprinted
  5724. from the printer's screen, the cleanup would delete the file mid-print.
  5725. Empty unless the printer is busy: on an ordinary completion the state is
  5726. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  5727. name, a path or a URL depending on firmware, and some report only the
  5728. plate's G-code, so the job name is matched as well, in the same spellings
  5729. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  5730. ignores case.
  5731. """
  5732. def _text(value) -> str:
  5733. return value.strip() if isinstance(value, str) else ""
  5734. if state is None:
  5735. return set()
  5736. current_state = _text(getattr(state, "state", None)).upper()
  5737. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  5738. return set()
  5739. in_use: set[str] = set()
  5740. gcode_file = _text(getattr(state, "gcode_file", None))
  5741. if gcode_file:
  5742. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  5743. # both legal in a file name, and raises on some inputs.
  5744. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  5745. if name:
  5746. in_use.add(name.lower())
  5747. subtask_name = _text(getattr(state, "subtask_name", None))
  5748. if subtask_name:
  5749. for name in (subtask_name, subtask_name.replace(" ", "_")):
  5750. for ext in (".3mf", ".gcode"):
  5751. in_use.add(f"{name}{ext}".lower())
  5752. return in_use
  5753. async def reconcile_stale_active_prints(printer_id: int) -> int:
  5754. """Synthesise ``on_print_complete`` for archives whose print can't be
  5755. running on the printer anymore.
  5756. Called once per MQTT (re)connection (from on_printer_status_change when
  5757. the connected edge flips False → True) and at Bambuddy startup (from
  5758. the FastAPI lifespan). Without this, a print that completes during a
  5759. disconnect window — followed by a smart-plug-driven power cycle — leaves
  5760. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  5761. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  5762. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  5763. power cycle until the operator notices (#1542 follow-up). Reconciliation
  5764. closes the loop by faking the missed PRINT COMPLETE — the existing
  5765. cleanup chain handles SD-file deletion, status updates, usage tracking,
  5766. and notifications.
  5767. Synthesised ``status="aborted"`` is the conservative label: we have no
  5768. proof the print finished successfully (and no progress evidence to
  5769. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  5770. fires later, overwrites the status with the correct value.
  5771. Returns the number of archives reconciled.
  5772. """
  5773. state = printer_manager.get_status(printer_id)
  5774. if not state:
  5775. return 0
  5776. # Don't reconcile while disconnected — we'd be making a decision against
  5777. # stale cached state. The connected → reconcile edge handles this.
  5778. if not state.connected:
  5779. return 0
  5780. from backend.app.models.archive import PrintArchive
  5781. reconciled = 0
  5782. async with async_session() as db:
  5783. result = await db.execute(
  5784. select(PrintArchive).where(
  5785. PrintArchive.printer_id == printer_id,
  5786. PrintArchive.status == "printing",
  5787. )
  5788. )
  5789. active = list(result.scalars().all())
  5790. if not active:
  5791. return 0
  5792. logger = logging.getLogger(__name__)
  5793. for archive in active:
  5794. is_stale, reason = _is_active_archive_stale(archive, state)
  5795. if not is_stale:
  5796. continue
  5797. logger.info(
  5798. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  5799. printer_id,
  5800. archive.id,
  5801. archive.filename,
  5802. reason,
  5803. )
  5804. # Synthesised payload: minimal fields the on_print_complete chain
  5805. # needs. `_reconciled` marker lets downstream code distinguish this
  5806. # from a real MQTT-driven completion if it ever needs to (e.g. for
  5807. # metrics / debug logging). raw_data is the live printer state so
  5808. # the usage tracker can compare end-of-print remain% against the
  5809. # captured start values.
  5810. try:
  5811. await on_print_complete(
  5812. printer_id,
  5813. {
  5814. "status": "aborted",
  5815. "filename": archive.filename,
  5816. "subtask_name": archive.print_name or "",
  5817. "subtask_id": archive.subtask_id or "",
  5818. "raw_data": state.raw_data or {},
  5819. "_reconciled": True,
  5820. },
  5821. )
  5822. reconciled += 1
  5823. except Exception as e:
  5824. # Catch-all: a reconciliation failure must not block the
  5825. # printer's normal status flow. The archive stays in
  5826. # ``status="printing"`` and the next reconnect retries.
  5827. logger.warning(
  5828. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  5829. archive.id,
  5830. e,
  5831. )
  5832. return reconciled
  5833. # #2547: clearance left between the nozzle and the top of the print when the
  5834. # plate is commanded back into camera framing. The nozzle is parked away from
  5835. # the part by then, so this is belt-and-braces against a max_z_height that
  5836. # under-reports (e.g. a slicer that excludes a final Z hop).
  5837. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  5838. # How far below the restored position to drop the plate again afterwards, so
  5839. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  5840. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  5841. # on machines with less headroom.
  5842. _PLATE_PARK_DROP_MM = 100.0
  5843. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  5844. # this axis, so it is a proven-safe speed for the full travel.
  5845. _PLATE_RESTORE_FEEDRATE = 600
  5846. # Time allowed for the plate to reach the restored position before the camera
  5847. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  5848. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  5849. # How long `_background_finish_photo` waits for this producer. Must cover the
  5850. # settle window plus a worst-case RTSP grab (15s), and stay below the
  5851. # notification path's own photo wait so a slow producer degrades to a
  5852. # photo-less notification rather than a missed one. The chamber light's
  5853. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  5854. # camera_light.MAX_DELAY_SECONDS stays below it.
  5855. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  5856. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  5857. """The ``_active_prints`` keys a finished print may be registered under.
  5858. Matching how they were registered in on_print_start. Shared by
  5859. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  5860. to find the same binding.
  5861. """
  5862. possible_keys = []
  5863. # Try subtask_name variations first (most reliable for matching)
  5864. if subtask_name:
  5865. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  5866. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  5867. possible_keys.append((printer_id, subtask_name))
  5868. # Try filename variations
  5869. if filename:
  5870. # Extract just the filename if it's a path
  5871. fname = filename.split("/")[-1] if "/" in filename else filename
  5872. if fname.endswith(".3mf"):
  5873. possible_keys.append((printer_id, fname))
  5874. elif fname.endswith(".gcode"):
  5875. base_name = fname.rsplit(".", 1)[0]
  5876. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  5877. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5878. possible_keys.append((printer_id, fname))
  5879. else:
  5880. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  5881. possible_keys.append((printer_id, f"{fname}.3mf"))
  5882. possible_keys.append((printer_id, fname))
  5883. # Also try full path versions
  5884. if filename.endswith(".3mf"):
  5885. possible_keys.append((printer_id, filename))
  5886. elif filename.endswith(".gcode"):
  5887. base_name = filename.rsplit(".", 1)[0]
  5888. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5889. possible_keys.append((printer_id, filename))
  5890. else:
  5891. possible_keys.append((printer_id, f"{filename}.3mf"))
  5892. possible_keys.append((printer_id, filename))
  5893. return possible_keys
  5894. def _archive_name_forms(archive) -> set[str]:
  5895. """The names an archive could be echoed back as, in normalised form (#3240).
  5896. Its print name, and its filename with and without the 3MF extension.
  5897. """
  5898. forms = set()
  5899. if archive.print_name:
  5900. forms.add(_normalise_subtask_name(archive.print_name))
  5901. if archive.filename:
  5902. forms.add(_normalise_subtask_name(archive.filename))
  5903. for suffix in (".gcode.3mf", ".3mf"):
  5904. if archive.filename.lower().endswith(suffix):
  5905. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  5906. forms.discard("")
  5907. return forms
  5908. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  5909. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  5910. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  5911. from the plate recorded when the job was dispatched. Neither is touched:
  5912. ``on_print_complete`` pops both, which is why the finish-photo producer
  5913. calls this before its first await, while they are still there.
  5914. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  5915. archive, or that it only knows by a name -- and on any error: the producer
  5916. calls this before the ``try`` that always releases the photo consumer, so
  5917. it must not raise.
  5918. """
  5919. try:
  5920. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  5921. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  5922. if archive_id is None:
  5923. return None, None
  5924. return archive_id, _print_plate_ids.get(archive_id)
  5925. except Exception:
  5926. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  5927. return None, None
  5928. async def _max_z_for_current_print(
  5929. printer_id: int,
  5930. data: dict,
  5931. logger,
  5932. archive_id: int | None,
  5933. plate_id: int | None = None,
  5934. ) -> float | None:
  5935. """Height of the print that just finished on ``printer_id``, or None (#2547).
  5936. This number becomes the target of a real Z move, so every step here refuses
  5937. rather than guesses. A height belonging to some *other* print is the one
  5938. failure that could drive the nozzle into the model: 20 mm carried onto a
  5939. 200 mm print would command the plate up through the part.
  5940. Three independent things therefore have to agree before a height is
  5941. returned:
  5942. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  5943. when it started (see ``_bound_print``), never one found by name. A name
  5944. is not an identity: every plate of a multi-plate file shares one, and a
  5945. reprint reuses its archive row, so the newest archive with the right
  5946. name can be another plate of the same file. Support bundles show the
  5947. old name lookup doing exactly that (archive 288 for a print bound to
  5948. 169, 313 layers against 125), stopped only by the layer check below.
  5949. No binding, no move.
  5950. 2. **Identity.** The bound archive's name still has to be the finished
  5951. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  5952. because the printer echoes spaces as underscores (#3240). Exact: not a
  5953. substring, and not the completion check's tolerance for a truncated
  5954. echo.
  5955. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  5956. match the layer count the printer itself reported over MQTT for the print
  5957. that just ended. These come from genuinely different sources, so a
  5958. mismatch means the row is not this print, whatever its name says.
  5959. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  5960. plate of a multi-plate file reuses the archive row without updating its
  5961. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  5962. ``on_print_complete`` may already have flipped the status by the time we
  5963. run.
  5964. """
  5965. subtask_name = (data.get("subtask_name") or "").strip()
  5966. if not subtask_name:
  5967. # Nothing to identify the print by — refuse rather than fall back to
  5968. # "whatever ran last on this printer".
  5969. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  5970. return None
  5971. if archive_id is None:
  5972. logger.info(
  5973. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  5974. printer_id,
  5975. subtask_name,
  5976. )
  5977. return None
  5978. try:
  5979. from backend.app.models.archive import PrintArchive
  5980. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  5981. async with async_session() as db:
  5982. result = await db.execute(
  5983. select(PrintArchive).where(
  5984. PrintArchive.id == archive_id,
  5985. PrintArchive.printer_id == printer_id,
  5986. PrintArchive.status.in_(("printing", "completed")),
  5987. PrintArchive.deleted_at.is_(None),
  5988. )
  5989. )
  5990. archive = result.scalar_one_or_none()
  5991. if archive is None or not archive.file_path:
  5992. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  5993. return None
  5994. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  5995. logger.warning(
  5996. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  5997. printer_id,
  5998. archive_id,
  5999. subtask_name,
  6000. )
  6001. return None
  6002. client = printer_manager.get_client(printer_id)
  6003. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  6004. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  6005. logger.warning(
  6006. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  6007. "— refusing to move the plate on a height that may not be this print's",
  6008. printer_id,
  6009. archive.id,
  6010. archive.total_layers,
  6011. reported_layers,
  6012. )
  6013. return None
  6014. # Stored relative to the data directory, like every other archive path
  6015. # (#3240: this read a `data_dir` setting that does not exist).
  6016. path = app_settings.base_dir / archive.file_path
  6017. plate = plate_id or archive.plate_id or 1
  6018. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  6019. except Exception as e:
  6020. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  6021. return None
  6022. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  6023. """Raise the plate back into camera framing before the finish photo (#2547).
  6024. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  6025. the time ``gcode_state`` reaches FINISH the finished print sits far below
  6026. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  6027. This commands an absolute ``G1 Z`` back to just above the last printed
  6028. layer.
  6029. Absolute, not relative, is the whole safety argument. ``max_z_height +
  6030. clearance`` is a height the toolhead was physically at seconds earlier, so
  6031. it is inside the travel limits by construction and leaves the nozzle above
  6032. the part. It is also unambiguous across model families: Z is the
  6033. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  6034. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  6035. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  6036. (#2579).
  6037. Returns True if the move was sent and waited out, False if it was skipped.
  6038. """
  6039. client = printer_manager.get_client(printer_id)
  6040. if client is None:
  6041. return False
  6042. # Re-read state immediately before commanding motion. If the queue has
  6043. # already started the next print, the printer is no longer ours to move.
  6044. state = getattr(client, "state", None)
  6045. if state is None or state.state != "FINISH":
  6046. logger.info(
  6047. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  6048. printer_id,
  6049. getattr(state, "state", "unknown"),
  6050. )
  6051. return False
  6052. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  6053. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  6054. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  6055. return False
  6056. logger.info(
  6057. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  6058. printer_id,
  6059. target_z,
  6060. max_z_height,
  6061. _PLATE_RESTORE_CLEARANCE_MM,
  6062. _PLATE_RESTORE_SETTLE_SECONDS,
  6063. )
  6064. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  6065. return True
  6066. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  6067. """Drop the plate again after the finish photo (#2547).
  6068. Without this the user walks up to a finished print sitting just under the
  6069. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  6070. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  6071. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  6072. print homes anyway.
  6073. """
  6074. client = printer_manager.get_client(printer_id)
  6075. state = getattr(client, "state", None) if client else None
  6076. if client is None or state is None or state.state != "FINISH":
  6077. return
  6078. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  6079. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  6080. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  6081. """True if a queue item is about to take this printer (#2547).
  6082. The scheduler dispatches the next job the moment a print completes, and a
  6083. plate move interleaved with a print start is not a race worth having. The
  6084. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  6085. this window; this closes the head of it.
  6086. """
  6087. try:
  6088. from backend.app.models.print_queue import PrintQueueItem
  6089. async with async_session() as db:
  6090. result = await db.execute(
  6091. select(PrintQueueItem.id)
  6092. .where(
  6093. PrintQueueItem.printer_id == printer_id,
  6094. PrintQueueItem.status.in_(("pending", "printing")),
  6095. )
  6096. .limit(1)
  6097. )
  6098. return result.scalar_one_or_none() is not None
  6099. except Exception as e:
  6100. # Fail closed: if we can't tell, don't move the plate.
  6101. logging.getLogger(__name__).debug(
  6102. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  6103. )
  6104. return True
  6105. async def on_finish_photo_moment(printer_id: int, data: dict):
  6106. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  6107. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  6108. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  6109. fallback for prints that skip stage 22 (cancel, external-spool-only,
  6110. HMS halt, firmware variants). Grabs one frame via the same
  6111. external-camera / RTSP path the post-completion fallback uses, stores
  6112. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  6113. ``_background_finish_photo`` consume the cached bytes when it runs.
  6114. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  6115. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  6116. set to Smooth (#1721). No force-on now means the user's explicit
  6117. timelapse=off in the slicer send dialog is respected.
  6118. """
  6119. logger = logging.getLogger(__name__)
  6120. trigger = data.get("trigger", "unknown")
  6121. timelapse_was_active = bool(data.get("timelapse_was_active"))
  6122. logger.info(
  6123. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  6124. printer_id,
  6125. trigger,
  6126. timelapse_was_active,
  6127. )
  6128. # If a timelapse is actively recording, skip the pre-capture — the
  6129. # post-completion path will extract the last frame from the recorded
  6130. # video, which still provides the best framing (toolhead parked,
  6131. # before bed drop) without the per-layer parking side effects.
  6132. if timelapse_was_active:
  6133. logger.info(
  6134. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  6135. printer_id,
  6136. )
  6137. return
  6138. # #1790: register the producer-done event BEFORE the first await so the
  6139. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  6140. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  6141. # The `finally` below guarantees `set()` runs on every exit, including
  6142. # early returns and exceptions, so the consumer's bounded wait can't hang.
  6143. producer_done = asyncio.Event()
  6144. _stage22_finish_in_flight[printer_id] = producer_done
  6145. # #3240: also before the first await. On the FINISH-state path
  6146. # `on_print_complete` is dispatched right behind us and pops both the
  6147. # print's archive binding and its plate; read here, they are still there.
  6148. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  6149. # #2547: set once the plate has actually been raised, and read by the
  6150. # `finally` below. Declared out here so a failure anywhere after the move —
  6151. # a camera timeout, a DB error — still lowers the plate again.
  6152. restore_max_z: float | None = None
  6153. try:
  6154. async with async_session() as db:
  6155. from backend.app.api.routes.settings import get_setting
  6156. from backend.app.models.printer import Printer
  6157. capture_setting = await get_setting(db, "capture_finish_photo")
  6158. if capture_setting is not None and capture_setting.lower() != "true":
  6159. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  6160. return
  6161. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  6162. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  6163. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6164. printer = result.scalar_one_or_none()
  6165. if printer is None:
  6166. logger.warning(
  6167. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  6168. printer_id,
  6169. )
  6170. return
  6171. frame_bytes: bytes | None = None
  6172. # #2708: the banked frame arrives already rotated — it comes from
  6173. # `_capture_snapshot_for_notification`, which rotates before returning.
  6174. # Every other source below is a raw grab. Tracking which lets us store
  6175. # exactly one rotation in `_stage22_finish_frames` either way.
  6176. frame_already_rotated = False
  6177. # On the FINISH-state path the End G-code has already run, and two very
  6178. # different situations arrive here needing opposite answers.
  6179. #
  6180. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  6181. # snippet may have ejected the plate — the scene in front of the camera
  6182. # is no longer the finished print, and no amount of moving the plate
  6183. # brings it back. Use the banked in-print frame instead.
  6184. #
  6185. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  6186. # than the camera frames well, and the toolhead is parked out of the
  6187. # way. That is the *best* moment available on firmware that never emits
  6188. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  6189. # back. Preferring the bank here unconditionally, as this code used to,
  6190. # is what shipped a mid-print photo with the toolhead over the part.
  6191. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  6192. banked = _inprint_frame_bank.get(printer_id)
  6193. if banked:
  6194. frame_bytes = banked
  6195. frame_already_rotated = True
  6196. logger.info(
  6197. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  6198. "frame (%d bytes) instead of a post-swap live grab",
  6199. len(banked),
  6200. )
  6201. else:
  6202. logger.warning(
  6203. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  6204. "in-print bank is empty — falling back to a live grab, which may show a "
  6205. "swapped or empty plate",
  6206. printer_id,
  6207. )
  6208. # `restore_max_z` is set only once the plate is actually up, because the
  6209. # `finally` reads it to decide whether it owes a move back down.
  6210. #
  6211. # Never on a print whose End G-code Bambuddy injected, even when the bank
  6212. # came up empty above: that machine may have just ejected its plate, and
  6213. # driving Z into whatever a swap mechanism is doing is not a risk worth
  6214. # taking for a photo of a bed we already know may be bare.
  6215. if (
  6216. frame_bytes is None
  6217. and trigger == "finish_state"
  6218. and restore_plate_enabled
  6219. and not print_dispatch_context.end_gcode_injected(printer_id)
  6220. ):
  6221. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  6222. if wants_restore is None:
  6223. logger.info(
  6224. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  6225. printer_id,
  6226. )
  6227. elif await _plate_restore_is_blocked_by_queue(printer_id):
  6228. logger.info(
  6229. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  6230. printer_id,
  6231. )
  6232. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  6233. restore_max_z = wants_restore
  6234. # Chamber light for the live capture below (#1655). The banked frame
  6235. # above was taken without it, like every in-print bank.
  6236. async with camera_light(printer if frame_bytes is None else None):
  6237. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  6238. from backend.app.api.routes.camera import live_frame_for_capture
  6239. from backend.app.services.external_camera import capture_frame
  6240. # #2707: this used to collide with the live view and fail, which is
  6241. # how finish-photo notifications went out with no image attached.
  6242. # Leaving frame_bytes None keeps the rest of the fallback chain.
  6243. defer, buffered = live_frame_for_capture(printer_id)
  6244. if defer:
  6245. frame_bytes = buffered
  6246. else:
  6247. frame_bytes = await capture_frame(
  6248. printer.external_camera_url,
  6249. printer.external_camera_type or "mjpeg",
  6250. snapshot_url=printer.external_camera_snapshot_url,
  6251. )
  6252. if frame_bytes:
  6253. logger.info(
  6254. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  6255. len(frame_bytes),
  6256. )
  6257. elif frame_bytes is None:
  6258. from backend.app.api.routes.camera import get_buffered_frame
  6259. buffered = get_buffered_frame(printer_id)
  6260. if buffered:
  6261. frame_bytes = buffered
  6262. logger.info(
  6263. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  6264. len(frame_bytes),
  6265. )
  6266. else:
  6267. from backend.app.services.camera import capture_camera_frame_bytes
  6268. frame_bytes = await capture_camera_frame_bytes(
  6269. ip_address=printer.ip_address,
  6270. access_code=printer.access_code,
  6271. model=printer.model,
  6272. timeout=15,
  6273. )
  6274. if frame_bytes:
  6275. logger.info(
  6276. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  6277. len(frame_bytes),
  6278. )
  6279. if frame_bytes:
  6280. if not frame_already_rotated:
  6281. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  6282. _stage22_finish_frames[printer_id] = frame_bytes
  6283. else:
  6284. logger.warning(
  6285. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  6286. printer_id,
  6287. )
  6288. except Exception as e:
  6289. logger.warning(
  6290. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  6291. printer_id,
  6292. e,
  6293. )
  6294. finally:
  6295. # #2547: we raised the plate, so we own lowering it — including when the
  6296. # capture above failed or threw partway through.
  6297. if restore_max_z is not None:
  6298. try:
  6299. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  6300. except Exception as e:
  6301. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6302. # #1790: always unblock the consumer's bounded wait — whether we stored
  6303. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  6304. # dict entry by the consumer doesn't affect signalling.
  6305. producer_done.set()
  6306. def _subtask_name_from_filename(filename: str) -> str:
  6307. """Recover the subtask name a print command would have carried for *filename*.
  6308. The dispatcher derives the printer-facing subtask name from the archive's
  6309. file name, so stripping the extensions back off gives the value MQTT echoes
  6310. on completion. Only the two extensions Bambuddy actually stores are removed,
  6311. and in the order they nest (``.gcode.3mf``), so a model whose own name
  6312. contains a dot -- ``My.Model.3mf`` -- keeps it.
  6313. """
  6314. name = PurePosixPath(filename).name
  6315. for suffix in (".3mf", ".gcode"):
  6316. if name.lower().endswith(suffix):
  6317. name = name[: -len(suffix)]
  6318. return name
  6319. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  6320. """Whether the subtask name is the printed 3MF's own file name.
  6321. A print started from the printer's screen reports the same full name, with
  6322. its extension, as both subtask and file (#3009). A dispatched print reports
  6323. a bare subtask name; one that merely ends in ".3mf" can be a model named
  6324. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  6325. """
  6326. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  6327. return False
  6328. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  6329. # How the printer marks a subtask name it had to cut short. Observed on real
  6330. # hardware at ~100 characters, but the cut-off is not a fixed character count
  6331. # (a name with multibyte characters came back at 98), so match the marker
  6332. # rather than a length.
  6333. _SUBTASK_TRUNCATION_MARKER = "..."
  6334. def _normalise_subtask_name(name: str) -> str:
  6335. """Canonical form for comparing a dispatched name against MQTT's echo.
  6336. The printer does not echo the name back verbatim: it substitutes
  6337. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  6338. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  6339. The 3MF lookup in this module has always known that -- it builds
  6340. space-to-underscore variants of every candidate filename, and its
  6341. directory search normalises both sides before comparing. This exists so
  6342. the completion check reads the same rule from the same place instead of
  6343. growing its own, which is exactly how it came to disagree (#2829).
  6344. A space at either end is substituted too: ``Part .gcode.3mf`` is
  6345. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  6346. are dropped after the substitution so both sides agree (#3241).
  6347. """
  6348. return name.strip().replace(" ", "_").strip("_").casefold()
  6349. def _subtask_names_match(expected: str, observed: str) -> bool:
  6350. """Whether two subtask names describe the same print.
  6351. Beyond the space/underscore substitution, the printer truncates long names
  6352. and marks the cut with ``...``. A truncated echo has to count as a match or
  6353. every print with a long name strands its queue item the same way.
  6354. """
  6355. expected_n = _normalise_subtask_name(expected)
  6356. observed_n = _normalise_subtask_name(observed)
  6357. if expected_n == observed_n:
  6358. return True
  6359. # Either side can be the truncated one: the printer truncates what it
  6360. # echoes, and an archive whose own filename was recorded from a previous
  6361. # truncated echo carries the marker too.
  6362. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  6363. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  6364. continue
  6365. # The full side has lost its edge underscores; a cut that lands right
  6366. # after one keeps it, so drop it here too (#3241). Nothing left before
  6367. # the marker is no evidence of anything, and must not match every name.
  6368. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  6369. if kept and full.startswith(kept):
  6370. return True
  6371. return False
  6372. async def _queue_item_dispatched_name(db, item) -> str:
  6373. """The subtask name *item* was dispatched under, or "" when unknowable.
  6374. A row with no archive, or an archive with no file name, is unverifiable
  6375. rather than wrong; every caller answers that with its permissive branch.
  6376. """
  6377. if item.archive_id is None:
  6378. return ""
  6379. from backend.app.models.archive import PrintArchive
  6380. archive = await db.get(PrintArchive, item.archive_id)
  6381. if archive is None or not archive.filename:
  6382. return ""
  6383. return _subtask_name_from_filename(archive.filename)
  6384. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  6385. """Whether this completion event is plausibly about *item*'s print.
  6386. The caller finds its queue row by printer and ``status='printing'`` alone,
  6387. which is all a completion event gives it -- there is no run identifier in
  6388. the MQTT payload to match on. That makes the lookup indiscriminate: any
  6389. completion delivered for this printer closes whichever row happens to be
  6390. printing, however unrelated. Comparing the subtask name against the archive
  6391. the row was dispatched with costs one primary-key load and rules that out.
  6392. Deliberately permissive: it answers False only on a positive disagreement
  6393. between two names we actually have. A row with no archive, an archive with
  6394. no file name, or an event with no subtask name is unverifiable rather than
  6395. wrong, and refusing those would strand the item in ``printing`` and wedge
  6396. the printer's queue -- a worse failure than the one being prevented.
  6397. """
  6398. observed = (data.get("subtask_name") or "").strip()
  6399. if not observed or item.archive_id is None:
  6400. return True
  6401. from backend.app.models.archive import PrintArchive
  6402. archive = await db.get(PrintArchive, item.archive_id)
  6403. if archive is None or not archive.filename:
  6404. return True
  6405. expected = _subtask_name_from_filename(archive.filename)
  6406. if not expected or _subtask_names_match(expected, observed):
  6407. return True
  6408. logging.getLogger(__name__).warning(
  6409. "Ignoring print completion for queue item %s: it was dispatched as %r "
  6410. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  6411. "printing rather than closing a run this event is not about.",
  6412. item.id,
  6413. expected,
  6414. archive.id,
  6415. archive.filename,
  6416. observed,
  6417. )
  6418. return False
  6419. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  6420. """Spend the 3MF download cache on a still-empty fallback archive.
  6421. ``on_print_complete`` drops the cache as its first act, which deletes the
  6422. file. If the cover endpoint (or anything else) pulled the 3MF while the
  6423. print ran and the archive never got one, this is the last moment those bytes
  6424. exist (#2957).
  6425. """
  6426. logger = logging.getLogger(__name__)
  6427. names = [
  6428. n
  6429. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  6430. if n
  6431. ]
  6432. for name in names:
  6433. try:
  6434. cached = get_cached_3mf(printer_id, name)
  6435. if cached and await try_recover_fallback_archive(printer_id, name, cached):
  6436. return
  6437. except Exception as e:
  6438. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  6439. async def _cleanup_sd_card_after_print(
  6440. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  6441. ) -> None:
  6442. """Delete a finished print's file from the printer's SD card."""
  6443. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  6444. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  6445. # auto-start files found in root on power cycle, causing ghost prints.
  6446. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  6447. try:
  6448. if subtask_name:
  6449. archive_filename: str | None = None
  6450. async with async_session() as db:
  6451. from backend.app.models.archive import PrintArchive
  6452. from backend.app.models.printer import Printer
  6453. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6454. printer = result.scalar_one_or_none()
  6455. if archive_id:
  6456. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  6457. archive_filename = archive_row.scalar_one_or_none()
  6458. if printer:
  6459. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  6460. from backend.app.utils.filename import derive_remote_filename
  6461. # Primary candidate: the exact path the dispatcher uploaded to
  6462. # (derived from archive.filename via the same rule as upload).
  6463. # Without it, a library row that ended up with a doubled
  6464. # .gcode.3mf (#1542) leaves the real file behind because the
  6465. # subtask_name + ext fallbacks below don't match what's on the
  6466. # SD card. Fallbacks remain for archive-less prints (subtask
  6467. # never resolved to an archive) and for older naming variants.
  6468. candidate_paths: list[str] = []
  6469. if archive_filename:
  6470. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  6471. for ext in (".3mf", ".gcode"):
  6472. fallback = f"/{subtask_name}{ext}"
  6473. if fallback not in candidate_paths:
  6474. candidate_paths.append(fallback)
  6475. # Three outcomes track across all candidates so the final log
  6476. # line reflects what actually happened. The A1 in #1721 always
  6477. # ends here with ``any_not_found=True`` and the others False
  6478. # — its firmware auto-cleans the SD card before our cleanup
  6479. # runs, every candidate FTP-DELE returns 550, and the old
  6480. # code burned 3 retries × 2 s × 3 candidates per print
  6481. # logging a misleading "may linger" WARNING on a successful
  6482. # print.
  6483. any_deleted = False
  6484. any_real_failure = False
  6485. any_not_found = False
  6486. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  6487. for remote_path in candidate_paths:
  6488. if PurePosixPath(remote_path).name.lower() in files_in_use:
  6489. logger.info(
  6490. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  6491. remote_path,
  6492. printer.name,
  6493. )
  6494. continue
  6495. # Retry only the FAILED case — 550 NOT_FOUND will never
  6496. # recover by waiting, so a "file isn't here" answer
  6497. # advances immediately to the next candidate without
  6498. # consuming the retry budget.
  6499. for attempt in range(1, 4):
  6500. try:
  6501. delete_result = await delete_file_async(
  6502. printer.ip_address,
  6503. printer.access_code,
  6504. remote_path,
  6505. printer_model=printer.model,
  6506. )
  6507. except Exception as e:
  6508. delete_result = DeleteResult.FAILED
  6509. logger.warning(
  6510. "SD card cleanup attempt %d/3 raised for %s: %s",
  6511. attempt,
  6512. remote_path,
  6513. e,
  6514. )
  6515. if delete_result == DeleteResult.DELETED:
  6516. any_deleted = True
  6517. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  6518. break
  6519. if delete_result == DeleteResult.NOT_FOUND:
  6520. any_not_found = True
  6521. break # 550 will not recover; try next candidate
  6522. # FAILED: real error — retry with backoff, then give up
  6523. if attempt < 3:
  6524. await asyncio.sleep(2)
  6525. else:
  6526. any_real_failure = True
  6527. logger.warning(
  6528. "SD card cleanup failed after 3 attempts for %s "
  6529. "(network/auth/transient error — file may linger on SD card)",
  6530. remote_path,
  6531. )
  6532. if not any_deleted and not any_real_failure and any_not_found:
  6533. # Every candidate said "not here." Either the printer
  6534. # firmware swept the SD card itself (common on A1) or the
  6535. # dispatcher's upload path doesn't match our candidate
  6536. # rule. Either way: nothing to clean up, no warning.
  6537. logger.debug(
  6538. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  6539. "(printer likely self-cleaned)",
  6540. printer.name,
  6541. )
  6542. except Exception as e:
  6543. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  6544. async def on_print_complete(printer_id: int, data: dict):
  6545. """Handle print completion - update the archive status."""
  6546. import time
  6547. logger = logging.getLogger(__name__)
  6548. start_time = time.time()
  6549. def log_timing(section: str):
  6550. elapsed = time.time() - start_time
  6551. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  6552. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  6553. # A kill-switch stop sends its provider notification immediately. Keep the
  6554. # task so the later notification path can await it and avoid a duplicate;
  6555. # if that immediate attempt failed, the regular completion path retries.
  6556. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  6557. # Last chance before the bytes go: if this print's archive is still an empty
  6558. # fallback and something downloaded the 3MF while it ran, fill the archive in
  6559. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  6560. # below deletes the file (#2957).
  6561. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  6562. # A pending cool-off retry has nothing left to recover for — the cache is
  6563. # about to be dropped and the print is over.
  6564. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  6565. if retry_task and not retry_task.done():
  6566. retry_task.cancel()
  6567. # Drop the 3MF download cache for this printer (#972). The print is over,
  6568. # nothing else legitimately needs the bytes; keeping them would only risk
  6569. # handing a stale file to the next print if it reuses the same name.
  6570. clear_3mf_cache(printer_id)
  6571. try:
  6572. ws_data = {
  6573. "status": data.get("status"),
  6574. "filename": data.get("filename"),
  6575. "subtask_name": data.get("subtask_name"),
  6576. "timelapse_was_active": data.get("timelapse_was_active"),
  6577. }
  6578. await ws_manager.send_print_complete(printer_id, ws_data)
  6579. log_timing("WebSocket send_print_complete")
  6580. except Exception as e:
  6581. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  6582. # Capture user info before clearing (needed for print log entry)
  6583. _print_user_info = printer_manager.get_current_print_user(printer_id)
  6584. # Clear current print user tracking (Issue #206)
  6585. printer_manager.clear_current_print_user(printer_id)
  6586. # If the user explicitly stopped this print from the queue UI the printer will
  6587. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  6588. # correct "print stopped" notification/email is sent instead of a failure alert.
  6589. _raw_status = data.get("status", "completed")
  6590. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  6591. logger.info(
  6592. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  6593. _raw_status,
  6594. printer_id,
  6595. )
  6596. data = {**data, "status": "cancelled"}
  6597. _user_stopped_printers.discard(printer_id)
  6598. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  6599. # may have left material on the bed: a user can cancel ten hours into a
  6600. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  6601. # touchscreen-stop reports `aborted` rather than `cancelled` because
  6602. # `_user_stopped_printers` is only populated when the user stops via the
  6603. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  6604. # which auto-dispatched the next queued print onto a fouled bed two seconds
  6605. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  6606. # Auto Off power cycles and Bambuddy restarts.
  6607. _final_status = data.get("status", "completed")
  6608. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  6609. printer_manager.set_awaiting_plate_clear(printer_id, True)
  6610. # MQTT relay - publish print complete
  6611. try:
  6612. printer_info = printer_manager.get_printer(printer_id)
  6613. if printer_info:
  6614. await mqtt_relay.on_print_complete(
  6615. printer_id,
  6616. printer_info.name,
  6617. printer_info.serial_number,
  6618. data.get("filename", ""),
  6619. data.get("subtask_name", ""),
  6620. data.get("status", "completed"),
  6621. )
  6622. except Exception:
  6623. pass # Don't fail print complete callback if MQTT fails
  6624. filename = data.get("filename", "")
  6625. subtask_name = data.get("subtask_name", "")
  6626. if not filename and not subtask_name:
  6627. logger.warning("Print complete without filename or subtask_name")
  6628. return
  6629. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  6630. # Build list of possible keys to try (matching how they were registered in on_print_start)
  6631. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  6632. # Find the archive for this print
  6633. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  6634. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  6635. archive_id = None
  6636. for key in possible_keys:
  6637. archive_id = _active_prints.pop(key, None)
  6638. if archive_id:
  6639. logger.info("Found archive %s with key %s", archive_id, key)
  6640. # Also clean up any other keys pointing to this archive
  6641. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  6642. for k in keys_to_remove:
  6643. _active_prints.pop(k, None)
  6644. break
  6645. # The archive bound when the print started, before the name search below.
  6646. # Only this one may give the finish-photo plate restore a height (#3240):
  6647. # the search matches names by substring.
  6648. bound_archive_id = archive_id
  6649. if not archive_id:
  6650. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  6651. async with async_session() as db:
  6652. from backend.app.models.archive import PrintArchive
  6653. # Try matching by subtask_name (stored as print_name) first
  6654. if subtask_name:
  6655. result = await db.execute(
  6656. select(PrintArchive)
  6657. .where(PrintArchive.printer_id == printer_id)
  6658. .where(PrintArchive.status == "printing")
  6659. .where(
  6660. or_(
  6661. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  6662. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  6663. )
  6664. )
  6665. .order_by(PrintArchive.created_at.desc())
  6666. .limit(1)
  6667. )
  6668. archive = result.scalar_one_or_none()
  6669. if archive:
  6670. archive_id = archive.id
  6671. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  6672. # Also try by filename
  6673. if not archive_id and filename:
  6674. result = await db.execute(
  6675. select(PrintArchive)
  6676. .where(PrintArchive.printer_id == printer_id)
  6677. .where(PrintArchive.filename == filename)
  6678. .where(PrintArchive.status == "printing")
  6679. .order_by(PrintArchive.created_at.desc())
  6680. .limit(1)
  6681. )
  6682. archive = result.scalar_one_or_none()
  6683. if archive:
  6684. archive_id = archive.id
  6685. await _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger)
  6686. log_timing("SD card cleanup")
  6687. # Update queue item status early — must run before the archive_id early-return
  6688. # so queue items don't get stuck in "printing" when archive lookup fails.
  6689. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  6690. queue_item_id = None
  6691. billing_run_id: str | None = None
  6692. billing_user_id: int | None = None
  6693. billing_cost_center_id: int | None = None
  6694. billing_plate_id: int | None = None
  6695. queue_status = None
  6696. queue_auto_off = False
  6697. try:
  6698. from backend.app.core.database import run_with_retry
  6699. from backend.app.models.print_queue import PrintQueueItem
  6700. async def _update_queue_status(db):
  6701. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  6702. nonlocal queue_item_id, queue_status, queue_auto_off
  6703. result = await db.execute(
  6704. select(PrintQueueItem)
  6705. .where(PrintQueueItem.printer_id == printer_id)
  6706. .where(PrintQueueItem.status == "printing")
  6707. )
  6708. printing_items = list(result.scalars().all())
  6709. if len(printing_items) > 1:
  6710. logger.warning(
  6711. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  6712. printer_id,
  6713. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  6714. )
  6715. item = printing_items[0] if printing_items else None
  6716. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  6717. return
  6718. if item:
  6719. queue_status = data.get("status", "completed")
  6720. # MQTT sends "aborted" for cancelled prints; normalise to
  6721. # "cancelled" so it matches the queue schema Literal.
  6722. if queue_status == "aborted":
  6723. queue_status = "cancelled"
  6724. item.status = queue_status
  6725. item.completed_at = datetime.now(timezone.utc)
  6726. if queue_status == "failed" and not item.error_message:
  6727. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  6728. # Bump usage counters on the source library file so admins can
  6729. # sort by "last printed" and (eventually) auto-purge stale
  6730. # files — #1008.
  6731. await _bump_library_file_usage_if_completed(db, item, queue_status)
  6732. await db.commit()
  6733. queue_item_id = item.id
  6734. billing_run_id = item.billing_run_id
  6735. billing_user_id = item.created_by_id
  6736. billing_cost_center_id = item.cost_center_id
  6737. billing_plate_id = item.plate_id
  6738. queue_auto_off = item.auto_off_after
  6739. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  6740. await run_with_retry(_update_queue_status, label="queue status update")
  6741. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  6742. # their own sessions and have their own error handling — no retry needed.
  6743. if queue_item_id is not None:
  6744. # Batch orders (#342): this run may have been the last one an order
  6745. # owed. Re-evaluate here rather than lazily on read, so a finished
  6746. # order reports itself complete without someone opening the page.
  6747. try:
  6748. from backend.app.services.print_batch import refresh_batch_status_for_item
  6749. async with async_session() as db:
  6750. await refresh_batch_status_for_item(db, queue_item_id)
  6751. await db.commit()
  6752. except Exception as e:
  6753. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  6754. # MQTT relay - publish queue job completed
  6755. try:
  6756. printer_info = printer_manager.get_printer(printer_id)
  6757. await mqtt_relay.on_queue_job_completed(
  6758. job_id=queue_item_id,
  6759. filename=filename or subtask_name,
  6760. printer_id=printer_id,
  6761. printer_name=printer_info.name if printer_info else "Unknown",
  6762. status=queue_status,
  6763. )
  6764. except Exception:
  6765. pass # Don't fail if MQTT fails
  6766. # Check if queue is now empty and send notification
  6767. try:
  6768. from sqlalchemy import func as sa_func
  6769. async with async_session() as db:
  6770. count_result = await db.execute(
  6771. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  6772. )
  6773. pending_count = count_result.scalar() or 0
  6774. if pending_count == 0:
  6775. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  6776. completed_result = await db.execute(
  6777. select(sa_func.count(PrintQueueItem.id)).where(
  6778. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  6779. PrintQueueItem.completed_at >= today_start,
  6780. )
  6781. )
  6782. completed_count = completed_result.scalar() or 1
  6783. await notification_service.on_queue_completed(
  6784. completed_count=completed_count,
  6785. db=db,
  6786. )
  6787. except Exception:
  6788. pass # Don't fail if notification fails
  6789. # Handle auto_off_after - power off printer if the queue item opted
  6790. # in. Delegates to the smart-plug manager so the off honours each
  6791. # plug's configured strategy (time delay or temperature threshold),
  6792. # is cancelled if the printer starts printing again, and never cuts
  6793. # power on a loaded print (#1890). Previously an inline block here
  6794. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  6795. # timeout regardless of print state — cutting a touchscreen reprint.
  6796. if queue_auto_off:
  6797. try:
  6798. async with async_session() as db:
  6799. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  6800. except Exception as e:
  6801. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  6802. except Exception as e:
  6803. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  6804. log_timing("Queue item update")
  6805. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  6806. # Must run before archive_id early-return so it fires for all prints (including
  6807. # prints started from BambuStudio/touchscreen that have no archive).
  6808. if data.get("status") == "completed":
  6809. try:
  6810. from backend.app.api.routes.settings import get_setting
  6811. async with async_session() as db:
  6812. threshold_str = await get_setting(db, "bed_cooled_threshold")
  6813. threshold = float(threshold_str) if threshold_str else 35.0
  6814. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  6815. async with async_session() as db:
  6816. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  6817. if providers:
  6818. _bed_cool_waiters[printer_id] = {
  6819. "threshold": threshold,
  6820. "filename": filename or subtask_name or "",
  6821. "registered_at": time.time(),
  6822. }
  6823. logger.info(
  6824. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  6825. printer_id,
  6826. threshold,
  6827. )
  6828. else:
  6829. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  6830. except Exception as e:
  6831. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  6832. # Capture the slicer estimate before usage tracking runs. The tracker may
  6833. # update archive.cost with this run's measured cost; billing partial runs
  6834. # against that already-partial value would discount the charge twice.
  6835. billing_planned_grams: float | None = None
  6836. billing_base_cost: float | None = None
  6837. if archive_id:
  6838. try:
  6839. async with async_session() as db:
  6840. from backend.app.models.archive import PrintArchive
  6841. billing_archive = await db.get(PrintArchive, archive_id)
  6842. if billing_archive:
  6843. billing_path = (
  6844. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  6845. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  6846. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  6847. billing_archive,
  6848. billing_path,
  6849. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  6850. )
  6851. except Exception as e:
  6852. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  6853. # --- Track filament consumption (must run before archive_id early-return so usage
  6854. # is recorded even when auto-archive is disabled) ---
  6855. usage_results: list[dict] = []
  6856. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  6857. stored_ams_mapping = data.get("ams_mapping")
  6858. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  6859. if not stored_ams_mapping and archive_id:
  6860. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  6861. # Always drain the plate_id register on completion — the session already
  6862. # consumed it at print-start injection; leaving it would leak into the next
  6863. # print on the same archive_id (rare but possible with reprints) (#1697).
  6864. # Capture the popped value so the completion notification can scope the
  6865. # archive-level (summed-across-plates per #1593) filament + time totals
  6866. # down to the single plate that was actually printed (#1785).
  6867. notify_plate_id: int | None = None
  6868. if archive_id:
  6869. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  6870. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  6871. try:
  6872. async with async_session() as db:
  6873. from backend.app.api.routes.settings import get_setting
  6874. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6875. if not _spoolman_on or _spoolman_on.lower() != "true":
  6876. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  6877. async with async_session() as db:
  6878. usage_results = await usage_on_print_complete(
  6879. printer_id,
  6880. data,
  6881. printer_manager,
  6882. db,
  6883. archive_id=archive_id,
  6884. ams_mapping=stored_ams_mapping,
  6885. )
  6886. if usage_results:
  6887. await ws_manager.broadcast(
  6888. {
  6889. "type": "spool_usage_logged",
  6890. "printer_id": printer_id,
  6891. "usage": usage_results,
  6892. }
  6893. )
  6894. log_timing("Usage tracker")
  6895. except Exception as e:
  6896. logger.warning("Usage tracker on_print_complete failed: %s", e)
  6897. # Drop the print-start context unconditionally — the Spoolman branch above
  6898. # skips the internal tracker entirely, so nothing else would clear what
  6899. # print start captured, and a row surviving its print would be restored
  6900. # onto the next one after a restart.
  6901. try:
  6902. from backend.app.services.usage_tracker import discard_session
  6903. async with async_session() as db:
  6904. await discard_session(db, printer_id)
  6905. except Exception as e:
  6906. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  6907. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  6908. if archive_id:
  6909. if data.get("status") == "completed":
  6910. try:
  6911. await _report_spoolman_usage(printer_id, archive_id)
  6912. log_timing("Spoolman usage report")
  6913. except Exception as e:
  6914. logger.warning("Spoolman usage reporting failed: %s", e)
  6915. else:
  6916. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  6917. try:
  6918. async with async_session() as db:
  6919. await _cleanup_spoolman_tracking(
  6920. printer_id,
  6921. archive_id,
  6922. db,
  6923. last_layer_num=data.get("last_layer_num"),
  6924. last_progress=data.get("last_progress"),
  6925. )
  6926. except Exception as e:
  6927. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  6928. log_timing("Filament usage tracking")
  6929. if not archive_id:
  6930. # The printer's own calibration run has no archive by design, so this
  6931. # arrives here every time one finishes. Returning before the no-archive
  6932. # notification is not just noise control: that path attributes an
  6933. # unmatched completion to any queue item this printer finished in the
  6934. # last five minutes, which for a calibration that runs alongside a real
  6935. # print means emailing its owner that their print is done, twice and
  6936. # early. Everything above this point has already run — the plate-clear
  6937. # gate, the queue reconciliation, the SD-card cleanup — so only the
  6938. # notification is skipped.
  6939. if is_internal_printer_job(filename, subtask_name):
  6940. logger.info(
  6941. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  6942. filename,
  6943. subtask_name,
  6944. )
  6945. return
  6946. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  6947. # Still send print-complete/failed/stopped notifications even without an archive.
  6948. # Try to enrich with queue/library-file data so user-specific emails work too.
  6949. async def _notify_no_archive():
  6950. try:
  6951. async with async_session() as db:
  6952. from backend.app.models.library import LibraryFile
  6953. from backend.app.models.print_queue import PrintQueueItem
  6954. from backend.app.models.printer import Printer
  6955. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6956. printer_obj = result.scalar_one_or_none()
  6957. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  6958. # Try to find the most-recent queue item for this printer so we can
  6959. # recover created_by_id and estimated print time.
  6960. # NOTE: By the time this task runs the queue item status has already
  6961. # been updated to a terminal state (completed/failed/cancelled), so
  6962. # we look for recently-completed items (within the last 5 minutes).
  6963. no_archive_data: dict | None = None
  6964. try:
  6965. cutoff = datetime.now(timezone.utc) - timedelta(minutes=5)
  6966. q_result = await db.execute(
  6967. select(PrintQueueItem)
  6968. .where(PrintQueueItem.printer_id == printer_id)
  6969. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled"]))
  6970. .where(PrintQueueItem.completed_at >= cutoff)
  6971. .order_by(PrintQueueItem.completed_at.desc())
  6972. .limit(1)
  6973. )
  6974. queue_item = q_result.scalar_one_or_none()
  6975. if queue_item:
  6976. no_archive_data = {"created_by_id": queue_item.created_by_id}
  6977. # Pull estimated time from library file when available
  6978. if queue_item.library_file_id:
  6979. lib_result = await db.execute(
  6980. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  6981. )
  6982. lib_file = lib_result.scalar_one_or_none()
  6983. if lib_file and lib_file.print_time_seconds:
  6984. no_archive_data["print_time_seconds"] = lib_file.print_time_seconds
  6985. except Exception as lookup_err:
  6986. logger.debug(
  6987. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  6988. )
  6989. # Enrich with usage tracker results (captured in enclosing scope)
  6990. if usage_results:
  6991. if no_archive_data is None:
  6992. no_archive_data = {}
  6993. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  6994. if total_from_usage > 0:
  6995. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  6996. no_archive_data["usage_results"] = usage_results
  6997. # Try MQTT remaining_time for print duration when no queue/library data
  6998. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  6999. mqtt_remaining = data.get("remaining_time")
  7000. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  7001. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  7002. ps = data.get("status", "completed")
  7003. logger.info(
  7004. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  7005. )
  7006. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7007. await notification_service.on_print_complete(
  7008. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  7009. )
  7010. else:
  7011. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7012. # Send user-specific email if we have a created_by_id
  7013. if no_archive_data and no_archive_data.get("created_by_id"):
  7014. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7015. await _dispatch_user_print_email(
  7016. ps,
  7017. no_archive_data["created_by_id"],
  7018. p_name,
  7019. raw_filename,
  7020. db,
  7021. )
  7022. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  7023. except Exception as e:
  7024. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  7025. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  7026. return
  7027. log_timing("Archive lookup")
  7028. # Update archive status
  7029. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  7030. try:
  7031. async with async_session() as db:
  7032. service = ArchiveService(db)
  7033. status = data.get("status", "completed")
  7034. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  7035. if hms_errors:
  7036. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  7037. failure_reason = derive_failure_reason(status, hms_errors)
  7038. if data.get("_reconciled"):
  7039. # A reconciled completion closes out a stale archive at
  7040. # reconnect — it is not a user action, so don't mislabel it
  7041. # "userCancelled". It shares the stale-cleanup path's key
  7042. # (issue #2974) and records that the real end time is unknown,
  7043. # which is also why its logged duration is 0 (#2592).
  7044. failure_reason = "noStatusUpdate"
  7045. if failure_reason:
  7046. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  7047. elif status == "failed" and hms_errors:
  7048. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  7049. await service.update_archive_status(
  7050. archive_id,
  7051. status=status,
  7052. completed_at=(
  7053. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  7054. ),
  7055. failure_reason=failure_reason,
  7056. )
  7057. logger.info(
  7058. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  7059. )
  7060. await ws_manager.send_archive_updated(
  7061. {
  7062. "id": archive_id,
  7063. "status": status,
  7064. }
  7065. )
  7066. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  7067. # MQTT relay - publish archive updated
  7068. try:
  7069. await mqtt_relay.on_archive_updated(
  7070. archive_id=archive_id,
  7071. print_name=filename or subtask_name,
  7072. status=status,
  7073. )
  7074. except Exception:
  7075. pass # Don't fail if MQTT fails
  7076. except Exception as e:
  7077. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  7078. # Continue with other operations even if archive update fails
  7079. log_timing("Archive status update")
  7080. # Apply finance wallet charge or release reservations once. For all partial
  7081. # terminal states (failed, aborted at the printer display, or cancelled via
  7082. # Bambuddy) use this run's measured spool delta, falling back to the last
  7083. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  7084. # estimate and therefore cannot represent an interrupted run.
  7085. try:
  7086. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  7087. async with async_session() as db:
  7088. from backend.app.models.archive import PrintArchive
  7089. from backend.app.services.finance_billing import apply_print_charge_for_archive
  7090. archive = await db.get(PrintArchive, archive_id)
  7091. if archive and billing_run_id is None:
  7092. billing_run_id = getattr(archive, "billing_run_id", None)
  7093. if archive and archive.created_by_id is None and _print_user_info:
  7094. archive.created_by_id = _print_user_info.get("user_id")
  7095. await db.flush()
  7096. run_status = data.get("status", "completed")
  7097. last_progress = data.get("last_progress")
  7098. if last_progress is None:
  7099. last_progress = data.get("progress")
  7100. actual_run_grams = _compute_run_filament_grams(
  7101. run_status,
  7102. billing_planned_grams,
  7103. last_progress,
  7104. usage_results,
  7105. )
  7106. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  7107. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  7108. charged = await apply_print_charge_for_archive(
  7109. db,
  7110. archive_id,
  7111. charged_user_id=billing_user_id,
  7112. cost_center_id=(
  7113. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  7114. ),
  7115. print_queue_id=queue_item_id,
  7116. print_run_id=billing_run_id,
  7117. base_cost_override=billing_base_cost,
  7118. filament_usage=filament_usage,
  7119. )
  7120. await db.commit()
  7121. if charged:
  7122. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  7123. except Exception as e:
  7124. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  7125. printer_info = printer_manager.get_printer(printer_id)
  7126. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  7127. billing_filename = filename or subtask_name or "Unknown"
  7128. billing_error = str(e)
  7129. try:
  7130. await ws_manager.broadcast(
  7131. {
  7132. "type": "billing_charge_failed",
  7133. "printer_id": printer_id,
  7134. "printer_name": billing_printer_name,
  7135. "filename": billing_filename,
  7136. "archive_id": archive_id,
  7137. }
  7138. )
  7139. except Exception as notification_error:
  7140. logger.error(
  7141. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  7142. archive_id,
  7143. notification_error,
  7144. )
  7145. async def _notify_billing_charge_failed() -> None:
  7146. try:
  7147. async with async_session() as notification_db:
  7148. await notification_service.on_billing_charge_failed(
  7149. printer_id,
  7150. billing_printer_name,
  7151. billing_filename,
  7152. archive_id,
  7153. billing_error,
  7154. notification_db,
  7155. )
  7156. except Exception as provider_error:
  7157. logger.error(
  7158. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  7159. archive_id,
  7160. provider_error,
  7161. exc_info=True,
  7162. )
  7163. spawn_background_task(
  7164. _notify_billing_charge_failed(),
  7165. name=f"billing-charge-failed-{archive_id}",
  7166. )
  7167. log_timing("Finance charge update")
  7168. # Write independent print log entry (separate table, never touches archives)
  7169. try:
  7170. async with async_session() as db:
  7171. from backend.app.models.archive import PrintArchive
  7172. from backend.app.services.print_log import record_archive_wear, write_log_entry
  7173. archive = await db.get(PrintArchive, archive_id)
  7174. if archive:
  7175. # Back-fill created_by_id on reprint (#730): reprint reuses the
  7176. # source archive row rather than creating a new one, so an
  7177. # archive that was auto-created from a printer-initiated
  7178. # print (created_by_id=NULL) would otherwise stay unattributed
  7179. # forever. When we have a print-session user AND the archive
  7180. # has no attribution yet, credit the current user. Never
  7181. # overwrite an existing attribution — the original uploader
  7182. # keeps ownership.
  7183. _print_user_id = _print_user_info.get("user_id") if _print_user_info else None
  7184. if archive.created_by_id is None and _print_user_id is not None:
  7185. archive.created_by_id = _print_user_id
  7186. p_info = printer_manager.get_printer(printer_id)
  7187. # Per-run actuals — written to PrintLogEntry so stats reflect
  7188. # what THIS print actually used, not the source archive's
  7189. # first-run values (#1378). Helper handles the partial-print
  7190. # math (failed / cancelled / stopped get scaled to progress
  7191. # or to tracked spool deltas).
  7192. _run_status = data.get("status", "completed")
  7193. # #2614: scope the per-run estimate to the printed plate. For a
  7194. # multi-plate 3MF dispatched one plate at a time, the archive's
  7195. # filament/cost are the whole-file totals; the PrintLogEntry must
  7196. # reflect only this plate. No effect on single-plate archives (the
  7197. # plate estimate equals the whole-file value) or on the tracker
  7198. # path (measured spool deltas win in _compute_run_filament_grams).
  7199. _est_full_path = (
  7200. app_settings.base_dir / archive.file_path if archive.file_path else None
  7201. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7202. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path)
  7203. _run_grams = _compute_run_filament_grams(
  7204. _run_status,
  7205. _est_grams,
  7206. data.get("last_progress", data.get("progress")),
  7207. usage_results,
  7208. )
  7209. # Per-run cost — prefer usage_results sum. For partial prints
  7210. # we deliberately skip the topup-to-estimate logic in
  7211. # usage_tracker (which assumes the print completed); the raw
  7212. # tracked-spool sum is closer to what THIS run actually cost.
  7213. _run_cost: float | None = None
  7214. if usage_results:
  7215. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  7216. if _run_cost is None and _run_status == "completed":
  7217. _run_cost = _est_cost
  7218. from backend.app.models.printer import Printer as _Printer
  7219. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  7220. run_entry = await write_log_entry(
  7221. db,
  7222. archive_id=archive.id,
  7223. # Captured by _update_queue_status above; None for
  7224. # printer-initiated prints with no queue row. Batch
  7225. # cost/energy roll-up joins on it (#342).
  7226. queue_item_id=queue_item_id,
  7227. status=_run_status,
  7228. print_name=archive.print_name,
  7229. printer_name=p_info.name if p_info else None,
  7230. printer_id=printer_id,
  7231. started_at=archive.started_at,
  7232. completed_at=archive.completed_at,
  7233. filament_type=archive.filament_type,
  7234. filament_color=archive.filament_color,
  7235. filament_used_grams=_run_grams,
  7236. cost=_run_cost,
  7237. wear_cost_per_hour=_wear_rate,
  7238. failure_reason=archive.failure_reason,
  7239. thumbnail_path=archive.thumbnail_path,
  7240. created_by_id=archive.created_by_id,
  7241. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  7242. # Reconciled completions have an unknown real end time —
  7243. # log 0 duration instead of the whole disconnect gap (#2592).
  7244. reconciled=bool(data.get("_reconciled")),
  7245. )
  7246. await record_archive_wear(db, archive, run_entry)
  7247. await db.commit()
  7248. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  7249. except Exception as e:
  7250. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  7251. log_timing("Print log entry")
  7252. # Run slow operations as background tasks to avoid blocking the event loop
  7253. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  7254. async def _background_energy_calculation():
  7255. """Calculate and save energy usage in background.
  7256. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  7257. backend restart no longer loses per-print energy data).
  7258. """
  7259. try:
  7260. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  7261. async with async_session() as db:
  7262. from backend.app.models.archive import PrintArchive
  7263. archive = await db.get(PrintArchive, archive_id)
  7264. if archive is None:
  7265. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  7266. return
  7267. starting_kwh = archive.energy_start_kwh
  7268. if starting_kwh is None:
  7269. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  7270. return
  7271. candidates = await energy_plug_candidates(db, printer_id)
  7272. if not candidates:
  7273. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  7274. return
  7275. # Same ordering as the start reading, so the delta below is
  7276. # against the counter that produced `starting_kwh` (#2859).
  7277. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  7278. if selected is None:
  7279. logger.warning(
  7280. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  7281. printer_id,
  7282. ", ".join(plug.name for plug in candidates),
  7283. )
  7284. return
  7285. plug, energy = selected
  7286. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  7287. energy_used = round(energy["total"] - starting_kwh, 4)
  7288. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  7289. if energy_used < 0:
  7290. logger.warning(
  7291. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  7292. archive_id,
  7293. starting_kwh,
  7294. energy["total"],
  7295. )
  7296. return
  7297. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  7298. # Each hour of the print at the price of that hour (#1251). If
  7299. # that fails, the last price known, as before, rather than no
  7300. # energy at all. Read first: the session may be unusable after.
  7301. last_price = await stored_price(db)
  7302. try:
  7303. energy_cost_value = round(
  7304. await print_energy_cost(
  7305. db,
  7306. plug_id=archive.energy_start_plug_id,
  7307. start_at=archive.energy_start_at,
  7308. start_kwh=starting_kwh,
  7309. start_price=archive.energy_start_price,
  7310. end_kwh=energy["total"],
  7311. end_plug_id=plug.id,
  7312. price_now=await current_price(db),
  7313. ),
  7314. 3,
  7315. )
  7316. except Exception as e:
  7317. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  7318. energy_cost_value = round(energy_used * last_price, 3)
  7319. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  7320. # reprint doesn't visually clobber the source archive's energy data
  7321. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  7322. from sqlalchemy import func
  7323. from backend.app.models.print_log import PrintLogEntry
  7324. existing_runs = await db.scalar(
  7325. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  7326. )
  7327. if (existing_runs or 0) <= 1:
  7328. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  7329. # we just wrote for THIS print. Either way it's the first run.
  7330. archive.energy_kwh = energy_used
  7331. archive.energy_cost = energy_cost_value
  7332. # Backfill the latest PrintLogEntry for this archive with energy
  7333. # (write_log_entry above ran before this background task completed,
  7334. # so energy fields are still NULL on that row).
  7335. latest_run = await db.execute(
  7336. select(PrintLogEntry)
  7337. .where(PrintLogEntry.archive_id == archive_id)
  7338. .order_by(PrintLogEntry.id.desc())
  7339. .limit(1)
  7340. )
  7341. run_row = latest_run.scalar_one_or_none()
  7342. if run_row is not None:
  7343. run_row.energy_kwh = energy_used
  7344. run_row.energy_cost = energy_cost_value
  7345. await db.commit()
  7346. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  7347. except Exception as e:
  7348. logger.warning("[ENERGY-BG] Failed: %s", e)
  7349. async def _background_finish_photo() -> str | None:
  7350. """Capture finish photo in background. Returns photo filename if captured."""
  7351. # #2547: set once this function has raised the plate itself (the
  7352. # timelapse path, where the moment producer returned without doing it).
  7353. # Declared out here so the `finally` can lower it again no matter where
  7354. # the capture below fails.
  7355. plate_restored_z: float | None = None
  7356. try:
  7357. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  7358. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  7359. # Read phase: settings + printer + archive in a short session, released
  7360. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  7361. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  7362. # tens of seconds; holding this session across it pinned one pooled
  7363. # connection idle-in-transaction per finishing print (issue #2572).
  7364. async with async_session() as db:
  7365. from backend.app.api.routes.settings import get_setting
  7366. from backend.app.models.archive import PrintArchive
  7367. from backend.app.models.printer import Printer
  7368. capture_enabled = await get_setting(db, "capture_finish_photo")
  7369. if capture_enabled is not None and capture_enabled.lower() != "true":
  7370. return None
  7371. if not archive_id:
  7372. return None
  7373. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  7374. archive = (
  7375. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7376. ).scalar_one_or_none()
  7377. if not printer or not archive:
  7378. return None
  7379. import uuid
  7380. from datetime import datetime
  7381. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  7382. if not archive.file_path:
  7383. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  7384. archive_dir = resolve_archive_dir(archive)
  7385. photo_filename = None
  7386. # Prefer the timelapse last-frame source when a timelapse was
  7387. # recording — it captures the moment after the toolhead parks
  7388. # but before the bed drops, which the live-camera grab below
  7389. # would miss (#1397). Skipped for external cameras (those have
  7390. # their own framing and don't see a Bambu timelapse). Only
  7391. # runs when the USER explicitly enabled timelapse for this
  7392. # print — #1721 removed Bambuddy's force-on at dispatch
  7393. # because it caused per-layer nozzle parking on Smooth-mode
  7394. # slicer profiles.
  7395. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  7396. printer.external_camera_enabled and printer.external_camera_url
  7397. )
  7398. timelapse_still_pending = False
  7399. if prefer_timelapse_source:
  7400. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  7401. archive_id=archive_id,
  7402. archive_dir=archive_dir,
  7403. rotation=getattr(printer, "camera_rotation", 0),
  7404. )
  7405. # #1721: replacement framing path — on_finish_photo_moment
  7406. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  7407. # parked, bed not yet dropped) and cached the JPEG bytes in
  7408. # _stage22_finish_frames. Consume them now so the saved photo
  7409. # has the better framing instead of the post-bed-drop angle
  7410. # the live-camera fallback below would give.
  7411. if not photo_filename:
  7412. # #1790: on the FINISH-state fallback path the producer
  7413. # task is dispatched back-to-back with this consumer, so
  7414. # a bare pop would race past with an empty result and
  7415. # the RTSP fallback below would collide with the
  7416. # producer's still-in-flight grab (single-client RTSP
  7417. # on Bambu printers). Wait for the producer to finish
  7418. # or give up before touching the cache.
  7419. #
  7420. # #2547: 20s was enough when the producer only ever grabbed a
  7421. # frame. It now also raises the plate first, which costs the
  7422. # settle window before the grab even starts — so the budget has
  7423. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  7424. # under the notification's own photo wait below.
  7425. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  7426. if in_flight is not None:
  7427. try:
  7428. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  7429. except asyncio.TimeoutError:
  7430. logger.warning(
  7431. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  7432. printer_id,
  7433. )
  7434. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  7435. if cached_frame:
  7436. # Already rotated by the producer (#2708) — rotating again
  7437. # here would undo the fix on the banked-frame path, whose
  7438. # bytes reach the cache having been rotated once already.
  7439. photos_dir = archive_dir / "photos"
  7440. photos_dir.mkdir(parents=True, exist_ok=True)
  7441. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7442. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7443. photo_path = photos_dir / photo_filename
  7444. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  7445. logger.info(
  7446. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  7447. photo_filename,
  7448. len(cached_frame),
  7449. )
  7450. # #2547: the timelapse path reaches the live grab below whenever the
  7451. # video hasn't landed in time — the documented usual outcome on
  7452. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  7453. # returned early for those prints without raising the plate, so
  7454. # without this the photo that actually ships in the notification is
  7455. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  7456. # asked us to fix. The archive still gets the better video frame
  7457. # later; this is about the image the user is sent.
  7458. #
  7459. # Gated on `timelapse_was_active` precisely because that is the
  7460. # condition under which the producer skipped. On every other path it
  7461. # has already raised and lowered the plate, and repeating that here
  7462. # would be a second pointless round trip.
  7463. if (
  7464. not photo_filename
  7465. and data.get("timelapse_was_active")
  7466. and not print_dispatch_context.end_gcode_injected(printer_id)
  7467. ):
  7468. try:
  7469. async with async_session() as db:
  7470. from backend.app.api.routes.settings import get_setting
  7471. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7472. if restore_setting is None or restore_setting.lower() == "true":
  7473. max_z = await _max_z_for_current_print(
  7474. printer_id, data, logger, bound_archive_id, notify_plate_id
  7475. )
  7476. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  7477. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  7478. plate_restored_z = max_z
  7479. except Exception as e:
  7480. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  7481. # Fallback chain: external camera → buffered live frame →
  7482. # fresh RTSP capture. Only runs if the timelapse path above
  7483. # didn't already produce a photo.
  7484. # Chamber light for the live capture below (#1655).
  7485. async with camera_light(printer if not photo_filename else None):
  7486. if not photo_filename:
  7487. if printer.external_camera_enabled and printer.external_camera_url:
  7488. logger.info("[PHOTO-BG] Using external camera")
  7489. from backend.app.api.routes.camera import live_frame_for_capture
  7490. from backend.app.services.external_camera import capture_frame
  7491. # #2707: the second half of the finish-photo failure — the
  7492. # pre-capture and this fallback both collided with the live
  7493. # view. None here continues down the fallback chain.
  7494. defer, buffered = live_frame_for_capture(printer_id)
  7495. if defer:
  7496. frame_data = buffered
  7497. else:
  7498. frame_data = await capture_frame(
  7499. printer.external_camera_url,
  7500. printer.external_camera_type or "mjpeg",
  7501. snapshot_url=printer.external_camera_snapshot_url,
  7502. )
  7503. if frame_data:
  7504. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  7505. photos_dir = archive_dir / "photos"
  7506. photos_dir.mkdir(parents=True, exist_ok=True)
  7507. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7508. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7509. photo_path = photos_dir / photo_filename
  7510. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  7511. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  7512. else:
  7513. # Check if camera stream is active - use buffered frame to avoid freeze
  7514. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  7515. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  7516. active_chamber_for_printer = [
  7517. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  7518. ]
  7519. buffered_frame = get_buffered_frame(printer_id)
  7520. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  7521. # Use frame from active stream
  7522. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  7523. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  7524. photos_dir = archive_dir / "photos"
  7525. photos_dir.mkdir(parents=True, exist_ok=True)
  7526. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7527. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7528. photo_path = photos_dir / photo_filename
  7529. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  7530. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  7531. else:
  7532. # No active stream - capture new frame
  7533. from backend.app.services.camera import capture_finish_photo
  7534. photo_filename = await capture_finish_photo(
  7535. printer_id=printer_id,
  7536. ip_address=printer.ip_address,
  7537. access_code=printer.access_code,
  7538. model=printer.model,
  7539. archive_dir=archive_dir,
  7540. rotation=getattr(printer, "camera_rotation", 0),
  7541. )
  7542. # Write phase: attach the photo in a fresh short-lived session.
  7543. if photo_filename:
  7544. async with async_session() as db:
  7545. from backend.app.models.archive import PrintArchive
  7546. arch = await db.get(PrintArchive, archive_id)
  7547. if arch is not None:
  7548. photos = arch.photos or []
  7549. photos.append(photo_filename)
  7550. arch.photos = photos
  7551. await db.commit()
  7552. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  7553. # The short wait above is bounded so a slow printer can't hold up
  7554. # the print-complete notification, which is what the caller is
  7555. # blocking on. When it ran out with the video still on its way,
  7556. # keep waiting off to the side and add the better frame to the
  7557. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  7558. # users, whose videos routinely take minutes to transfer, never get
  7559. # the pre-bed-drop framing this path exists to provide.
  7560. #
  7561. # Spawned here rather than at the point the wait gave up: both this
  7562. # function and the upgrade do a read-modify-write on `photos`, and
  7563. # the live-camera fallback above can take tens of seconds. Starting
  7564. # the upgrade before that write means the two can interleave and one
  7565. # silently drops the other's entry, leaving a JPEG on disk that the
  7566. # gallery never lists.
  7567. if timelapse_still_pending:
  7568. spawn_background_task(
  7569. _upgrade_finish_photo_from_timelapse(
  7570. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  7571. ),
  7572. name=f"finish-photo-upgrade-{archive_id}",
  7573. )
  7574. return photo_filename
  7575. except Exception as e:
  7576. logger.warning("[PHOTO-BG] Failed: %s", e)
  7577. return None
  7578. finally:
  7579. # #2547: we raised the plate, so we owe the move back down — even if
  7580. # the capture in between threw. Otherwise the user finds the print
  7581. # pinned under the nozzle.
  7582. if plate_restored_z is not None:
  7583. try:
  7584. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  7585. except Exception as e:
  7586. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7587. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  7588. # Photo capture task - result will be used by notifications
  7589. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  7590. log_timing("Background tasks scheduled (energy, photo)")
  7591. # Also run smart plug, notifications, and maintenance as background tasks
  7592. print_status = data.get("status", "completed")
  7593. async def _background_smart_plug():
  7594. """Handle smart plug automation in background."""
  7595. try:
  7596. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  7597. async with async_session() as db:
  7598. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  7599. logger.info("[AUTO-OFF-BG] Completed")
  7600. except Exception as e:
  7601. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  7602. async def _background_notifications(finish_photo_filename: str | None = None):
  7603. """Send print complete notifications in background."""
  7604. try:
  7605. logger.info(
  7606. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  7607. )
  7608. async with async_session() as db:
  7609. from backend.app.models.archive import PrintArchive
  7610. from backend.app.models.printer import Printer
  7611. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7612. printer = result.scalar_one_or_none()
  7613. printer_name = printer.name if printer else f"Printer {printer_id}"
  7614. archive_data = None
  7615. if archive_id:
  7616. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7617. archive = archive_result.scalar_one_or_none()
  7618. if archive:
  7619. # Actual elapsed time from started_at/completed_at when both are
  7620. # populated (every terminal status sets completed_at after #1198).
  7621. # Falls back to None so the notification path can decide whether to
  7622. # render the slicer estimate as a last resort.
  7623. actual_time_seconds = None
  7624. if archive.started_at and archive.completed_at:
  7625. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  7626. if elapsed > 0:
  7627. actual_time_seconds = int(elapsed)
  7628. archive_data = {
  7629. "print_time_seconds": archive.print_time_seconds,
  7630. "actual_time_seconds": actual_time_seconds,
  7631. "actual_filament_grams": archive.filament_used_grams,
  7632. "failure_reason": archive.failure_reason,
  7633. "created_by_id": archive.created_by_id,
  7634. }
  7635. # Scale filament usage for partial prints
  7636. if print_status != "completed" and archive.filament_used_grams:
  7637. progress = data.get("progress") or 0
  7638. scale = _partial_progress_scale(progress)
  7639. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  7640. archive_data["progress"] = progress
  7641. # Pass per-slot data from archive.extra_data
  7642. if archive.extra_data and archive.extra_data.get("filament_slots"):
  7643. slots = archive.extra_data["filament_slots"]
  7644. if print_status != "completed":
  7645. scale = _partial_progress_scale(data.get("progress"))
  7646. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  7647. archive_data["filament_slots"] = slots
  7648. # Scope project-summed totals down to the plate that was
  7649. # actually printed — see _scope_notification_archive_data_to_plate
  7650. # for the why (#1785).
  7651. archive_data = _scope_notification_archive_data_to_plate(
  7652. archive_data,
  7653. archive.file_path,
  7654. notify_plate_id,
  7655. print_status,
  7656. data.get("progress"),
  7657. app_settings.base_dir,
  7658. )
  7659. # Enrich filament_grams from usage_results when archive has no 3MF data
  7660. if not archive_data.get("actual_filament_grams") and usage_results:
  7661. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7662. if total_from_usage > 0:
  7663. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7664. # Pass usage tracker results for AMS slot info in notifications
  7665. if usage_results:
  7666. archive_data["usage_results"] = usage_results
  7667. # Add finish photo URL and image bytes if available
  7668. if finish_photo_filename:
  7669. photo_url, photo_bytes = await _finish_photo_for_notification(
  7670. db, archive, archive_id, finish_photo_filename
  7671. )
  7672. if photo_url:
  7673. archive_data["finish_photo_url"] = photo_url
  7674. if photo_bytes:
  7675. archive_data["image_data"] = photo_bytes
  7676. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7677. await notification_service.on_print_complete(
  7678. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  7679. )
  7680. else:
  7681. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7682. # Post-print outcome confirmation (#1898). Runs in this
  7683. # background task so the finish photo fetched above rides
  7684. # along with the prompt.
  7685. if print_status == "completed" and archive_id:
  7686. await _dispatch_outcome_confirmation_safely(
  7687. db, printer_id, printer_name, data, archive_id, archive_data
  7688. )
  7689. # Send user-specific email notification
  7690. if archive_data:
  7691. created_by_id = archive_data.get("created_by_id")
  7692. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7693. await _dispatch_user_print_email(
  7694. print_status,
  7695. created_by_id,
  7696. printer_name,
  7697. raw_filename,
  7698. db,
  7699. image_data=archive_data.get("image_data"),
  7700. finish_photo_url=archive_data.get("finish_photo_url"),
  7701. )
  7702. logger.info("[NOTIFY-BG] Completed")
  7703. except Exception as e:
  7704. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  7705. async def _background_maintenance_check():
  7706. """Check for maintenance due in background."""
  7707. if print_status != "completed":
  7708. return
  7709. try:
  7710. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  7711. async with async_session() as db:
  7712. from backend.app.models.printer import Printer
  7713. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7714. printer = result.scalar_one_or_none()
  7715. printer_name = printer.name if printer else f"Printer {printer_id}"
  7716. await ensure_default_types(db)
  7717. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  7718. items_needing_attention = [
  7719. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  7720. for item in overview.maintenance_items
  7721. if item.enabled and (item.is_due or item.is_warning)
  7722. ]
  7723. if items_needing_attention:
  7724. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  7725. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  7726. # MQTT relay - publish maintenance alerts
  7727. for item in items_needing_attention:
  7728. try:
  7729. await mqtt_relay.on_maintenance_alert(
  7730. printer_id=printer_id,
  7731. printer_name=printer_name,
  7732. maintenance_type=item["name"],
  7733. current_value=0, # Not easily available here
  7734. threshold=0, # Not easily available here
  7735. )
  7736. except Exception:
  7737. pass # Don't fail if MQTT fails
  7738. else:
  7739. logger.info("[MAINT-BG] Completed (no items need attention)")
  7740. except Exception as e:
  7741. logger.warning("[MAINT-BG] Failed: %s", e)
  7742. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  7743. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  7744. # Notification task waits for photo capture to complete first (with timeout).
  7745. # When a timelapse was recording, photo sourcing polls the per-print
  7746. # timelapse for up to 60s (#1397) — extend the budget so the notification
  7747. # carries the correct bed-up photo instead of falling through to the
  7748. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  7749. #
  7750. # #2547: both budgets now have to cover a plate restore as well.
  7751. #
  7752. # Without timelapse, the wait is on the moment producer, which raises the
  7753. # plate before its grab — so this has to outlast that producer's own budget.
  7754. #
  7755. # With timelapse, the capture polls up to
  7756. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  7757. # falls back to a live grab, which is the case that raises the plate. At the
  7758. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  7759. # restore would have moved the plate for a photo nobody waited for.
  7760. photo_wait_timeout = (
  7761. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  7762. if data.get("timelapse_was_active")
  7763. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  7764. )
  7765. async def _photo_then_notify():
  7766. """Wait for photo capture, then send notification with photo URL."""
  7767. finish_photo = None
  7768. try:
  7769. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  7770. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  7771. except TimeoutError:
  7772. logger.warning(
  7773. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  7774. photo_wait_timeout,
  7775. )
  7776. except Exception as e:
  7777. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  7778. try:
  7779. await _background_notifications(finish_photo)
  7780. except Exception as e:
  7781. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  7782. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  7783. # Stitch external camera layer timelapse if session was active
  7784. print_status = data.get("status", "completed")
  7785. async def _background_layer_timelapse():
  7786. """Stitch layer timelapse and attach to archive."""
  7787. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  7788. try:
  7789. if print_status == "completed":
  7790. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  7791. timelapse_path = await tl_complete(printer_id)
  7792. if timelapse_path and archive_id:
  7793. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  7794. async with async_session() as db:
  7795. service = ArchiveService(db)
  7796. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  7797. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  7798. # Clean up the temp file
  7799. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  7800. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  7801. elif timelapse_path:
  7802. # Timelapse created but no archive - just clean up
  7803. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  7804. else:
  7805. # Print failed or cancelled - cancel timelapse session
  7806. cancel_session(printer_id)
  7807. logger.info(
  7808. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  7809. )
  7810. except Exception as e:
  7811. logger.warning("[LAYER-TL] Failed: %s", e)
  7812. # Try to cancel session on error
  7813. try:
  7814. cancel_session(printer_id)
  7815. except Exception:
  7816. pass # Best-effort timelapse session cancellation on error
  7817. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  7818. log_timing("All background tasks scheduled")
  7819. # Auto-scan for timelapse if recording was active during the print
  7820. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  7821. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  7822. # Schedule timelapse scan as background task with retries
  7823. # The printer needs time to encode the video after print completion
  7824. baseline = _timelapse_baselines.pop(printer_id, None)
  7825. spawn_background_task(
  7826. _scan_for_timelapse_with_retries(archive_id, baseline),
  7827. name=f"scan-timelapse-{archive_id}",
  7828. )
  7829. log_timing("Timelapse scan scheduled")
  7830. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  7831. # AMS sensor history recording
  7832. _ams_history_task: asyncio.Task | None = None
  7833. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  7834. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  7835. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  7836. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  7837. _ams_alarm_cooldown: dict[str, datetime] = {}
  7838. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  7839. # (printer_id, ams_id) already reported as sending the drop index and no
  7840. # percentage. Logged once each so a supported printer that turns out to do this
  7841. # shows up in a support bundle rather than as a user wondering where the
  7842. # humidity reading went -- see the note at the read site below (#3140).
  7843. _ams_index_only_logged: set[tuple[int, int]] = set()
  7844. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  7845. """Temperature at which the AMS alarm fires, falling back to the display band.
  7846. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  7847. when a notification was sent as well, which is why a room above it made the
  7848. alarm fire once an hour for as long as the weather lasted -- and the only way
  7849. to stop that was to raise the display band and lose the colour that says the
  7850. unit is warm (#2905).
  7851. Unset resolves to the fair threshold, so an install that never sets one is
  7852. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  7853. so that arrives here as a string and is handled by the same branch as any
  7854. other unparseable value -- there is no separate sentinel to keep in sync.
  7855. A non-positive value is refused rather than honoured: zero would alarm
  7856. permanently, and it is far more likely to be a cleared field than a
  7857. deliberate choice.
  7858. """
  7859. if raw_alarm_value is None:
  7860. return fair_threshold
  7861. try:
  7862. value = float(raw_alarm_value)
  7863. except (TypeError, ValueError):
  7864. return fair_threshold
  7865. if not math.isfinite(value) or value <= 0:
  7866. return fair_threshold
  7867. return value
  7868. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  7869. # through a cycle and the cool-down after it (#1802). Stored in the settings
  7870. # table rather than alongside _ams_alarm_cooldown above, because a restart
  7871. # partway through a cool-down would otherwise resume alarming about heat the
  7872. # user asked for — the same internal-timestamp-row pattern as
  7873. # support.py's debug_logging_enabled_at.
  7874. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  7875. # Upper bound on that suppression. The latch normally clears as soon as the unit
  7876. # reads at or below the threshold; see utils.ams_drying for why this cap only
  7877. # matters when it never does.
  7878. AMS_DRYING_GRACE_MINUTES = 120
  7879. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  7880. """Read the persisted per-AMS drying latch, dropping entries out of window.
  7881. Anything older than the grace cap would expire on its next visit anyway, so
  7882. discarding it here costs nothing and stops rows for deleted printers from
  7883. accumulating.
  7884. Stamps ahead of now get two defences, because a box whose clock jumps
  7885. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  7886. ones are discarded outright, and the rest are clamped to now. Without the
  7887. clamp the cap would measure from a moment that has not happened yet and hold
  7888. the alarm quiet for the skew on top of the cap. One unnecessary notification
  7889. after a clock jump is a far better failure than an alarm silently disabled
  7890. for hours.
  7891. """
  7892. from backend.app.models.settings import Settings
  7893. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  7894. setting = result.scalar_one_or_none()
  7895. if not setting or not setting.value:
  7896. return {}
  7897. try:
  7898. raw = json.loads(setting.value)
  7899. except (ValueError, TypeError):
  7900. return {} # Corrupted row → no latch, alarms behave as they did before
  7901. if not isinstance(raw, dict):
  7902. return {}
  7903. now = datetime.now(timezone.utc)
  7904. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  7905. latch: dict[str, datetime] = {}
  7906. for key, value in raw.items():
  7907. try:
  7908. stamp = datetime.fromisoformat(str(value))
  7909. except (ValueError, TypeError):
  7910. continue
  7911. if stamp.tzinfo is None:
  7912. stamp = stamp.replace(tzinfo=timezone.utc)
  7913. if not (now - window <= stamp <= now + window):
  7914. continue
  7915. # Nothing may sit in the future: suppression is measured as now minus
  7916. # the stamp, so a stamp ahead of now would extend it by the skew on top
  7917. # of the cap. Clamping the survivors keeps the cap an actual cap.
  7918. latch[str(key)] = min(stamp, now)
  7919. return latch
  7920. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  7921. """Persist the latch, writing only when it actually changed.
  7922. Adds the session change but does not commit — the caller's own commit
  7923. carries it, so the latch lands in the same transaction as the sensor rows
  7924. that produced it.
  7925. """
  7926. from backend.app.models.settings import Settings
  7927. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  7928. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  7929. setting = result.scalar_one_or_none()
  7930. if setting is None:
  7931. # Don't create the row on installs that never dry anything.
  7932. if payload != "{}":
  7933. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  7934. elif setting.value != payload:
  7935. setting.value = payload
  7936. def _ams_has_filament(ams_data: dict) -> bool:
  7937. """True if this AMS unit has at least one tray slot holding filament.
  7938. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  7939. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  7940. still report sensor readings, but those readings are ambient and not
  7941. actionable: no filament to dry, no humidity to push down. #1619 — gate
  7942. humidity/temperature alarms on this check so empty units don't generate
  7943. hourly noise. Sensor history still records regardless so the UI charts
  7944. stay continuous.
  7945. Fallback path inspects the `tray` array's `tray_type` fields for setups
  7946. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  7947. """
  7948. bits = ams_data.get("tray_exist_bits")
  7949. if isinstance(bits, str) and bits.strip():
  7950. try:
  7951. return int(bits, 16) > 0
  7952. except ValueError:
  7953. pass
  7954. trays = ams_data.get("tray")
  7955. if isinstance(trays, list):
  7956. return any(
  7957. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  7958. )
  7959. return False
  7960. async def record_ams_history():
  7961. """Background task to record AMS humidity and temperature data."""
  7962. logger = logging.getLogger(__name__)
  7963. # Wait a short time for MQTT connections to establish on startup
  7964. await asyncio.sleep(10)
  7965. while True:
  7966. try:
  7967. from backend.app.models.ams_history import AMSSensorHistory
  7968. from backend.app.models.printer import Printer
  7969. from backend.app.models.settings import Settings
  7970. async with async_session() as db:
  7971. # Get all active printers
  7972. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  7973. printers = result.scalars().all()
  7974. # Get alarm thresholds from settings
  7975. humidity_threshold = 60.0 # Default: fair threshold
  7976. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  7977. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  7978. setting = result.scalar_one_or_none()
  7979. if setting:
  7980. try:
  7981. humidity_threshold = float(setting.value)
  7982. except (ValueError, TypeError):
  7983. pass # Keep default threshold if stored value is invalid
  7984. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  7985. setting = result.scalar_one_or_none()
  7986. if setting:
  7987. try:
  7988. temp_fair_threshold = float(setting.value)
  7989. except (ValueError, TypeError):
  7990. pass # Keep default threshold if stored value is invalid
  7991. # The alarm gets its own threshold, seeded from the resolved fair
  7992. # value so an install that has never set one behaves exactly as
  7993. # it did before (#2905). ams_temp_fair decides when the card turns
  7994. # amber; 35 C is a reasonable place to change a colour and not a
  7995. # reasonable place to page someone. A room above it makes the
  7996. # alarm fire once an hour for as long as the weather lasts, and
  7997. # the only way to stop it was to raise the display band and lose
  7998. # the colour that says the unit is warm.
  7999. #
  8000. # An unset value is stored as the literal "None", which the except
  8001. # below swallows the same way it swallows garbage -- so the
  8002. # fallback costs nothing and needs no sentinel of its own.
  8003. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  8004. setting = result.scalar_one_or_none()
  8005. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  8006. temp_fair_threshold, setting.value if setting else None
  8007. )
  8008. # Per-filament humidity threshold overrides (#1605) — resolved
  8009. # per-AMS below from the loaded tray types. Reuses the same
  8010. # resolver as the auto-drying scheduler so behavior stays in
  8011. # lockstep across both consumers.
  8012. from backend.app.services.print_scheduler import PrintScheduler
  8013. per_type_humidity_thresholds: dict[str, int] = {}
  8014. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  8015. setting = result.scalar_one_or_none()
  8016. if setting and setting.value:
  8017. try:
  8018. raw = json.loads(setting.value)
  8019. if isinstance(raw, dict):
  8020. for k, v in raw.items():
  8021. try:
  8022. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  8023. v
  8024. )
  8025. except (TypeError, ValueError):
  8026. continue
  8027. except (ValueError, TypeError):
  8028. pass # Invalid JSON → no overrides, fall through to global threshold
  8029. # Per-AMS drying latch (#1802), loaded once per pass and written
  8030. # back below only if a unit changed it.
  8031. drying_latch = await _load_ams_drying_latch(db)
  8032. drying_latch_before = dict(drying_latch)
  8033. recorded_count = 0
  8034. for printer in printers:
  8035. # Get current state from printer manager
  8036. state = printer_manager.get_status(printer.id)
  8037. if not state or not state.connected or not state.raw_data:
  8038. continue # Skip disconnected printers - don't use stale data
  8039. raw_data = state.raw_data
  8040. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  8041. continue
  8042. # Record data for each AMS unit
  8043. for ams_data in raw_data["ams"]:
  8044. ams_id = int(ams_data.get("id", 0))
  8045. # Percentage only. The 1-5 index is inverted, so
  8046. # charting it as a percentage drew the wettest units as
  8047. # the driest (#3140); a unit that reports no percentage
  8048. # leaves a gap in the chart instead. See
  8049. # utils/ams_humidity.
  8050. humidity = ams_humidity_percent(ams_data)
  8051. # No supported printer is known to send the index
  8052. # alone -- the report came from unsupported firmware,
  8053. # and no install has been seen using the old fallback.
  8054. # "Known" is doing work there, so say so once per unit:
  8055. # the alternative is a silent blank card.
  8056. if humidity is None and ams_data.get("humidity") is not None:
  8057. unit_key = (printer.id, ams_id)
  8058. if unit_key not in _ams_index_only_logged:
  8059. _ams_index_only_logged.add(unit_key)
  8060. logger.info(
  8061. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  8062. "percentage. The index is inverted and is not shown as a percentage "
  8063. "(#3140), so this unit has no humidity reading, chart or alarm. "
  8064. "Please report this with the printer and AMS firmware versions.",
  8065. printer.name,
  8066. ams_id,
  8067. )
  8068. # Get temperature
  8069. temperature = None
  8070. temp_str = ams_data.get("temp")
  8071. if temp_str is not None:
  8072. try:
  8073. temperature = float(temp_str)
  8074. except (ValueError, TypeError):
  8075. pass # Skip unparseable temperature value
  8076. # Skip if no data
  8077. if humidity is None and temperature is None:
  8078. continue
  8079. # Record the data point
  8080. history = AMSSensorHistory(
  8081. printer_id=printer.id,
  8082. ams_id=ams_id,
  8083. humidity=humidity,
  8084. # Both columns hold the same reading now that the
  8085. # index can no longer reach ``humidity``. Writing it
  8086. # through the same value also stops a genuine 0%
  8087. # from being stored as NULL, which the old truthiness
  8088. # test did.
  8089. humidity_raw=humidity,
  8090. temperature=temperature,
  8091. )
  8092. db.add(history)
  8093. recorded_count += 1
  8094. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  8095. is_ams_ht = ams_id >= 128
  8096. if is_ams_ht:
  8097. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  8098. else:
  8099. ams_label = f"AMS-{chr(65 + ams_id)}"
  8100. # Skip alarm dispatch for empty AMS units — humidity /
  8101. # temperature readings are ambient with no filament to
  8102. # protect, and the hourly notification just becomes
  8103. # noise. Sensor history was already recorded above so
  8104. # the UI charts stay continuous (#1619). Per-AMS check
  8105. # so a multi-AMS setup with one loaded + one empty
  8106. # still alarms on the loaded unit.
  8107. if not _ams_has_filament(ams_data):
  8108. continue
  8109. # Resolve per-filament humidity threshold for this AMS
  8110. # unit (#1605). Falls back to the global ams_humidity_fair
  8111. # when no per-type overrides are configured.
  8112. trays = ams_data.get("tray", []) or []
  8113. effective_humidity_threshold = float(
  8114. PrintScheduler.resolve_humidity_threshold(
  8115. trays, per_type_humidity_thresholds, int(humidity_threshold)
  8116. )
  8117. )
  8118. # Check humidity alarm (only if above threshold)
  8119. if humidity is not None and humidity > effective_humidity_threshold:
  8120. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  8121. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8122. now = datetime.now(timezone.utc)
  8123. if (
  8124. last_alarm is None
  8125. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8126. ):
  8127. _ams_alarm_cooldown[cooldown_key] = now
  8128. logger.info(
  8129. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  8130. )
  8131. try:
  8132. # Call different notification method based on AMS type
  8133. if is_ams_ht:
  8134. await notification_service.on_ams_ht_humidity_high(
  8135. printer.id,
  8136. printer.name,
  8137. ams_label,
  8138. humidity,
  8139. effective_humidity_threshold,
  8140. db,
  8141. )
  8142. else:
  8143. await notification_service.on_ams_humidity_high(
  8144. printer.id,
  8145. printer.name,
  8146. ams_label,
  8147. humidity,
  8148. effective_humidity_threshold,
  8149. db,
  8150. )
  8151. except Exception as e:
  8152. logger.warning("Failed to send humidity alarm: %s", e)
  8153. # A drying cycle heats the unit far past ams_temp_fair on
  8154. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  8155. # AMS-HT, against a 35 C default — so the alarm fired
  8156. # once an hour for the whole cycle and kept firing while
  8157. # the unit cooled back down (#1802). Latch on the
  8158. # firmware's own drying state and hold until the reading
  8159. # returns to normal. Humidity is deliberately left alone:
  8160. # it falls during drying, which is the whole point.
  8161. latch_key = f"{printer.id}:{ams_id}"
  8162. # The latch releases at `threshold`, so it takes the alarm
  8163. # number too. Handing it the display band would strand the
  8164. # latch on any unit that settles back above it -- a room
  8165. # where the AMS rests at 37.7 C never returns under a 35 C
  8166. # band, so the latch could only expire on the grace cap
  8167. # rather than releasing when the unit had actually cooled.
  8168. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  8169. drying_active=is_drying_active(ams_data),
  8170. temperature=temperature,
  8171. threshold=temp_alarm_threshold,
  8172. latched_at=drying_latch.get(latch_key),
  8173. now=datetime.now(timezone.utc),
  8174. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  8175. )
  8176. if new_latch is None:
  8177. drying_latch.pop(latch_key, None)
  8178. else:
  8179. drying_latch[latch_key] = new_latch
  8180. # Check temperature alarm (only if above threshold)
  8181. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  8182. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  8183. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8184. now = datetime.now(timezone.utc)
  8185. if (
  8186. last_alarm is None
  8187. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8188. ):
  8189. _ams_alarm_cooldown[cooldown_key] = now
  8190. logger.info(
  8191. f"Sending temperature alarm for {printer.name} {ams_label}: "
  8192. f"{temperature}°C > {temp_alarm_threshold}°C"
  8193. )
  8194. try:
  8195. # Call different notification method based on AMS type
  8196. if is_ams_ht:
  8197. # The reported threshold has to be the one
  8198. # that fired, or the message says "> 35 °C"
  8199. # while firing at 45.
  8200. await notification_service.on_ams_ht_temperature_high(
  8201. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8202. )
  8203. else:
  8204. await notification_service.on_ams_temperature_high(
  8205. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8206. )
  8207. except Exception as e:
  8208. logger.warning("Failed to send temperature alarm: %s", e)
  8209. if drying_latch != drying_latch_before:
  8210. await _save_ams_drying_latch(db, drying_latch)
  8211. await db.commit()
  8212. if recorded_count > 0:
  8213. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  8214. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  8215. global _ams_cleanup_counter
  8216. _ams_cleanup_counter += 1
  8217. if _ams_cleanup_counter >= 288:
  8218. _ams_cleanup_counter = 0
  8219. # Get retention days from settings
  8220. from backend.app.models.settings import Settings
  8221. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  8222. setting = result.scalar_one_or_none()
  8223. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  8224. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8225. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  8226. await db.commit()
  8227. if result.rowcount > 0:
  8228. logger.info(
  8229. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  8230. )
  8231. # Wait until next recording interval
  8232. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  8233. except asyncio.CancelledError:
  8234. break
  8235. except Exception as e:
  8236. logger.warning("AMS history recording failed: %s", e)
  8237. await asyncio.sleep(60) # Wait a bit before retrying
  8238. def start_ams_history_recording():
  8239. """Start the AMS history recording background task."""
  8240. global _ams_history_task
  8241. if _ams_history_task is None:
  8242. _ams_history_task = asyncio.create_task(record_ams_history())
  8243. logging.getLogger(__name__).info("AMS history recording started")
  8244. def stop_ams_history_recording():
  8245. """Stop the AMS history recording background task."""
  8246. global _ams_history_task
  8247. if _ams_history_task:
  8248. _ams_history_task.cancel()
  8249. _ams_history_task = None
  8250. logging.getLogger(__name__).info("AMS history recording stopped")
  8251. # Printer sensor history recording (nozzle / bed / chamber)
  8252. _printer_sensor_history_task: asyncio.Task | None = None
  8253. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  8254. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  8255. _printer_sensor_cleanup_counter = 0
  8256. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  8257. # MQTT parser writes, so we don't need to handle per-model field aliases here
  8258. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  8259. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  8260. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  8261. _SENSOR_TARGET_KEYS = {
  8262. "nozzle": "nozzle_target",
  8263. "nozzle_2": "nozzle_2_target",
  8264. "bed": "bed_target",
  8265. "chamber": "chamber_target",
  8266. }
  8267. async def record_printer_sensor_history():
  8268. """Background task to record nozzle / bed / chamber readings.
  8269. Pulls from `state.temperatures` (already normalised across all printer
  8270. models by the MQTT parser) rather than re-parsing raw_data, so we get
  8271. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  8272. """
  8273. logger = logging.getLogger(__name__)
  8274. await asyncio.sleep(10)
  8275. while True:
  8276. try:
  8277. from backend.app.models.printer import Printer
  8278. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  8279. from backend.app.models.settings import Settings
  8280. async with async_session() as db:
  8281. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8282. printers = result.scalars().all()
  8283. recorded_count = 0
  8284. for printer in printers:
  8285. state = printer_manager.get_status(printer.id)
  8286. if not state or not state.connected:
  8287. continue
  8288. temps = getattr(state, "temperatures", None) or {}
  8289. if not isinstance(temps, dict):
  8290. continue
  8291. for kind in _SENSOR_KINDS:
  8292. if kind not in temps:
  8293. continue
  8294. try:
  8295. value = float(temps[kind])
  8296. except (ValueError, TypeError):
  8297. continue
  8298. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  8299. target_val: float | None = None
  8300. if target_raw is not None:
  8301. try:
  8302. target_val = float(target_raw)
  8303. except (ValueError, TypeError):
  8304. target_val = None
  8305. db.add(
  8306. PrinterSensorHistory(
  8307. printer_id=printer.id,
  8308. sensor_kind=kind,
  8309. value=value,
  8310. target=target_val,
  8311. )
  8312. )
  8313. recorded_count += 1
  8314. await db.commit()
  8315. if recorded_count > 0:
  8316. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  8317. # Periodic cleanup — once every ~24h at this interval.
  8318. global _printer_sensor_cleanup_counter
  8319. _printer_sensor_cleanup_counter += 1
  8320. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  8321. if _printer_sensor_cleanup_counter >= cleanup_every:
  8322. _printer_sensor_cleanup_counter = 0
  8323. result = await db.execute(
  8324. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  8325. )
  8326. setting = result.scalar_one_or_none()
  8327. retention_days = int(setting.value) if setting else PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  8328. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8329. cleanup = await db.execute(
  8330. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  8331. )
  8332. await db.commit()
  8333. if cleanup.rowcount > 0:
  8334. logger.info(
  8335. "Cleaned up %s old printer sensor history entries (older than %s days)",
  8336. cleanup.rowcount,
  8337. retention_days,
  8338. )
  8339. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  8340. except asyncio.CancelledError:
  8341. break
  8342. except Exception as e:
  8343. logger.warning("Printer sensor history recording failed: %s", e)
  8344. await asyncio.sleep(60)
  8345. def start_printer_sensor_history_recording():
  8346. global _printer_sensor_history_task
  8347. if _printer_sensor_history_task is None:
  8348. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  8349. logging.getLogger(__name__).info("Printer sensor history recording started")
  8350. def stop_printer_sensor_history_recording():
  8351. global _printer_sensor_history_task
  8352. if _printer_sensor_history_task:
  8353. _printer_sensor_history_task.cancel()
  8354. _printer_sensor_history_task = None
  8355. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  8356. # Printer runtime tracking
  8357. _runtime_tracking_task: asyncio.Task | None = None
  8358. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  8359. async def track_printer_runtime():
  8360. """Background task to track printer active runtime (RUNNING state only).
  8361. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  8362. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  8363. which track mechanical wear. Pause time has no motion and no wear, so
  8364. counting it inflates maintenance warnings (#1521).
  8365. """
  8366. logger = logging.getLogger(__name__)
  8367. # Wait for MQTT connections to establish on startup
  8368. await asyncio.sleep(15)
  8369. while True:
  8370. try:
  8371. from backend.app.models.printer import Printer
  8372. # Fetch printer IDs in a short-lived read-only session
  8373. async with async_session() as db:
  8374. result = await db.execute(
  8375. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  8376. Printer.is_active.is_(True)
  8377. )
  8378. )
  8379. printer_rows = result.all()
  8380. now = datetime.now(timezone.utc)
  8381. updated_count = 0
  8382. # Update each printer in its own short session to minimise write-lock
  8383. # hold time and avoid blocking critical commits like queue status
  8384. # updates (#897).
  8385. for pid, pname, runtime_secs, last_update in printer_rows:
  8386. state = printer_manager.get_status(pid)
  8387. if not state:
  8388. logger.debug("[%s] Runtime tracking: no state available", pname)
  8389. continue
  8390. if not state.connected:
  8391. logger.debug("[%s] Runtime tracking: not connected", pname)
  8392. continue
  8393. needs_commit = False
  8394. new_runtime = runtime_secs
  8395. new_last_update = last_update
  8396. if state.state == "RUNNING":
  8397. if last_update:
  8398. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  8399. elapsed = (now - lu).total_seconds()
  8400. if elapsed > 0:
  8401. new_runtime = runtime_secs + int(elapsed)
  8402. updated_count += 1
  8403. needs_commit = True
  8404. logger.debug(
  8405. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  8406. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  8407. )
  8408. else:
  8409. needs_commit = True
  8410. logger.debug("[%s] Runtime tracking: first active detection", pname)
  8411. new_last_update = now
  8412. else:
  8413. if last_update is not None:
  8414. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  8415. new_last_update = None
  8416. needs_commit = True
  8417. if needs_commit:
  8418. try:
  8419. async with async_session() as db:
  8420. result = await db.execute(select(Printer).where(Printer.id == pid))
  8421. printer = result.scalar_one_or_none()
  8422. if printer:
  8423. printer.runtime_seconds = new_runtime
  8424. printer.last_runtime_update = new_last_update
  8425. await db.commit()
  8426. except Exception as e:
  8427. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  8428. if updated_count > 0:
  8429. logger.debug("Updated runtime for %s printer(s)", updated_count)
  8430. except asyncio.CancelledError:
  8431. logger.info("Runtime tracking cancelled")
  8432. break
  8433. except Exception as e:
  8434. logger.warning("Runtime tracking failed: %s", e)
  8435. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  8436. def start_runtime_tracking():
  8437. """Start the printer runtime tracking background task."""
  8438. global _runtime_tracking_task
  8439. if _runtime_tracking_task is None:
  8440. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  8441. logging.getLogger(__name__).info("Printer runtime tracking started")
  8442. def stop_runtime_tracking():
  8443. """Stop the printer runtime tracking background task."""
  8444. global _runtime_tracking_task
  8445. if _runtime_tracking_task:
  8446. _runtime_tracking_task.cancel()
  8447. _runtime_tracking_task = None
  8448. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  8449. # SpoolBuddy device watchdog
  8450. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  8451. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  8452. async def _spoolbuddy_watchdog_loop():
  8453. """Periodic check for SpoolBuddy devices that have gone offline."""
  8454. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  8455. while True:
  8456. try:
  8457. await spoolbuddy_watchdog()
  8458. except asyncio.CancelledError:
  8459. break
  8460. except Exception as e:
  8461. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  8462. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  8463. def start_spoolbuddy_watchdog():
  8464. global _spoolbuddy_watchdog_task
  8465. if _spoolbuddy_watchdog_task is None:
  8466. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  8467. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  8468. def stop_spoolbuddy_watchdog():
  8469. global _spoolbuddy_watchdog_task
  8470. if _spoolbuddy_watchdog_task:
  8471. _spoolbuddy_watchdog_task.cancel()
  8472. _spoolbuddy_watchdog_task = None
  8473. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  8474. # Dead-MQTT-session recovery
  8475. #
  8476. # check_staleness() covers the "connected but silent" half-broken session. It
  8477. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  8478. # is the only thing left watching at that point. When paho stops making
  8479. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  8480. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  8481. # offline with the UI open the whole time, recovered only when something
  8482. # happened to nudge it.
  8483. #
  8484. # This loop is that backstop. It only touches printers that had a working
  8485. # session and lost it, and only when the MQTT port still answers — a printer
  8486. # that is simply switched off is left to paho, since rebuilding a client
  8487. # against an unreachable host achieves nothing and would fill the log every
  8488. # night.
  8489. _connection_watchdog_task: asyncio.Task | None = None
  8490. CONNECTION_WATCHDOG_INTERVAL = 60
  8491. # How long a printer must have been silent before we stop trusting paho.
  8492. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  8493. # so a session that is recovering on its own is never interrupted.
  8494. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  8495. # Per-printer floor between rebuild attempts.
  8496. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  8497. _connection_watchdog_last_attempt: dict[int, float] = {}
  8498. async def _recover_dead_printer_sessions() -> int:
  8499. """Rebuild MQTT clients that have been offline too long to still be trying.
  8500. Returns the number of printers a rebuild was attempted for (for tests and
  8501. for the caller's logging). Never raises: one unreachable printer must not
  8502. stop the sweep for the rest of the farm.
  8503. """
  8504. logger = logging.getLogger(__name__)
  8505. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  8506. now = time.monotonic()
  8507. recovered = 0
  8508. for printer_id, client in list(printer_manager._clients.items()):
  8509. try:
  8510. if client.state.connected:
  8511. _connection_watchdog_last_attempt.pop(printer_id, None)
  8512. continue
  8513. # Time since the last inbound message is the age of the last known
  8514. # good session — no extra bookkeeping needed, and it is the same
  8515. # clock is_stale() reads. 0 means this client has never had one:
  8516. # that is the initial-connect path, where paho retrying is the
  8517. # correct and only behaviour, so leave it be.
  8518. last_msg = client._last_message_time
  8519. if not last_msg:
  8520. continue
  8521. offline_for = time.time() - last_msg
  8522. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  8523. continue
  8524. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  8525. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  8526. continue
  8527. if not await check_port(client.ip_address, PORT_MQTT):
  8528. # Switched off, unplugged, or off the network. Paho's retry is
  8529. # the right handler; say so at debug level and move on.
  8530. logger.debug(
  8531. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  8532. "— leaving the reconnect to paho",
  8533. printer_id,
  8534. offline_for,
  8535. )
  8536. _connection_watchdog_last_attempt[printer_id] = now
  8537. continue
  8538. _connection_watchdog_last_attempt[printer_id] = now
  8539. recovered += 1
  8540. logger.warning(
  8541. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  8542. "rebuilding the client with a fresh session (last connect error: %s)",
  8543. printer_id,
  8544. offline_for,
  8545. PORT_MQTT,
  8546. client.last_connect_error or "none recorded",
  8547. )
  8548. # Async context, so this takes the hard-reset path: fresh client_id,
  8549. # paho's QoS 1 queue dropped. That matters — a project_file left
  8550. # unacked on the dead session would otherwise replay into the new
  8551. # one and trip 0500_4003 on the printer (#1136).
  8552. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  8553. except Exception as e:
  8554. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  8555. return recovered
  8556. async def _connection_watchdog_loop():
  8557. logger = logging.getLogger(__name__)
  8558. # Let the initial connects settle before judging anyone offline.
  8559. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  8560. while True:
  8561. try:
  8562. await _recover_dead_printer_sessions()
  8563. except asyncio.CancelledError:
  8564. break
  8565. except Exception as e:
  8566. logger.warning("Connection watchdog sweep failed: %s", e)
  8567. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  8568. def start_connection_watchdog():
  8569. global _connection_watchdog_task
  8570. if _connection_watchdog_task is None:
  8571. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  8572. logging.getLogger(__name__).info("Printer connection watchdog started")
  8573. def stop_connection_watchdog():
  8574. global _connection_watchdog_task
  8575. if _connection_watchdog_task:
  8576. _connection_watchdog_task.cancel()
  8577. _connection_watchdog_task = None
  8578. _connection_watchdog_last_attempt.clear()
  8579. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  8580. # Camera stream orphan cleanup
  8581. _camera_cleanup_task: asyncio.Task | None = None
  8582. CAMERA_CLEANUP_INTERVAL = 60
  8583. async def _camera_cleanup_loop():
  8584. """Periodically clean up orphaned ffmpeg processes."""
  8585. from backend.app.api.routes.camera import cleanup_orphaned_streams
  8586. while True:
  8587. try:
  8588. await cleanup_orphaned_streams()
  8589. except asyncio.CancelledError:
  8590. break
  8591. except Exception as e:
  8592. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  8593. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  8594. def start_camera_cleanup():
  8595. global _camera_cleanup_task
  8596. if _camera_cleanup_task is None:
  8597. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  8598. logging.getLogger(__name__).info("Camera stream cleanup started")
  8599. def stop_camera_cleanup():
  8600. global _camera_cleanup_task
  8601. if _camera_cleanup_task:
  8602. _camera_cleanup_task.cancel()
  8603. _camera_cleanup_task = None
  8604. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  8605. # ---------------------------------------------------------------------------
  8606. # Expected-print TTL eviction
  8607. # ---------------------------------------------------------------------------
  8608. def _evict_stale_expected_prints() -> None:
  8609. """Remove entries from _expected_prints / _expected_print_creators that are
  8610. older than _EXPECTED_PRINT_TTL_SECONDS.
  8611. This prevents unbounded growth when a print is registered (via
  8612. register_expected_print) but on_print_start never fires — e.g. because the
  8613. printer disconnects, the app restarts, or the print is started directly from
  8614. the printer panel without going through the queue.
  8615. """
  8616. # Use monotonic time so the TTL is unaffected by system clock adjustments
  8617. # (e.g. NTP sync, DST changes).
  8618. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  8619. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  8620. if not stale_keys:
  8621. return
  8622. evicted_archive_ids: set[int] = set()
  8623. for key in stale_keys:
  8624. archive_id = _expected_prints.pop(key, None)
  8625. if archive_id is not None:
  8626. evicted_archive_ids.add(archive_id)
  8627. _expected_print_creators.pop(key, None)
  8628. _expected_print_registered_at.pop(key, None)
  8629. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  8630. # that have no remaining live keys in _expected_prints (all variants
  8631. # were just evicted).
  8632. live_archive_ids = set(_expected_prints.values())
  8633. for archive_id in evicted_archive_ids:
  8634. if archive_id not in live_archive_ids:
  8635. _print_ams_mappings.pop(archive_id, None)
  8636. _print_cost_center_ids.pop(archive_id, None)
  8637. _print_plate_ids.pop(archive_id, None)
  8638. logging.getLogger(__name__).info(
  8639. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  8640. )
  8641. async def _expected_prints_cleanup_loop() -> None:
  8642. """Background task: periodically evict stale expected-print entries."""
  8643. while True:
  8644. try:
  8645. _evict_stale_expected_prints()
  8646. except asyncio.CancelledError:
  8647. raise
  8648. except Exception as e:
  8649. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  8650. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  8651. def start_expected_prints_cleanup() -> None:
  8652. global _expected_prints_cleanup_task
  8653. if _expected_prints_cleanup_task is None:
  8654. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  8655. logging.getLogger(__name__).info("Expected prints cleanup started")
  8656. def stop_expected_prints_cleanup() -> None:
  8657. global _expected_prints_cleanup_task
  8658. if _expected_prints_cleanup_task:
  8659. _expected_prints_cleanup_task.cancel()
  8660. _expected_prints_cleanup_task = None
  8661. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  8662. # ---------------------------------------------------------------------------
  8663. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  8664. # ---------------------------------------------------------------------------
  8665. _auth_cleanup_task: asyncio.Task | None = None
  8666. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  8667. async def _run_auth_cleanup() -> None:
  8668. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  8669. from backend.app.core.database import async_session
  8670. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  8671. from backend.app.models.user_totp import UserTOTP
  8672. now = datetime.now(timezone.utc)
  8673. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  8674. try:
  8675. async with async_session() as db:
  8676. stale_cutoff = now - timedelta(hours=1)
  8677. result = await db.execute(
  8678. select(UserTOTP).where(
  8679. UserTOTP.is_enabled.is_(False),
  8680. UserTOTP.created_at < stale_cutoff,
  8681. )
  8682. )
  8683. stale_records = result.scalars().all()
  8684. if stale_records:
  8685. for rec in stale_records:
  8686. await db.delete(rec)
  8687. await db.commit()
  8688. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  8689. except Exception as e:
  8690. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  8691. # Remove expired revoked-JTI entries (they are no longer needed once the
  8692. # original token's exp has passed — the token would be rejected by JWT
  8693. # signature verification regardless).
  8694. try:
  8695. async with async_session() as db:
  8696. await db.execute(
  8697. delete(AuthEphemeralToken).where(
  8698. AuthEphemeralToken.token_type == "revoked_jti",
  8699. AuthEphemeralToken.expires_at < now,
  8700. )
  8701. )
  8702. await db.commit()
  8703. except Exception as e:
  8704. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  8705. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  8706. # Events outside this window can never affect rate-limit decisions — they only
  8707. # consume DB space. Use the same window constant as the rate limiter so the
  8708. # two are always in sync.
  8709. try:
  8710. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  8711. async with async_session() as db:
  8712. await db.execute(
  8713. delete(AuthRateLimitEvent).where(
  8714. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  8715. )
  8716. )
  8717. await db.commit()
  8718. except Exception as e:
  8719. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  8720. async def _auth_cleanup_loop() -> None:
  8721. """Periodic background task: run auth cleanup every hour."""
  8722. while True:
  8723. try:
  8724. await _run_auth_cleanup()
  8725. except asyncio.CancelledError:
  8726. break
  8727. except Exception as e:
  8728. logging.warning("Auth cleanup loop error: %s", e)
  8729. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  8730. def start_auth_cleanup() -> None:
  8731. global _auth_cleanup_task
  8732. if _auth_cleanup_task is None:
  8733. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  8734. logging.getLogger(__name__).info("Auth periodic cleanup started")
  8735. def stop_auth_cleanup() -> None:
  8736. global _auth_cleanup_task
  8737. if _auth_cleanup_task:
  8738. _auth_cleanup_task.cancel()
  8739. _auth_cleanup_task = None
  8740. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  8741. @asynccontextmanager
  8742. async def lifespan(app: FastAPI):
  8743. # Startup
  8744. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  8745. # anything else can spawn tasks that might trip it.
  8746. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  8747. install_proactor_reset_filter()
  8748. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  8749. # what turned descriptor exhaustion into a corrupted database (#2883).
  8750. from backend.app.core.fd_limit import raise_open_file_limit
  8751. raise_open_file_limit()
  8752. # Before init_db, so the warning is near the top of the log rather than
  8753. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  8754. warn_if_running_on_uvloop()
  8755. await init_db()
  8756. # Browser download tokens expire after five minutes. Remove abandoned
  8757. # prepared ZIPs at startup as well as before each new preparation so a
  8758. # quiet appliance cannot retain an unusable bundle indefinitely.
  8759. try:
  8760. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  8761. await prune_stale_printer_file_bundles()
  8762. except Exception as exc:
  8763. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  8764. # After migrations, so the is_env_managed column exists. Never raises --
  8765. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  8766. # startup (see apply_env_oidc_provider).
  8767. from backend.app.core.oidc_env import apply_env_oidc_provider
  8768. async with async_session() as oidc_db:
  8769. await apply_env_oidc_provider(oidc_db)
  8770. # Close out batches that finished before `completed` was a reachable status
  8771. # (#342). Without this the Batches tab opens on every batch created since
  8772. # the feature shipped, all still marked active. Never blocks startup.
  8773. try:
  8774. from backend.app.services.print_batch import backfill_batch_statuses
  8775. async with async_session() as batch_db:
  8776. await backfill_batch_statuses(batch_db)
  8777. except Exception as exc:
  8778. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  8779. # Register an app-scoped httpx client for Bambu Cloud services so
  8780. # per-request BambuCloudService instances reuse the same connection pool
  8781. # (important for routes like /cloud/filament-info that chain many
  8782. # get_setting_detail calls). The shared client stores no region/token
  8783. # state, so the per-request ownership pattern that fixed the region-bleed
  8784. # bug is preserved.
  8785. import httpx as _httpx
  8786. from backend.app.services.bambu_cloud import set_shared_http_client
  8787. from backend.app.services.model_providers.makerworld.service import (
  8788. set_shared_http_client as set_shared_makerworld_http_client,
  8789. )
  8790. from backend.app.services.orca_cloud import (
  8791. set_shared_http_client as set_shared_orca_http_client,
  8792. )
  8793. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  8794. set_shared_http_client(_shared_cloud_http_client)
  8795. # Reuse the same connection pool for MakerWorld — different host, same
  8796. # keep-alive pool saves a TLS handshake per request.
  8797. set_shared_makerworld_http_client(_shared_cloud_http_client)
  8798. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  8799. # each spun up (and never closed) its own client, leaking sockets.
  8800. set_shared_orca_http_client(_shared_cloud_http_client)
  8801. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  8802. # This can happen when a print was cancelled mid-print on versions before this fix.
  8803. try:
  8804. async with async_session() as db:
  8805. from backend.app.models.print_queue import PrintQueueItem
  8806. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  8807. aborted_items = result.scalars().all()
  8808. if aborted_items:
  8809. for item in aborted_items:
  8810. item.status = "cancelled"
  8811. await db.commit()
  8812. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  8813. except Exception as e:
  8814. logging.warning("Failed to fix aborted queue items: %s", e)
  8815. # Restore debug logging state from previous session
  8816. await init_debug_logging()
  8817. # Set up printer manager callbacks
  8818. loop = asyncio.get_event_loop()
  8819. printer_manager.set_event_loop(loop)
  8820. printer_manager.set_status_change_callback(on_printer_status_change)
  8821. printer_manager.set_print_start_callback(on_print_start)
  8822. printer_manager.set_print_complete_callback(on_print_complete)
  8823. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  8824. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  8825. printer_manager.set_ams_change_callback(on_ams_change)
  8826. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  8827. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  8828. await printer_manager.load_awaiting_plate_clear_from_db()
  8829. # Layer change callback for external camera timelapse
  8830. async def on_layer_change(printer_id: int, layer_num: int):
  8831. """Capture timelapse frame on layer change + first layer notification."""
  8832. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  8833. await tl_layer_change(printer_id, layer_num)
  8834. # #1867: bank a recent in-print frame so the finish-photo path has a
  8835. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  8836. # #2547 added `on_print_progress` as a second driver — this one alone
  8837. # stops firing once the final layer begins.
  8838. await _maybe_bank_inprint_frame(printer_id, layer_num)
  8839. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  8840. # Gate on actual printing state — Bambu firmware ticks layer_num during
  8841. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  8842. # nozzle clean), so a bare layer_num check can fire minutes before the
  8843. # first real extrusion. We require gcode_state == RUNNING and
  8844. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  8845. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  8846. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  8847. # edge fires later; _first_layer_notified stays clear until we actually send
  8848. # so a deferred re-evaluation can win. See issue #1837.
  8849. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  8850. client = printer_manager.get_client(printer_id)
  8851. state = client.state if client else None
  8852. if not state or state.state != "RUNNING":
  8853. return
  8854. if state.mc_print_sub_stage not in (None, 0):
  8855. return
  8856. _first_layer_notified[printer_id] = True
  8857. try:
  8858. async with async_session() as db:
  8859. from backend.app.models.printer import Printer
  8860. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8861. printer = result.scalar_one_or_none()
  8862. if not printer:
  8863. return
  8864. printer_name = printer.name
  8865. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  8866. total_layers = state.total_layers if state else 0
  8867. image_data = await _capture_snapshot_for_notification(
  8868. printer_id, printer, logging.getLogger(__name__)
  8869. )
  8870. await notification_service.on_first_layer_complete(
  8871. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  8872. )
  8873. except Exception as e:
  8874. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  8875. printer_manager.set_layer_change_callback(on_layer_change)
  8876. async def on_print_progress(printer_id: int, percent: int):
  8877. """#2547: keep the in-print frame bank fresh through the final layer.
  8878. `on_layer_change` stops the moment the last layer starts, which on the
  8879. H2C capture that closed #2547 left the bank stale for the three minutes
  8880. that layer took. Progress is the only field that keeps advancing there,
  8881. and it freezes before the End G-code runs — so banking on it stays
  8882. inside the print and never sees a swapped plate.
  8883. """
  8884. client = printer_manager.get_client(printer_id)
  8885. state = client.state if client else None
  8886. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  8887. printer_manager.set_print_progress_callback(on_print_progress)
  8888. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  8889. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  8890. waiter = _bed_cool_waiters.get(printer_id)
  8891. if not waiter:
  8892. return
  8893. threshold = waiter["threshold"]
  8894. if bed_temp > threshold:
  8895. return
  8896. # Bed is at or below threshold — fire notification and remove waiter
  8897. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  8898. if not waiter_info:
  8899. return # Another callback already handled it
  8900. bed_cool_logger = logging.getLogger(__name__)
  8901. bed_cool_logger.info(
  8902. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  8903. bed_temp,
  8904. printer_id,
  8905. threshold,
  8906. )
  8907. try:
  8908. printer_info = printer_manager.get_printer(printer_id)
  8909. p_name = printer_info.name if printer_info else "Unknown"
  8910. async with async_session() as db:
  8911. await notification_service.on_bed_cooled(
  8912. printer_id=printer_id,
  8913. printer_name=p_name,
  8914. bed_temp=bed_temp,
  8915. threshold=threshold,
  8916. filename=waiter_info["filename"],
  8917. db=db,
  8918. )
  8919. except Exception as e:
  8920. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  8921. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  8922. async def on_drying_complete(printer_id: int, ams_id: int):
  8923. """Smart-plug auto-off-after-drying trigger (#1349).
  8924. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  8925. manager walks all plugs linked to this printer and turns off only
  8926. the ones with ``auto_off_after_drying`` enabled, after their
  8927. per-plug delay. Multiple AMS units finishing close together (e.g. a
  8928. dual-AMS dry that ends within the same MQTT push) call this once
  8929. per unit — the manager's ``_cancel_pending_off`` collapses
  8930. repeated scheduling on the same plug to one timer, so duplicate
  8931. fires are safe.
  8932. """
  8933. try:
  8934. async with async_session() as db:
  8935. await smart_plug_manager.on_drying_complete(printer_id, db)
  8936. except Exception as e:
  8937. logging.getLogger(__name__).warning(
  8938. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  8939. printer_id,
  8940. ams_id,
  8941. e,
  8942. )
  8943. printer_manager.set_drying_complete_callback(on_drying_complete)
  8944. async def on_drying_cycle_end(printer_id: int, cycle):
  8945. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  8946. from backend.app.services.spool_drying import record_drying_cycle
  8947. try:
  8948. async with async_session() as db:
  8949. await record_drying_cycle(db, printer_id, cycle)
  8950. except Exception as e:
  8951. logging.getLogger(__name__).warning(
  8952. "Failed to record drying for printer %d (AMS %d): %s",
  8953. printer_id,
  8954. cycle.ams_id,
  8955. e,
  8956. )
  8957. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  8958. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  8959. """Surface the read-back result of a spool assignment to the UI (#2582).
  8960. The MQTT client confirms (or fails to confirm) that the tray telemetry
  8961. echoed back the filament id we pushed. We relay that as a websocket
  8962. event so the frontend can toast "loaded" / "assignment didn't take"
  8963. instead of the historic silent fire-and-forget, which made the
  8964. AMS→Studio hand-off feel random to users.
  8965. """
  8966. try:
  8967. from backend.app.services.spool_assignment_notifications import (
  8968. _slot_label_from_global_tray,
  8969. )
  8970. if ams_id == 255:
  8971. global_id = 254 + tray_id
  8972. elif ams_id >= 128:
  8973. global_id = ams_id
  8974. else:
  8975. global_id = ams_id * 4 + tray_id
  8976. slot_label = _slot_label_from_global_tray(global_id)
  8977. printer_info = printer_manager.get_printer(printer_id)
  8978. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  8979. await ws_manager.broadcast(
  8980. {
  8981. "type": "spool_assignment_verified",
  8982. "printer_id": printer_id,
  8983. "printer_name": printer_name,
  8984. "ams_id": ams_id,
  8985. "tray_id": tray_id,
  8986. "slot": slot_label,
  8987. "verified": verified,
  8988. # Present on success: False means the filament setting landed
  8989. # but the K-profile (cali_idx) did not — the reporter's exact
  8990. # "loaded but no flow profile" symptom.
  8991. "kprofile_applied": detail.get("kprofile_applied", True),
  8992. # Present on failure: whether any tray telemetry was seen in
  8993. # the window (distinguishes "printer silent" from "printer
  8994. # stored something else").
  8995. "saw_tray": detail.get("saw_tray", False),
  8996. }
  8997. )
  8998. except Exception as e:
  8999. logging.getLogger(__name__).warning(
  9000. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  9001. printer_id,
  9002. ams_id,
  9003. tray_id,
  9004. e,
  9005. )
  9006. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  9007. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  9008. """Persist a mid-print tray change for completion-time attribution.
  9009. AMS filament backup switches trays without telling the slicer, so the
  9010. tray-change log is the only record of which spool fed which layers.
  9011. Keeping it only in memory meant a restart mid-print charged everything
  9012. to the tray that finished the job.
  9013. """
  9014. try:
  9015. from backend.app.services.usage_tracker import record_tray_change
  9016. async with async_session() as db:
  9017. await record_tray_change(db, printer_id, tray_global, layer_num)
  9018. except Exception as e:
  9019. logging.getLogger(__name__).warning(
  9020. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  9021. printer_id,
  9022. tray_global,
  9023. layer_num,
  9024. e,
  9025. )
  9026. printer_manager.set_tray_change_callback(on_tray_change)
  9027. # Initialize MQTT relay from settings
  9028. async with async_session() as db:
  9029. from backend.app.api.routes.settings import get_setting
  9030. mqtt_settings = {
  9031. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  9032. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  9033. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  9034. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  9035. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  9036. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  9037. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  9038. }
  9039. await mqtt_relay.configure(mqtt_settings)
  9040. # Restore MQTT smart plug subscriptions
  9041. if mqtt_settings.get("mqtt_enabled"):
  9042. from backend.app.models.smart_plug import SmartPlug
  9043. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  9044. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  9045. mqtt_plugs = result.scalars().all()
  9046. restored = 0
  9047. for plug in mqtt_plugs:
  9048. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  9049. restored += 1
  9050. if restored:
  9051. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  9052. # Connect to all active printers
  9053. async with async_session() as db:
  9054. await init_printer_connections(db)
  9055. # Auto-connect to Spoolman if enabled
  9056. async with async_session() as db:
  9057. from backend.app.api.routes.settings import get_setting
  9058. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  9059. spoolman_url = await get_setting(db, "spoolman_url")
  9060. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  9061. try:
  9062. client = await init_spoolman_client(spoolman_url)
  9063. if await client.health_check():
  9064. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  9065. # Ensure the 'tag' extra field exists for RFID/UUID storage
  9066. field_ok = await client.ensure_tag_extra_field()
  9067. if not field_ok:
  9068. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  9069. # Register the BambuStudio slicer-preset fields used by the
  9070. # spool-edit / assign flow. Spoolman rejects PATCHes with
  9071. # unknown extra keys, so these must exist before any update
  9072. # that touches them.
  9073. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  9074. if not await client.ensure_extra_field(field_name):
  9075. logging.warning(
  9076. "Spoolman extra field %r registration failed — "
  9077. "spool slicer-preset edits will return 502",
  9078. field_name,
  9079. )
  9080. else:
  9081. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  9082. except Exception as e:
  9083. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  9084. # Start the print scheduler
  9085. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  9086. # Start the smart plug scheduler for time-based on/off
  9087. smart_plug_manager.start_scheduler()
  9088. # Start the Home Assistant sensor poller (#1148)
  9089. ha_sensor_manager.start()
  9090. location_ha_sensor_manager.start()
  9091. # Resume any pending auto-offs that were interrupted by restart
  9092. await smart_plug_manager.resume_pending_auto_offs()
  9093. # Start the notification digest scheduler
  9094. notification_service.start_digest_scheduler()
  9095. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  9096. # provider in reactions/both mode; the notification routes resync them.
  9097. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  9098. # until the next provider save, not the whole startup.
  9099. try:
  9100. await telegram_reaction_poller.start()
  9101. except Exception as e:
  9102. logging.warning("Telegram reaction poller did not start: %s", e)
  9103. # Start the GitHub backup scheduler
  9104. await github_backup_service.start_scheduler()
  9105. # Start the local backup scheduler
  9106. await local_backup_service.start_scheduler()
  9107. await obico_detection_service.start()
  9108. # Start the library trash sweeper (#1008)
  9109. await library_trash_service.start_scheduler()
  9110. # Start the archive auto-purge sweeper (#1008 follow-up)
  9111. await archive_purge_service.start_scheduler()
  9112. # Start AMS history recording
  9113. start_ams_history_recording()
  9114. # Start printer sensor (nozzle / bed / chamber) history recording
  9115. start_printer_sensor_history_recording()
  9116. # Start printer runtime tracking
  9117. start_runtime_tracking()
  9118. # Start SpoolBuddy device watchdog
  9119. start_spoolbuddy_watchdog()
  9120. # Start camera stream orphan cleanup
  9121. start_camera_cleanup()
  9122. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  9123. start_connection_watchdog()
  9124. # One-shot sweep for timelapse session directories orphaned by a crash
  9125. # or restart that happened mid-print (in-memory session tracking can't
  9126. # survive that, and nothing else reaps the leftover frames/output file)
  9127. try:
  9128. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9129. removed = cleanup_orphaned_timelapse_sessions()
  9130. if removed:
  9131. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  9132. except Exception as e:
  9133. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  9134. # Start expected-print TTL eviction (prevents memory leak when prints are
  9135. # registered but on_print_start never fires)
  9136. start_expected_prints_cleanup()
  9137. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  9138. start_auth_cleanup()
  9139. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  9140. from backend.app.services import announcements as announcements_service
  9141. announcements_service.start()
  9142. from backend.app.services.printer_media import start_printer_download_cleanup
  9143. start_printer_download_cleanup()
  9144. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  9145. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  9146. from backend.app.services.loop_watchdog import start_loop_watchdog
  9147. start_loop_watchdog()
  9148. # Initialize virtual printer manager and sync from DB
  9149. from backend.app.services.virtual_printer import virtual_printer_manager
  9150. virtual_printer_manager.set_session_factory(async_session)
  9151. virtual_printer_manager.set_printer_manager(printer_manager)
  9152. try:
  9153. await virtual_printer_manager.sync_from_db()
  9154. logging.info("Virtual printer manager synced from database")
  9155. except Exception as e:
  9156. logging.warning("Failed to sync virtual printers: %s", e)
  9157. yield
  9158. # Shutdown
  9159. print_scheduler.stop()
  9160. smart_plug_manager.stop_scheduler()
  9161. ha_sensor_manager.stop()
  9162. location_ha_sensor_manager.stop()
  9163. notification_service.stop_digest_scheduler()
  9164. await telegram_reaction_poller.aclose()
  9165. github_backup_service.stop_scheduler()
  9166. local_backup_service.stop_scheduler()
  9167. library_trash_service.stop_scheduler()
  9168. archive_purge_service.stop_scheduler()
  9169. obico_detection_service.stop()
  9170. stop_ams_history_recording()
  9171. stop_printer_sensor_history_recording()
  9172. stop_runtime_tracking()
  9173. stop_spoolbuddy_watchdog()
  9174. stop_camera_cleanup()
  9175. stop_connection_watchdog()
  9176. from backend.app.services.loop_watchdog import stop_loop_watchdog
  9177. stop_loop_watchdog()
  9178. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  9179. # cleanly rather than waiting on a queue that nothing will ever fill.
  9180. try:
  9181. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  9182. await shutdown_all_broadcasters()
  9183. except Exception as e:
  9184. logging.warning("Failed to shut down camera broadcasters: %s", e)
  9185. stop_expected_prints_cleanup()
  9186. stop_auth_cleanup()
  9187. from backend.app.services import announcements as announcements_service
  9188. announcements_service.stop()
  9189. from backend.app.services.printer_media import stop_printer_download_cleanup
  9190. await stop_printer_download_cleanup()
  9191. printer_manager.disconnect_all()
  9192. slot_unlink_grace.reset()
  9193. await close_spoolman_client()
  9194. # Stop all virtual printer services
  9195. await virtual_printer_manager.stop_all()
  9196. await mqtt_smart_plug_service.disconnect(timeout=2)
  9197. await mqtt_relay.disconnect(timeout=2)
  9198. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  9199. set_shared_http_client(None)
  9200. set_shared_makerworld_http_client(None)
  9201. set_shared_orca_http_client(None)
  9202. await _shared_cloud_http_client.aclose()
  9203. # Checkpoint WAL (SQLite only) and close all database connections
  9204. from backend.app.core.db_dialect import is_sqlite
  9205. if is_sqlite():
  9206. try:
  9207. async with engine.begin() as conn:
  9208. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  9209. logging.info("WAL checkpoint completed")
  9210. except Exception as e:
  9211. logging.warning("WAL checkpoint failed: %s", e)
  9212. await engine.dispose()
  9213. app = FastAPI(
  9214. title=app_settings.app_name,
  9215. description="Archive and manage Bambu Lab 3MF files",
  9216. version=APP_VERSION,
  9217. lifespan=lifespan,
  9218. )
  9219. # =============================================================================
  9220. # Authentication Middleware - Secures ALL API routes by default
  9221. # =============================================================================
  9222. # Public routes that don't require authentication even when auth is enabled
  9223. PUBLIC_API_ROUTES = {
  9224. # Auth routes needed before/during login
  9225. "/api/v1/auth/status",
  9226. "/api/v1/auth/login",
  9227. "/api/v1/auth/setup", # Needed for initial setup and recovery
  9228. # Advanced auth status needed for login page
  9229. "/api/v1/auth/advanced-auth/status",
  9230. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  9231. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  9232. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  9233. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  9234. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  9235. # OIDC routes that must be reachable without a JWT
  9236. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  9237. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  9238. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  9239. # Connected apps: the app's server swaps a code for the user's identity,
  9240. # authenticated by its client secret rather than a login token.
  9241. "/api/v1/connect/token",
  9242. # Version check for updates (no sensitive data)
  9243. "/api/v1/updates/version",
  9244. # Metrics endpoint handles its own prometheus_token authentication
  9245. "/api/v1/metrics",
  9246. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  9247. # this BEFORE a JWT is available to pick up the firstboot wizard's
  9248. # hostname / timezone / locale and the chrony NTP-gate state. The
  9249. # response contains user-set defaults and a public sync flag — no
  9250. # secrets. Without this entry the global auth middleware returns 401
  9251. # before the route handler runs, regardless of the route's own
  9252. # "no auth required" intent.
  9253. "/api/v1/system/appliance",
  9254. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  9255. # authenticates with a long-lived ``camwall``-scoped token in the query
  9256. # string — exactly like the camera streams two lists below, and for the same
  9257. # reason (no header to put a JWT in). "Public" here only means the middleware
  9258. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  9259. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  9260. # plain ``camera_stream`` token does NOT open this door.
  9261. "/api/v1/camwall/printers",
  9262. # Overlay branding: the route enforces overlay-scoped token authentication.
  9263. "/api/v1/overlay-branding/logo",
  9264. }
  9265. # Route prefixes that are public (for routes with dynamic segments)
  9266. PUBLIC_API_PREFIXES = [
  9267. # WebSocket connections handle their own auth
  9268. "/api/v1/ws",
  9269. # OIDC authorize redirects — include provider_id in path
  9270. "/api/v1/auth/oidc/authorize/",
  9271. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  9272. # a phone with no session, so no header can carry a JWT — the single-use
  9273. # capability token in the path IS the credential (same reasoning as the
  9274. # /dl/ slicer downloads below). The route grants nothing beyond writing
  9275. # good/reject on the one archive the token was minted for.
  9276. "/api/v1/archives/confirm/",
  9277. ]
  9278. # Route patterns that are public (read-only display data)
  9279. # These are checked with "in path" - needed because browsers load images/videos
  9280. # via <img src> and <video src> which don't include Authorization headers
  9281. PUBLIC_API_PATTERNS = [
  9282. # Thumbnails
  9283. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  9284. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  9285. # Images and media
  9286. "/photos/", # /archives/{id}/photos/{filename}
  9287. "/project-image/", # /archives/{id}/project-image/{path}
  9288. "/qrcode", # /archives/{id}/qrcode
  9289. "/timelapse", # /archives/{id}/timelapse (video)
  9290. "/cover", # /printers/{id}/cover
  9291. "/icon", # /external-links/{id}/icon
  9292. # Camera (streams loaded via <img> tag)
  9293. "/camera/stream", # /printers/{id}/camera/stream
  9294. "/camera/snapshot", # /printers/{id}/camera/snapshot
  9295. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  9296. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  9297. # string (same reasoning as the camera streams above — no header to carry a
  9298. # JWT). "Public" only means the middleware steps aside; the route still runs
  9299. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  9300. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  9301. "/overlay-status", # /printers/{id}/overlay-status
  9302. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  9303. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  9304. # download token in the URL path instead.
  9305. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  9306. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  9307. # and these patterns match by substring. Without its own entry the middleware
  9308. # 401s the slicer's header-less request before the route's token check runs,
  9309. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  9310. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  9311. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  9312. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  9313. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  9314. ]
  9315. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  9316. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  9317. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  9318. Format: comma-separated list of ``scheme://host[:port]`` origins.
  9319. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  9320. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  9321. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  9322. Invalid entries are dropped with a warning rather than failing startup, so
  9323. a typo in one origin doesn't take the whole deployment down.
  9324. """
  9325. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  9326. if not raw:
  9327. return ()
  9328. valid: list[str] = []
  9329. for item in raw.split(","):
  9330. candidate = item.strip()
  9331. if not candidate:
  9332. continue
  9333. try:
  9334. parsed = urlparse(candidate)
  9335. except ValueError as e:
  9336. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  9337. continue
  9338. if parsed.scheme not in ("http", "https"):
  9339. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  9340. continue
  9341. if not parsed.netloc:
  9342. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  9343. continue
  9344. if parsed.path and parsed.path != "/":
  9345. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  9346. continue
  9347. if parsed.query or parsed.fragment:
  9348. _security_headers_logger.warning(
  9349. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  9350. )
  9351. continue
  9352. if "*" in parsed.netloc:
  9353. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  9354. continue
  9355. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  9356. if valid:
  9357. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  9358. return tuple(valid)
  9359. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  9360. def _frame_ancestors(default_value: str) -> str:
  9361. """Compose the ``frame-ancestors`` CSP directive (#1191).
  9362. ``default_value`` is the strict directive used when the operator has not
  9363. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  9364. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  9365. Settings URL builder's preview). When trusted origins
  9366. are configured, ``'self'`` is always included so same-origin embedding never
  9367. breaks even if an operator forgets to add their own origin to the list.
  9368. """
  9369. if _TRUSTED_FRAME_ORIGINS:
  9370. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  9371. return f"frame-ancestors {default_value};"
  9372. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  9373. # patterns are anchored on the exact emitted name so the relaxed policies
  9374. # below can never apply to any other asset.
  9375. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  9376. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  9377. # -> /assets/pdf.worker.min-<hash>.js
  9378. # Vite also emits a one-line chunk under the second name that only exports the
  9379. # worker's URL. The page imports it as a module, and a module script is run
  9380. # under the importing document's policy, never its own response's, so it
  9381. # matching as well changes nothing.
  9382. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  9383. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  9384. @app.middleware("http")
  9385. async def security_headers_middleware(request, call_next):
  9386. """Add standard HTTP security headers to every response."""
  9387. # Per-request nonce stamped into `script-src` (#1460). On its own this
  9388. # changes nothing for Bambuddy's own pages — index.html has no inline
  9389. # scripts since the SW registration moved to /sw-register.js. The reason
  9390. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  9391. # script injected into the HTML on the edge, with a fresh hash on every
  9392. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  9393. # it clones the same nonce onto its injected <script>, and the inline
  9394. # script passes the policy without us needing 'unsafe-inline'. See
  9395. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  9396. csp_nonce = secrets.token_urlsafe(16)
  9397. # Routes that render their own HTML need it too, or their inline script is
  9398. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  9399. # one that does: it submits its own form so a verdict still costs one tap.
  9400. request.state.csp_nonce = csp_nonce
  9401. response = await call_next(request)
  9402. response.headers["X-Content-Type-Options"] = "nosniff"
  9403. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  9404. # browsers honour CSP frame-ancestors instead, and the legacy
  9405. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  9406. # When operators have explicitly allowlisted trusted frame origins (#1191
  9407. # — typically Home Assistant on a different port), drop X-Frame-Options
  9408. # and let the CSP-side frame-ancestors directive govern embedding.
  9409. if not _TRUSTED_FRAME_ORIGINS:
  9410. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  9411. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  9412. # Content-Security-Policy for the React SPA.
  9413. # Notes:
  9414. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  9415. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  9416. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  9417. # - media-src blob:: timelapse video player uses Blob URLs.
  9418. # - font-src data:: some icon fonts are embedded as data URIs.
  9419. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  9420. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  9421. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  9422. # default CSP would render a blank page.
  9423. response.headers["Content-Security-Policy"] = (
  9424. "default-src 'self'; "
  9425. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  9426. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  9427. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  9428. "connect-src 'self'; "
  9429. "font-src 'self' data: https://fonts.gstatic.com; "
  9430. "worker-src 'self' blob:; "
  9431. "object-src 'none'; "
  9432. "base-uri 'self'; " + _frame_ancestors("'none'")
  9433. )
  9434. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  9435. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  9436. # its emscripten/embind glue generates invoker functions with `new
  9437. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  9438. # worker is governed by the policy delivered with the WORKER SCRIPT's
  9439. # own response — not the document's — so relaxing it here confines
  9440. # eval to that DOM-less worker context. The document policy below
  9441. # stays nonce-strict, and this response header has no effect when the
  9442. # file is merely fetched (a fetch's CSP is enforced against the
  9443. # requesting document, not the resource's own headers).
  9444. response.headers["Content-Security-Policy"] = (
  9445. "default-src 'self'; "
  9446. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  9447. "connect-src 'self'; "
  9448. "object-src 'none'; "
  9449. "base-uri 'self'; " + _frame_ancestors("'none'")
  9450. )
  9451. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  9452. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  9453. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  9454. # rule as the STEP worker above: the policy that governs a dedicated
  9455. # worker is the one delivered with its own script, so the wasm compile
  9456. # has to be permitted here rather than on the document. Unlike the STEP
  9457. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  9458. response.headers["Content-Security-Policy"] = (
  9459. "default-src 'self'; "
  9460. "script-src 'self' 'wasm-unsafe-eval'; "
  9461. "connect-src 'self'; "
  9462. "object-src 'none'; "
  9463. "base-uri 'self'; " + _frame_ancestors("'none'")
  9464. )
  9465. else:
  9466. # The streaming overlay is embedded same-origin by the URL builder's
  9467. # preview in Settings (#1422), so this branch allows 'self'.
  9468. # Embedding from anywhere else is still refused: 'self'
  9469. # only permits a framer on this origin, which is Bambuddy's own UI, so
  9470. # a clickjacking page on another host is blocked exactly as before.
  9471. # (The overlay draws status over a camera feed and its only interactive
  9472. # element is the logo link, so there is nothing to bait a click into
  9473. # even from a same-origin framer.) Cross-origin embedding of the
  9474. # overlay — Home Assistant on another port — remains what
  9475. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  9476. # allowlist in.
  9477. #
  9478. # The connected-app consent page (/connect/authorize) gets the same
  9479. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  9480. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  9481. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  9482. # requires every ancestor to be this origin, so a foreign page -- a
  9483. # sidebar link's site included -- still cannot frame the consent
  9484. # screen to bait a click.
  9485. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  9486. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  9487. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  9488. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  9489. # the policy served with their own script, so each gets it in its own
  9490. # branch above and the document policy stays as strict as it was.
  9491. response.headers["Content-Security-Policy"] = (
  9492. "default-src 'self'; "
  9493. f"script-src 'self' 'nonce-{csp_nonce}'; "
  9494. "style-src 'self' 'unsafe-inline'; "
  9495. "img-src 'self' data: blob:; "
  9496. "media-src 'self' blob:; "
  9497. "connect-src 'self' ws: wss:; "
  9498. "font-src 'self' data:; "
  9499. "object-src 'none'; "
  9500. "base-uri 'self'; "
  9501. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  9502. )
  9503. if request.url.scheme == "https":
  9504. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  9505. return response
  9506. @app.middleware("http")
  9507. async def auth_middleware(request, call_next):
  9508. """Enforce authentication on all API routes when auth is enabled.
  9509. This middleware provides defense-in-depth by checking auth at the API gateway level,
  9510. regardless of whether individual routes have auth dependencies.
  9511. """
  9512. from starlette.responses import JSONResponse
  9513. path = request.url.path
  9514. # Only apply to API routes
  9515. if not path.startswith("/api/"):
  9516. return await call_next(request)
  9517. # Allow public routes
  9518. if path in PUBLIC_API_ROUTES:
  9519. return await call_next(request)
  9520. # Allow public prefixes
  9521. for prefix in PUBLIC_API_PREFIXES:
  9522. if path.startswith(prefix):
  9523. return await call_next(request)
  9524. # Allow public patterns (read-only display data like thumbnails)
  9525. for pattern in PUBLIC_API_PATTERNS:
  9526. if pattern in path:
  9527. return await call_next(request)
  9528. # Check if auth is enabled. Fail CLOSED on any exception during the
  9529. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  9530. # an attacker who could force a DB exception (e.g. file-descriptor
  9531. # exhaustion via login flood) bypass auth on every protected endpoint.
  9532. try:
  9533. async with async_session() as db:
  9534. from backend.app.core.auth import is_auth_enabled
  9535. auth_enabled = await is_auth_enabled(db)
  9536. if not auth_enabled:
  9537. # Auth disabled, allow all requests
  9538. return await call_next(request)
  9539. except Exception:
  9540. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  9541. return JSONResponse(
  9542. status_code=503,
  9543. content={"detail": "Authentication service temporarily unavailable"},
  9544. )
  9545. # Auth is enabled - require valid token
  9546. auth_header = request.headers.get("Authorization")
  9547. x_api_key = request.headers.get("X-API-Key")
  9548. # Check for API key auth first
  9549. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  9550. # API key authentication - let the request through to be validated by route handler
  9551. # API keys are validated per-route since they have different permission levels
  9552. return await call_next(request)
  9553. # Check for JWT auth
  9554. if not auth_header or not auth_header.startswith("Bearer "):
  9555. return JSONResponse(
  9556. status_code=401,
  9557. content={"detail": "Authentication required"},
  9558. headers={"WWW-Authenticate": "Bearer"},
  9559. )
  9560. # Validate JWT token
  9561. import jwt
  9562. try:
  9563. from backend.app.core.auth import (
  9564. ALGORITHM,
  9565. SECRET_KEY,
  9566. _is_token_fresh,
  9567. get_user_by_username,
  9568. is_jti_revoked,
  9569. )
  9570. token = auth_header.replace("Bearer ", "")
  9571. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  9572. username = payload.get("sub")
  9573. if not username:
  9574. raise ValueError("No username in token")
  9575. jti = payload.get("jti")
  9576. if not jti:
  9577. raise ValueError("No jti in token")
  9578. iat = payload.get("iat")
  9579. # Verify user exists, is active, and token is still fresh (L-R8-A).
  9580. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  9581. # this session so the gateway adds a single pooled checkout, not two (#2572).
  9582. async with async_session() as db:
  9583. if await is_jti_revoked(jti, db):
  9584. return JSONResponse(
  9585. status_code=401,
  9586. content={"detail": "Token has been revoked"},
  9587. headers={"WWW-Authenticate": "Bearer"},
  9588. )
  9589. user = await get_user_by_username(db, username)
  9590. if not user or not user.is_active:
  9591. return JSONResponse(
  9592. status_code=401,
  9593. content={"detail": "User not found or inactive"},
  9594. headers={"WWW-Authenticate": "Bearer"},
  9595. )
  9596. if not _is_token_fresh(iat, user):
  9597. return JSONResponse(
  9598. status_code=401,
  9599. content={"detail": "Token no longer valid"},
  9600. headers={"WWW-Authenticate": "Bearer"},
  9601. )
  9602. except jwt.ExpiredSignatureError:
  9603. return JSONResponse(
  9604. status_code=401,
  9605. content={"detail": "Token has expired"},
  9606. headers={"WWW-Authenticate": "Bearer"},
  9607. )
  9608. except (jwt.InvalidTokenError, ValueError, Exception):
  9609. return JSONResponse(
  9610. status_code=401,
  9611. content={"detail": "Invalid token"},
  9612. headers={"WWW-Authenticate": "Bearer"},
  9613. )
  9614. return await call_next(request)
  9615. @app.middleware("http")
  9616. async def trace_id_middleware(request, call_next):
  9617. """Stamp every HTTP request with a trace ID and echo it back.
  9618. Decorated AFTER auth_middleware on purpose: Starlette stacks
  9619. @app.middleware decorators LIFO, so the last-decorated runs first
  9620. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  9621. which means auth-middleware log lines (and every line emitted on the
  9622. way down to and back from the route handler) all carry the same
  9623. trace ID. If we put it before auth, auth's logs would be stamped
  9624. with the *previous* request's ID — useless for correlation.
  9625. Honours an inbound ``X-Trace-Id`` header so callers running their
  9626. own tracing can correlate their span IDs with our log lines, but
  9627. only if the value passes the whitelist gate in
  9628. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  9629. rejected (too long, contains control chars, etc.) silently triggers
  9630. a freshly minted server-side ID rather than failing the request.
  9631. The minted (or echoed) ID is set on a ContextVar so that every log
  9632. record emitted during the request — application logs *and* uvicorn's
  9633. access log — carries it via TraceIDFilter, and is also written to
  9634. the ``X-Trace-Id`` response header so clients can pin a server-side
  9635. log search to the exact request they made.
  9636. """
  9637. from backend.app.core.trace import (
  9638. generate_trace_id,
  9639. normalise_inbound_trace_id,
  9640. trace_id_var,
  9641. )
  9642. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  9643. trace_id = inbound if inbound is not None else generate_trace_id()
  9644. token = trace_id_var.set(trace_id)
  9645. try:
  9646. response = await call_next(request)
  9647. finally:
  9648. # Reset the ContextVar so a record emitted in a totally
  9649. # unrelated background task that just happens to inherit this
  9650. # context doesn't keep referencing this request's ID forever.
  9651. # In practice ContextVar.reset is best-effort under asyncio
  9652. # task-spawn semantics, but the cost is one attribute write so
  9653. # we may as well do it.
  9654. trace_id_var.reset(token)
  9655. response.headers["X-Trace-Id"] = trace_id
  9656. return response
  9657. # API routes
  9658. app.include_router(auth.router, prefix=app_settings.api_prefix)
  9659. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  9660. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  9661. app.include_router(users.router, prefix=app_settings.api_prefix)
  9662. app.include_router(groups.router, prefix=app_settings.api_prefix)
  9663. app.include_router(printers.router, prefix=app_settings.api_prefix)
  9664. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  9665. app.include_router(archives.router, prefix=app_settings.api_prefix)
  9666. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  9667. app.include_router(finance.router, prefix=app_settings.api_prefix)
  9668. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  9669. app.include_router(labels.router, prefix=app_settings.api_prefix)
  9670. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  9671. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  9672. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  9673. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  9674. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  9675. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  9676. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  9677. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  9678. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  9679. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  9680. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  9681. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  9682. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  9683. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  9684. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  9685. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  9686. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  9687. app.include_router(updates.router, prefix=app_settings.api_prefix)
  9688. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  9689. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  9690. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  9691. app.include_router(camera.router, prefix=app_settings.api_prefix)
  9692. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  9693. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  9694. app.include_router(projects.router, prefix=app_settings.api_prefix)
  9695. app.include_router(library.router, prefix=app_settings.api_prefix)
  9696. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  9697. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  9698. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  9699. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  9700. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  9701. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  9702. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  9703. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  9704. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  9705. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  9706. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  9707. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  9708. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  9709. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  9710. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  9711. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  9712. app.include_router(system.router, prefix=app_settings.api_prefix)
  9713. app.include_router(support.router, prefix=app_settings.api_prefix)
  9714. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  9715. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  9716. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  9717. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  9718. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  9719. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  9720. app.include_router(obico.router, prefix=app_settings.api_prefix)
  9721. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  9722. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  9723. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  9724. # Serve static files (React build)
  9725. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  9726. # Compressed, and cached for good where Vite hashed the name (#3175).
  9727. app.mount(
  9728. "/assets",
  9729. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  9730. name="assets",
  9731. )
  9732. if (app_settings.static_dir / "img").exists():
  9733. app.mount(
  9734. "/img",
  9735. StaticFiles(directory=app_settings.static_dir / "img"),
  9736. name="img",
  9737. )
  9738. if (app_settings.static_dir / "icons").exists():
  9739. app.mount(
  9740. "/icons",
  9741. StaticFiles(directory=app_settings.static_dir / "icons"),
  9742. name="icons",
  9743. )
  9744. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  9745. # falls through to the SPA catch-all and returns index.html, which the
  9746. # browser's font sanitizer rejects ("downloadable font: rejected by
  9747. # sanitizer").
  9748. if (app_settings.static_dir / "fonts").exists():
  9749. app.mount(
  9750. "/fonts",
  9751. StaticFiles(directory=app_settings.static_dir / "fonts"),
  9752. name="fonts",
  9753. )
  9754. @app.get("/")
  9755. async def serve_frontend():
  9756. """Serve the React frontend."""
  9757. index_file = app_settings.static_dir / "index.html"
  9758. if index_file.exists():
  9759. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  9760. return {
  9761. "message": "Bambuddy API",
  9762. "docs": "/docs",
  9763. "frontend": "Build and place React app in /static directory",
  9764. }
  9765. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  9766. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  9767. # forever, but the HTML wrapping it is the only file that knows which hash
  9768. # is current. Without explicit cache-control headers Chromium decides
  9769. # heuristically (typically 10% of the time since Last-Modified) and on
  9770. # long-running kiosks happily serves stale HTML across browser restarts.
  9771. # That stale HTML references an old bundle hash, the old bundle is also
  9772. # in the disk cache, and the user ends up running pre-update JS forever
  9773. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  9774. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  9775. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  9776. @app.get("/health")
  9777. async def health_check():
  9778. """Health check endpoint."""
  9779. return {"status": "healthy"}
  9780. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  9781. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  9782. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  9783. # in deployment debugging.
  9784. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  9785. async def serve_manifest():
  9786. """Serve PWA manifest."""
  9787. manifest_file = app_settings.static_dir / "manifest.json"
  9788. if manifest_file.exists():
  9789. return FileResponse(manifest_file, media_type="application/manifest+json")
  9790. return {"error": "Manifest not found"}
  9791. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  9792. async def serve_service_worker():
  9793. """Serve service worker."""
  9794. sw_file = app_settings.static_dir / "sw.js"
  9795. if sw_file.exists():
  9796. return FileResponse(
  9797. sw_file,
  9798. media_type="application/javascript",
  9799. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  9800. )
  9801. return {"error": "Service worker not found"}
  9802. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  9803. async def serve_sw_register():
  9804. """Serve the service-worker registration bootstrap script.
  9805. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  9806. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  9807. """
  9808. reg_file = app_settings.static_dir / "sw-register.js"
  9809. if reg_file.exists():
  9810. return FileResponse(reg_file, media_type="application/javascript")
  9811. return {"error": "sw-register.js not found"}
  9812. # ── GCode viewer static files ────────────────────────────────────────────────
  9813. # Catch-all route for React Router (must be last)
  9814. @app.get("/{full_path:path}")
  9815. async def serve_spa(full_path: str):
  9816. """Serve React app for client-side routing."""
  9817. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  9818. if full_path.startswith("api/"):
  9819. from fastapi import HTTPException
  9820. raise HTTPException(status_code=404, detail="Not found")
  9821. index_file = app_settings.static_dir / "index.html"
  9822. if index_file.exists():
  9823. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  9824. return {"error": "Frontend not built"}