main.py 437 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169
  1. import asyncio
  2. import json
  3. import logging
  4. import os
  5. import posixpath
  6. import secrets
  7. import time
  8. from contextlib import asynccontextmanager
  9. from datetime import datetime, timedelta, timezone
  10. from logging.handlers import RotatingFileHandler
  11. from pathlib import Path, PurePosixPath
  12. from urllib.parse import urlparse
  13. from fastapi import FastAPI
  14. from fastapi.responses import FileResponse
  15. from fastapi.staticfiles import StaticFiles
  16. from sqlalchemy import delete, or_, select, text
  17. from backend.app.api.routes import (
  18. ams_history,
  19. api_keys,
  20. archive_purge,
  21. archives,
  22. auth,
  23. bug_report,
  24. camera,
  25. camwall,
  26. cloud,
  27. discovery,
  28. external_links,
  29. filaments,
  30. finance,
  31. firmware,
  32. github_backup,
  33. groups,
  34. ha_sensors,
  35. inventory,
  36. kprofiles,
  37. labels,
  38. library,
  39. library_tags,
  40. library_trash,
  41. library_variants,
  42. local_backup,
  43. local_presets,
  44. maintenance,
  45. makerworld,
  46. metrics,
  47. mfa,
  48. notification_templates,
  49. notifications,
  50. obico,
  51. orca_cloud,
  52. pending_uploads,
  53. pipeline_runs,
  54. print_log,
  55. print_queue,
  56. printer_sensor_history,
  57. printers,
  58. projects,
  59. scheduled_dryings,
  60. settings as settings_routes,
  61. slice_jobs,
  62. slicer_pipelines,
  63. slicer_presets,
  64. smart_plugs,
  65. sponsor_prompt,
  66. spoolbuddy,
  67. spoolman,
  68. spoolman_inventory,
  69. support,
  70. system,
  71. updates,
  72. user_notifications,
  73. users,
  74. virtual_printers,
  75. webhook,
  76. websocket,
  77. )
  78. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  79. from backend.app.api.routes.support import init_debug_logging
  80. from backend.app.core.config import APP_VERSION, settings as app_settings
  81. from backend.app.core.database import async_session, engine, init_db
  82. from backend.app.core.tasks import spawn_background_task
  83. from backend.app.core.websocket import ws_manager
  84. from backend.app.services import print_dispatch_context
  85. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  86. from backend.app.services.archive_purge import archive_purge_service
  87. from backend.app.services.bambu_ftp import (
  88. FileNotOnPrinterError,
  89. cache_3mf_download,
  90. clear_3mf_cache,
  91. download_file_async,
  92. download_file_try_paths_async,
  93. ftps_handshake_blocked,
  94. get_cached_3mf,
  95. get_ftp_retry_settings,
  96. with_ftp_retry,
  97. )
  98. from backend.app.services.bambu_mqtt import PrinterState
  99. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  100. from backend.app.services.github_backup import github_backup_service
  101. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  102. from backend.app.services.homeassistant import homeassistant_service
  103. from backend.app.services.library_trash import library_trash_service
  104. from backend.app.services.local_backup import local_backup_service
  105. from backend.app.services.mqtt_relay import mqtt_relay
  106. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  107. from backend.app.services.notification_service import notification_service
  108. from backend.app.services.obico_detection import obico_detection_service
  109. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  110. from backend.app.services.print_scheduler import scheduler as print_scheduler
  111. from backend.app.services.print_storage import (
  112. external_storage_present,
  113. ftp_probe_paths,
  114. print_file_reachable_over_ftp,
  115. )
  116. from backend.app.services.printer_manager import (
  117. init_printer_connections,
  118. parse_plate_id,
  119. printer_manager,
  120. printer_state_to_dict,
  121. resolve_plate_id,
  122. )
  123. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  124. from backend.app.services.smart_plug_manager import smart_plug_manager
  125. from backend.app.services.spool_assignment_notifications import (
  126. notify_missing_spool_assignments_on_print_start,
  127. )
  128. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  129. from backend.app.services.spoolman_tracking import (
  130. cleanup_tracking as _cleanup_spoolman_tracking,
  131. report_usage as _report_spoolman_usage,
  132. store_print_data as _store_spoolman_print_data,
  133. )
  134. from backend.app.services.tasmota import tasmota_service
  135. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  136. from backend.app.utils.fts_routing import extruder_for_inlet, slot_extruder as resolve_slot_extruder
  137. from backend.app.utils.local_time import utcnow_naive
  138. from backend.app.utils.print_jobs import is_internal_printer_job
  139. # =============================================================================
  140. # Dependency Check - runs before other imports to give helpful error messages
  141. # =============================================================================
  142. def _start_error_server(missing_packages: list):
  143. """Start a minimal HTTP server to display dependency errors in browser."""
  144. import os
  145. import signal
  146. from http.server import BaseHTTPRequestHandler, HTTPServer
  147. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  148. html = f"""<!DOCTYPE html>
  149. <html>
  150. <head>
  151. <title>Bambuddy - Setup Required</title>
  152. <style>
  153. body {{
  154. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  155. background: #0f172a; color: #e2e8f0;
  156. display: flex; justify-content: center; align-items: center;
  157. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  158. }}
  159. .container {{
  160. background: #1e293b; border-radius: 12px; padding: 40px;
  161. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  162. }}
  163. h1 {{ color: #f87171; margin-bottom: 10px; }}
  164. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  165. .packages {{
  166. background: #0f172a; border-radius: 8px; padding: 20px;
  167. margin: 20px 0; text-align: left;
  168. }}
  169. .packages ul {{ margin: 0; padding-left: 20px; }}
  170. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  171. .command {{
  172. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  173. margin: 15px 0; font-family: monospace; color: #4ade80;
  174. text-align: left; overflow-x: auto;
  175. }}
  176. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  177. </style>
  178. </head>
  179. <body>
  180. <div class="container">
  181. <h1>Setup Required</h1>
  182. <h2>Missing Python packages</h2>
  183. <div class="packages"><ul>{packages_html}</ul></div>
  184. <p>To fix, run this command on your server:</p>
  185. <div class="command">pip install -r requirements.txt</div>
  186. <p>Or if using a virtual environment:</p>
  187. <div class="command">./venv/bin/pip install -r requirements.txt</div>
  188. <p class="note">After installing, restart Bambuddy:<br>
  189. <code>sudo systemctl restart bambuddy</code></p>
  190. </div>
  191. </body>
  192. </html>"""
  193. class ErrorHandler(BaseHTTPRequestHandler):
  194. def do_GET(self):
  195. self.send_response(503)
  196. self.send_header("Content-type", "text/html")
  197. self.end_headers()
  198. self.wfile.write(html.encode())
  199. def log_message(self, format, *args):
  200. print(f"[Error Server] {args[0]}")
  201. port = int(os.environ.get("PORT", 8000))
  202. print(f"\nStarting error server on http://0.0.0.0:{port}")
  203. print("Visit this URL in your browser to see the error details.\n")
  204. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  205. def shutdown(signum, frame):
  206. print("\nShutting down error server...")
  207. raise SystemExit(0)
  208. signal.signal(signal.SIGTERM, shutdown)
  209. signal.signal(signal.SIGINT, shutdown)
  210. server.serve_forever()
  211. def check_dependencies():
  212. """Check that all required packages are installed."""
  213. missing = []
  214. # Map of import name -> package name (for pip install)
  215. required = {
  216. "jwt": "PyJWT",
  217. "fastapi": "fastapi",
  218. "uvicorn": "uvicorn",
  219. "sqlalchemy": "sqlalchemy",
  220. "aiosqlite": "aiosqlite",
  221. "pydantic": "pydantic",
  222. "paho.mqtt": "paho-mqtt",
  223. }
  224. for module, package in required.items():
  225. try:
  226. __import__(module)
  227. except ImportError:
  228. missing.append(package)
  229. if missing:
  230. print("\n" + "=" * 60)
  231. print("ERROR: Missing required Python packages!")
  232. print("=" * 60)
  233. print(f"\nMissing packages: {', '.join(missing)}")
  234. print("\nTo fix, run:")
  235. print(" pip install -r requirements.txt")
  236. print("\nOr if using a virtual environment:")
  237. print(" ./venv/bin/pip install -r requirements.txt")
  238. print("=" * 60 + "\n")
  239. _start_error_server(missing)
  240. check_dependencies()
  241. # =============================================================================
  242. # Import settings first for logging configuration
  243. # Configure logging based on settings
  244. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  245. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  246. log_level = getattr(logging, log_level_str, logging.INFO)
  247. # Trace ID column ([-] when no request scope is active — startup, MQTT
  248. # callbacks, scheduled tasks not chained from a request — so the column
  249. # stays visually aligned and missing values are obvious in grep). See
  250. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  251. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  252. # Create root logger
  253. root_logger = logging.getLogger()
  254. root_logger.setLevel(log_level)
  255. # Trace-ID injection: this filter populates record.trace_id from the
  256. # per-request ContextVar so the format string above can reference it.
  257. # Attached to each HANDLER (not the root logger) because Python's
  258. # logging semantics only invoke a logger's filters on records that
  259. # *originated* at that logger — records propagated up from child
  260. # loggers (every named logger in the app) never trigger root's filter.
  261. # Putting it on the handlers means every record any handler emits gets
  262. # trace_id injected just before the formatter runs, regardless of which
  263. # logger created the record. Without this, the formatter raises
  264. # KeyError on every child-logger record and the record is silently
  265. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  266. # partially" bug we hit. See backend/app/core/trace.py for the
  267. # ContextVar the filter reads.
  268. from backend.app.core.trace import TraceIDFilter
  269. _trace_id_filter = TraceIDFilter()
  270. # Console handler - always enabled
  271. console_handler = logging.StreamHandler()
  272. console_handler.setLevel(log_level)
  273. console_handler.setFormatter(logging.Formatter(log_format))
  274. console_handler.addFilter(_trace_id_filter)
  275. root_logger.addHandler(console_handler)
  276. # File handler - only in production or if explicitly enabled
  277. if app_settings.log_to_file:
  278. log_file = app_settings.log_dir / "bambuddy.log"
  279. file_handler = RotatingFileHandler(
  280. log_file,
  281. maxBytes=app_settings.log_max_bytes,
  282. backupCount=app_settings.log_backup_count,
  283. encoding="utf-8",
  284. )
  285. file_handler.setLevel(log_level)
  286. file_handler.setFormatter(logging.Formatter(log_format))
  287. file_handler.addFilter(_trace_id_filter)
  288. root_logger.addHandler(file_handler)
  289. logging.info("Logging to file: %s", log_file)
  290. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  291. # access logger with propagate=False by default, so without this attach
  292. # there is no on-disk record of which endpoint triggered a server-state
  293. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  294. # for exactly this reason. Filtered to write methods only
  295. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  296. # frontend don't churn the rotation window faster than it's useful.
  297. from backend.app.core.logging_filters import (
  298. CancelledPoolNoiseFilter,
  299. WriteRequestsOnlyFilter,
  300. )
  301. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  302. uvicorn_access_logger.addHandler(file_handler)
  303. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  304. # Uvicorn's access logger has propagate=False (its own default), so the
  305. # root-attached TraceIDFilter never sees these records. Attach a
  306. # second instance directly so HTTP access lines carry the same trace
  307. # ID column as the application logs they correlate with.
  308. uvicorn_access_logger.addFilter(TraceIDFilter())
  309. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  310. # BaseHTTPMiddleware cancelling the inner task scope on client
  311. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  312. # underlying transaction leak; this filter only suppresses the residual
  313. # log records that pre-existing pools still emit during their cleanup.
  314. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  315. # Reduce noise from third-party libraries in production
  316. if not app_settings.debug:
  317. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  318. logging.getLogger("httpcore").setLevel(logging.WARNING)
  319. logging.getLogger("httpx").setLevel(logging.WARNING)
  320. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  321. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  322. # Track active prints: {(printer_id, filename): archive_id}
  323. _active_prints: dict[tuple[int, str], int] = {}
  324. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  325. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  326. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  327. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  328. # instead of running its own grab-now chain when present, so the finish photo
  329. # captures the better-framed pre-bed-drop moment without us having to force
  330. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  331. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  332. #
  333. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  334. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  335. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  336. # bank and the others are not — so the consumer can't tell them apart and
  337. # must not rotate again.
  338. _stage22_finish_frames: dict[int, bytes] = {}
  339. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  340. # `finally` block (whether it captured a frame or not). The consumer in
  341. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  342. # so the FINISH-state fallback path — where moment and completion are dispatched
  343. # back-to-back — doesn't race past the producer with an empty pop, and the
  344. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  345. # grab (Bambu printers allow only one RTSP client at a time).
  346. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  347. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  348. # layer-change and on print-progress advances (#2547) while the model is still
  349. # printing, then consumed by the FINISH-state finish-photo path when the
  350. # dispatcher recorded that it injected End G-code into this print. Bambu
  351. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  352. # plate-swap) has run, so a live grab there would capture the swapped/empty
  353. # plate.
  354. #
  355. # The load-bearing property: both drivers are print telemetry that stops before
  356. # the End G-code executes — no further layer_num increases, and mc_percent
  357. # freezes — so the last banked frame is always the finished print before the
  358. # swap. Anything added as a third driver must hold that same property.
  359. _inprint_frame_bank: dict[int, bytes] = {}
  360. # Monotonic timestamp of the last banked frame per printer — throttles banking
  361. # so tall prints don't add a camera grab on every layer.
  362. _inprint_frame_bank_ts: dict[int, float] = {}
  363. # Minimum seconds between banked frames, except the final object layer which
  364. # always refreshes for the best framing.
  365. _INPRINT_BANK_MIN_INTERVAL = 25.0
  366. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  367. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  368. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  369. # the first connected status update for that connection; transitions back
  370. # to False whenever we observe `state.connected = False` so the next
  371. # reconnect re-arms reconciliation. Keyed by printer_id.
  372. _printer_reconciled_since_connect: dict[int, bool] = {}
  373. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  374. # {(printer_id, filename): archive_id}
  375. _expected_prints: dict[tuple[int, str], int] = {}
  376. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  377. # Used by usage tracker to map 3MF slots to physical AMS trays
  378. _print_ams_mappings: dict[int, list[int]] = {}
  379. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  380. _print_cost_center_ids: dict[int, int] = {}
  381. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  382. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  383. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  384. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  385. # for the queue path. Cleared on print completion or TTL eviction.
  386. _print_plate_ids: dict[int, int] = {}
  387. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  388. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  389. _last_progress_milestone: dict[int, int] = {}
  390. # Track whether first layer complete notification has been sent for current print
  391. _first_layer_notified: dict[int, bool] = {}
  392. # Track whether we already sent a kill-switch stop for the current unauthorized print
  393. _unauthorized_print_kill_sent: set[int] = set()
  394. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  395. # lookup briefly so an unknown active print does not query the database on
  396. # every status frame. A short TTL keeps settings changes responsive.
  397. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  398. _kill_switch_setting_cache: tuple[bool, float] | None = None
  399. # Provider notification started when the kill switch stops a print. The later
  400. # MQTT print-complete callback awaits this task and only sends its regular
  401. # provider notification when the immediate attempt failed.
  402. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  403. # Track HMS errors that have been notified: {printer_id: set of error codes}
  404. # This prevents sending duplicate notifications for the same error
  405. _notified_hms_errors: dict[int, set[str]] = {}
  406. # Track when HMS errors were last seen: {printer_id: timestamp}
  407. # Used to debounce clearing — prevents flapping errors from re-triggering notifications
  408. _hms_last_seen: dict[int, float] = {}
  409. _HMS_CLEAR_GRACE_SECONDS = 30.0
  410. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  411. # Used for snapshot-diff detection at print completion
  412. _timelapse_baselines: dict[int, set[str]] = {}
  413. # Track printers waiting for bed to cool after print completion.
  414. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  415. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  416. _bed_cool_waiters: dict[int, dict] = {}
  417. # Track printers where the user explicitly stopped the print from the queue UI.
  418. # When on_print_complete fires with status "failed" for these printers we treat it
  419. # as "cancelled" (stopped by user) so the correct notification email is sent.
  420. _user_stopped_printers: set[int] = set()
  421. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  422. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  423. # holds the previous observation so we only fire on the True → False edge (a
  424. # False → False repeat doesn't notify; an initial False at startup doesn't
  425. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  426. # holds the per-printer pending asyncio task that fires the notification
  427. # after a debounce window — cancelled if the printer reconnects before the
  428. # window elapses, so transient MQTT blips don't flood the user.
  429. _printer_last_connected: dict[int, bool] = {}
  430. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  431. # Debounce: a printer must stay offline this long before we notify. Sized
  432. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  433. # so a single stale-trigger cooldown isn't enough to fire — only a real
  434. # offline that survives one reconnect attempt notifies.
  435. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  436. # HMS short-code → human-readable failure reason. Used by _dispatch_archive_update
  437. # when status="failed" to label the print's failure_reason in archives.
  438. #
  439. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  440. # which is wrong on two counts:
  441. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  442. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  443. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  444. # the public wiki) as part of its user-cancel sequence. Matching on the module
  445. # alone caused user-cancellations to be archived as "Layer shift" failures.
  446. # We now match by full short code only — anything not in this map leaves
  447. # failure_reason=None rather than guessing.
  448. _HMS_FAILURE_REASONS: dict[str, str] = {
  449. # Layer shift / step loss
  450. "0300_4057": "Layer shift",
  451. "0300_4068": "Layer shift",
  452. "0300_800C": "Layer shift",
  453. # Filament runout (printer-side & per-AMS-slot)
  454. "0300_8004": "Filament runout",
  455. "0700_8011": "Filament runout",
  456. "0701_8011": "Filament runout",
  457. "0702_8011": "Filament runout",
  458. "0703_8011": "Filament runout",
  459. "0704_8011": "Filament runout",
  460. "0705_8011": "Filament runout",
  461. "0706_8011": "Filament runout",
  462. "0707_8011": "Filament runout",
  463. "07FF_8011": "Filament runout",
  464. # Clogged nozzle / extruder
  465. "0300_4006": "Clogged nozzle",
  466. "0300_8016": "Clogged nozzle",
  467. "0300_801C": "Clogged nozzle",
  468. "0700_8003": "Clogged nozzle",
  469. "0700_8007": "Clogged nozzle",
  470. "0700_8013": "Clogged nozzle",
  471. "0701_8003": "Clogged nozzle",
  472. "0701_8007": "Clogged nozzle",
  473. "0701_8013": "Clogged nozzle",
  474. "0702_8003": "Clogged nozzle",
  475. }
  476. def _hms_short_code(attr: int, code: int | str) -> str:
  477. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  478. if isinstance(code, str):
  479. code_int = int(code.replace("0x", ""), 16) if code else 0
  480. else:
  481. code_int = int(code or 0)
  482. attr_int = int(attr or 0)
  483. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  484. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  485. """Derive a human-readable failure_reason for an archived print.
  486. Returns "User cancelled" for cancelled/aborted prints; for failed prints,
  487. returns the first matching reason from _HMS_FAILURE_REASONS, or None when
  488. no HMS code matches (don't guess — null is honest).
  489. """
  490. if status in ("aborted", "cancelled"):
  491. return "User cancelled"
  492. if status != "failed":
  493. return None
  494. for err in hms_errors or []:
  495. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  496. if short_code in _HMS_FAILURE_REASONS:
  497. return _HMS_FAILURE_REASONS[short_code]
  498. return None
  499. # Track created_by_id for expected prints so the user email can be sent even when
  500. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  501. # {(printer_id, filename): created_by_id}
  502. _expected_print_creators: dict[tuple[int, str], int] = {}
  503. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  504. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  505. # updates for the same printer in quick succession (~30 ms apart, observed in
  506. # the wild on H2D + dual AMS).
  507. #
  508. # Without this serialisation, two concurrent on_ams_change callbacks each read
  509. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  510. # the second commit hits
  511. # IntegrityError: duplicate key value violates unique constraint
  512. # "spool_assignment_printer_id_ams_id_tray_id_key"
  513. # SQLite's WAL serial-write semantics had been silently swallowing the race
  514. # until optional Postgres support landed (asyncpg allows true concurrent
  515. # transactions and surfaces the constraint violation).
  516. #
  517. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  518. # assign) are inside the lock. The Spoolman sync block further down stays
  519. # concurrent because it's network-bound and idempotent.
  520. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  521. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  522. """Return the per-printer assignment lock, creating it on first use."""
  523. lock = _ams_assignment_locks.get(printer_id)
  524. if lock is None:
  525. lock = asyncio.Lock()
  526. _ams_assignment_locks[printer_id] = lock
  527. return lock
  528. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  529. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  530. # tag tuple changes for the slot. Cleared when the slot is reported empty
  531. # so remove + reinsert reliably re-prompts the UI.
  532. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  533. async def _broadcast_unknown_tag(
  534. *,
  535. printer_id: int,
  536. ams_id: int,
  537. tray_id: int,
  538. tag_uid: str,
  539. tray_uuid: str,
  540. tray_type: str | None = None,
  541. tray_color: str | None = None,
  542. tray_sub_brands: str | None = None,
  543. tray_count: int | None = None,
  544. ) -> None:
  545. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  546. _logger = logging.getLogger(__name__)
  547. slot_key = (ams_id, tray_id)
  548. tag_key = (tag_uid or "", tray_uuid or "")
  549. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  550. if per_printer.get(slot_key) == tag_key:
  551. _logger.debug(
  552. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  553. printer_id,
  554. ams_id,
  555. tray_id,
  556. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  557. )
  558. return
  559. _logger.info(
  560. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  561. printer_id,
  562. ams_id,
  563. tray_id,
  564. tray_type,
  565. tray_color,
  566. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  567. )
  568. # Broadcast first; only commit the dedup if the WS write succeeds.
  569. # If broadcast raises, the next MQTT push retries instead of being
  570. # permanently silenced by a poisoned dedup entry.
  571. await ws_manager.broadcast(
  572. {
  573. "type": "unknown_tag",
  574. "printer_id": printer_id,
  575. "ams_id": ams_id,
  576. "tray_id": tray_id,
  577. "tag_uid": tag_uid,
  578. "tray_uuid": tray_uuid,
  579. "tray_type": tray_type,
  580. "tray_color": tray_color,
  581. "tray_sub_brands": tray_sub_brands,
  582. "tray_count": tray_count,
  583. }
  584. )
  585. per_printer[slot_key] = tag_key
  586. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  587. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  588. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  589. if per_printer is None:
  590. return
  591. per_printer.pop((ams_id, tray_id), None)
  592. # TTL for expected-print entries: evict registrations older than this to prevent
  593. # unbounded growth when a print is registered but never starts (e.g. printer
  594. # disconnect, app restart, print started from the printer panel).
  595. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  596. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  597. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  598. # Cleanup loop interval
  599. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  600. _expected_prints_cleanup_task: asyncio.Task | None = None
  601. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  602. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  603. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  604. possible_keys: list[tuple[int, str]] = []
  605. filename = (state.gcode_file or state.current_print or "").strip()
  606. subtask_name = (state.subtask_name or "").strip()
  607. if subtask_name:
  608. possible_keys.append((printer_id, subtask_name))
  609. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  610. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  611. if filename:
  612. base_name = filename.rsplit("/", 1)[-1]
  613. if base_name.endswith(".gcode.3mf"):
  614. root_name = base_name[: -len(".gcode.3mf")]
  615. possible_keys.append((printer_id, root_name))
  616. possible_keys.append((printer_id, base_name))
  617. possible_keys.append((printer_id, f"{root_name}.gcode"))
  618. possible_keys.append((printer_id, f"{root_name}.3mf"))
  619. elif base_name.endswith(".3mf"):
  620. root_name = base_name[: -len(".3mf")]
  621. possible_keys.append((printer_id, root_name))
  622. possible_keys.append((printer_id, base_name))
  623. elif base_name.endswith(".gcode"):
  624. root_name = base_name[: -len(".gcode")]
  625. possible_keys.append((printer_id, root_name))
  626. possible_keys.append((printer_id, f"{root_name}.3mf"))
  627. possible_keys.append((printer_id, base_name))
  628. else:
  629. possible_keys.append((printer_id, base_name))
  630. possible_keys.append((printer_id, f"{base_name}.3mf"))
  631. return possible_keys
  632. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  633. """Check the cheap, process-local print ownership signals."""
  634. if printer_manager.get_current_print_user(printer_id):
  635. return True
  636. return any(key in _expected_prints or key in _active_prints for key in _build_status_print_keys(printer_id, state))
  637. async def _is_printer_kill_switch_enabled_cached() -> bool:
  638. """Return the kill-switch setting without querying on every MQTT frame."""
  639. global _kill_switch_setting_cache
  640. now = time.monotonic()
  641. if _kill_switch_setting_cache is not None:
  642. enabled, expires_at = _kill_switch_setting_cache
  643. if now < expires_at:
  644. return enabled
  645. async with async_session() as db:
  646. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  647. enabled = await is_printer_kill_switch_enabled(db)
  648. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  649. return enabled
  650. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  651. """Resolve whether the current print was started by Bambuddy.
  652. ``None`` means identity is not yet safe to decide. The kill switch must
  653. defer in that case: stopping a print is irreversible, and the first status
  654. frames after a restart may arrive before all subtask fields are populated.
  655. """
  656. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  657. return True
  658. possible_keys = _build_status_print_keys(printer_id, state)
  659. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  660. # is on disk. subtask_id is minted per print and pins the answer to the job
  661. # actually running, rather than to an unrelated one that reuses a filename.
  662. raw_subtask_id = getattr(state, "subtask_id", None)
  663. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  664. if subtask_id in ("", "0"):
  665. return None
  666. from backend.app.models.archive import PrintArchive
  667. result = await db.execute(
  668. select(PrintArchive)
  669. .where(
  670. PrintArchive.printer_id == printer_id,
  671. PrintArchive.status == "printing",
  672. PrintArchive.subtask_id == subtask_id,
  673. )
  674. .order_by(PrintArchive.created_at.desc())
  675. .limit(1)
  676. )
  677. archive = result.scalar_one_or_none()
  678. # An archive row on its own proves nothing: `on_print_start` archives every
  679. # print it observes, including ones started from Bambu Studio or Handy, and
  680. # stamps them with the same status and subtask_id. Authorizing on its mere
  681. # existence would disable the kill switch the moment the 3MF finishes
  682. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  683. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  684. # (carried over from the queue item that started it).
  685. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  686. # Rehydrate the fast in-memory path for subsequent status frames. Include
  687. # both the archive filename and every normalized key reported by MQTT.
  688. _active_prints[(printer_id, archive.filename)] = archive.id
  689. for key in possible_keys:
  690. _active_prints[key] = archive.id
  691. return True
  692. # No dispatch marker. Before calling this someone else's print, check whether
  693. # Bambuddy has a job of its own running on this printer: a library-file
  694. # dispatch has no archive at send time, and an archive created seconds later
  695. # by `on_print_start` carries neither marker. The queue row, which the
  696. # scheduler commits to status="printing" before the MQTT send, is the one
  697. # durable record every Bambuddy print has. It cannot be tied to this
  698. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  699. # print is irreversible, and refusing to act costs nothing but a log line.
  700. from backend.app.models.print_queue import PrintQueueItem
  701. dispatched_here = await db.scalar(
  702. select(PrintQueueItem.id)
  703. .where(
  704. PrintQueueItem.printer_id == printer_id,
  705. PrintQueueItem.status == "printing",
  706. )
  707. .limit(1)
  708. )
  709. if dispatched_here is not None:
  710. return None
  711. return False
  712. async def _send_kill_switch_provider_notification(
  713. printer_id: int,
  714. printer_name: str,
  715. data: dict,
  716. ) -> bool:
  717. """Send the immediate print-stopped provider notification.
  718. Returning a success flag lets the normal MQTT completion path retry when
  719. this early notification could not be delivered.
  720. """
  721. logger = logging.getLogger(__name__)
  722. try:
  723. async with async_session() as db:
  724. await notification_service.on_print_complete(
  725. printer_id,
  726. printer_name,
  727. "stopped",
  728. data,
  729. db,
  730. )
  731. return True
  732. except Exception as e:
  733. logger.warning(
  734. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  735. printer_id,
  736. e,
  737. )
  738. return False
  739. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  740. """Wait for an immediate kill-switch notification, if one was scheduled."""
  741. if task is None:
  742. return False
  743. try:
  744. return await task
  745. except Exception as e:
  746. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  747. return False
  748. async def _get_plug_energy(plug, db) -> dict | None:
  749. """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
  750. For HA plugs, configures the service with current settings from DB.
  751. For MQTT plugs, returns data from the subscription service.
  752. For REST plugs, polls the status URL with JSON path extraction.
  753. """
  754. if plug.plug_type == "homeassistant":
  755. from backend.app.api.routes.settings import get_homeassistant_settings
  756. ha_settings = await get_homeassistant_settings(db)
  757. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  758. return await homeassistant_service.get_energy(plug)
  759. elif plug.plug_type == "mqtt":
  760. # MQTT plugs report "today" energy, not lifetime total
  761. # For per-print tracking, we use "today" as the counter (resets at midnight)
  762. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  763. if mqtt_data:
  764. return {
  765. "power": mqtt_data.power,
  766. "today": mqtt_data.energy,
  767. "total": mqtt_data.energy, # Use today as total for per-print calculations
  768. }
  769. return None
  770. elif plug.plug_type == "rest":
  771. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  772. return await rest_smart_plug_service.get_energy(plug)
  773. else:
  774. return await tasmota_service.get_energy(plug)
  775. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  776. """Capture the smart plug lifetime counter on the archive at print start.
  777. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  778. tracking survives a backend restart mid-print. The print-end handler reads
  779. this value back from the DB and computes the delta against the current
  780. plug counter.
  781. """
  782. _logger = logging.getLogger(__name__)
  783. try:
  784. candidates = await energy_plug_candidates(db, printer_id)
  785. if not candidates:
  786. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  787. return False
  788. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  789. if selected is None:
  790. # Naming the plugs matters here: with several linked to one printer
  791. # this is the difference between "the meter is offline" and "you
  792. # linked only accessories" (#2859).
  793. _logger.warning(
  794. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  795. printer_id,
  796. archive.id,
  797. ", ".join(plug.name for plug in candidates),
  798. )
  799. return False
  800. plug, energy = selected
  801. archive.energy_start_kwh = float(energy["total"])
  802. await db.commit()
  803. _logger.info(
  804. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  805. f" ({context})" if context else "",
  806. archive.id,
  807. plug.name,
  808. energy["total"],
  809. )
  810. return True
  811. except Exception as e:
  812. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  813. return False
  814. def register_expected_print(
  815. printer_id: int,
  816. filename: str,
  817. archive_id: int,
  818. ams_mapping: list[int] | None = None,
  819. created_by_id: int | None = None,
  820. cost_center_id: int | None = None,
  821. plate_id: int | None = None,
  822. ):
  823. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  824. # Store with multiple filename variations to catch different naming patterns
  825. _expected_prints[(printer_id, filename)] = archive_id
  826. # Also store without .3mf extension if present
  827. if filename.endswith(".3mf"):
  828. base = filename[:-4]
  829. _expected_prints[(printer_id, base)] = archive_id
  830. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  831. # Store AMS mapping for usage tracking at print completion
  832. if ams_mapping is not None:
  833. _print_ams_mappings[archive_id] = ams_mapping
  834. if cost_center_id is not None:
  835. _print_cost_center_ids[archive_id] = cost_center_id
  836. # Store plate_id for usage tracking when this is a single-plate dispatch from
  837. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  838. # file's filament total to the spool instead of just the printed plate (#1697).
  839. if plate_id is not None:
  840. _print_plate_ids[archive_id] = plate_id
  841. # Store created_by_id so the user start email can be sent even when the archive
  842. # itself has no created_by_id (e.g. library-file-based queue prints)
  843. if created_by_id is not None:
  844. _expected_print_creators[(printer_id, filename)] = created_by_id
  845. if filename.endswith(".3mf"):
  846. base = filename[:-4]
  847. _expected_print_creators[(printer_id, base)] = created_by_id
  848. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  849. # Record registration time for TTL-based eviction
  850. _registered_at = time.monotonic()
  851. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  852. if filename.endswith(".3mf"):
  853. base = filename[:-4]
  854. _expected_print_registered_at[(printer_id, base)] = _registered_at
  855. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  856. logging.getLogger(__name__).info(
  857. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  858. )
  859. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  860. """Undo :func:`register_expected_print` when the print never went out.
  861. Registration has to happen *before* the MQTT print command, because the
  862. printer can report the print before the line after the send executes. So
  863. every path that registers and then fails to send — a cancel winning the
  864. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  865. between — leaves an expectation for a print that will never arrive.
  866. The TTL sweep evicts those after two hours, which is far longer than it
  867. takes a user to react to a failed dispatch by pressing print again: that
  868. reprint would be folded into the *old* archive and take the stale
  869. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  870. Mirrors the sweep's rules, including the one that is easy to get wrong:
  871. ``_print_ams_mappings`` / ``_print_plate_ids`` are keyed by archive, not by
  872. file, so they may only be dropped once no live key still points at that
  873. archive.
  874. """
  875. keys = [(printer_id, filename)]
  876. if filename.endswith(".3mf"):
  877. base = filename[:-4]
  878. keys.append((printer_id, base))
  879. keys.append((printer_id, f"{base}.gcode"))
  880. removed = False
  881. for key in keys:
  882. if _expected_prints.pop(key, None) is not None:
  883. removed = True
  884. _expected_print_creators.pop(key, None)
  885. _expected_print_registered_at.pop(key, None)
  886. if archive_id not in set(_expected_prints.values()):
  887. _print_ams_mappings.pop(archive_id, None)
  888. _print_plate_ids.pop(archive_id, None)
  889. if removed:
  890. logging.getLogger(__name__).info(
  891. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  892. printer_id,
  893. filename,
  894. archive_id,
  895. )
  896. def _compute_run_filament_grams(
  897. status: str,
  898. archive_filament_used_grams: float | None,
  899. progress: float | int | None,
  900. usage_results: list[dict] | None,
  901. ) -> float | None:
  902. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  903. Priority for every status:
  904. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  905. weight delta — same source that drives "Total Consumed" on the
  906. Inventory page, so Stats and Inventory totals stay aligned).
  907. 2. For ``completed``: the slicer estimate (no tracker available, fall
  908. back to the canonical "this print used X" value).
  909. 3. For partial statuses: ``estimate * progress%``.
  910. 4. ``None`` if nothing is known.
  911. """
  912. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  913. if tracked_grams > 0:
  914. return round(tracked_grams, 1)
  915. if status == "completed":
  916. return archive_filament_used_grams
  917. if archive_filament_used_grams:
  918. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  919. if scale > 0:
  920. return round(archive_filament_used_grams * scale, 1)
  921. return None
  922. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  923. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  924. stored_ams_mapping = data.get("ams_mapping")
  925. if not stored_ams_mapping and archive_id:
  926. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  927. return stored_ams_mapping
  928. def _get_start_plate_id(archive_id: int | None) -> int | None:
  929. """Resolve plate_id for print start without consuming stored direct-Print state.
  930. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  931. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  932. read it back at print-start without popping (the entry is popped on print
  933. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  934. """
  935. if archive_id is None:
  936. return None
  937. return _print_plate_ids.get(archive_id)
  938. def _partial_progress_scale(progress: int | float | None) -> float:
  939. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  940. Used by every site that multiplies a "would-have-used" slicer estimate
  941. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  942. so the three sites in ``_background_notifications`` (and the per-plate
  943. override helper) can't drift apart on the coercion shape.
  944. """
  945. return max(0.0, min((progress or 0) / 100.0, 1.0))
  946. def _scope_notification_archive_data_to_plate(
  947. archive_data: dict,
  948. archive_file_path: str | None,
  949. plate_id: int | None,
  950. print_status: str,
  951. progress: int | float | None,
  952. base_dir: Path,
  953. ) -> dict:
  954. """Override summed-across-plates totals in ``archive_data`` with the values
  955. for ``plate_id`` so the completion notification reports what was actually
  956. printed, not the whole project (#1785).
  957. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  958. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  959. the archive card's "whole project" headline, wrong for the completion
  960. notification of a single-plate print. The queue UI already re-reads the
  961. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  962. notification payload (filament grams, time estimate, per-slot breakdown).
  963. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  964. no per-plate values — in every fail case the original ``archive_data`` is
  965. returned unchanged so the notification still sends.
  966. """
  967. if plate_id is None or not archive_file_path:
  968. return archive_data
  969. from backend.app.utils.threemf_tools import (
  970. extract_filament_usage_from_3mf,
  971. extract_print_time_from_3mf,
  972. )
  973. archive_path = base_dir / archive_file_path
  974. if not archive_path.exists():
  975. return archive_data
  976. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  977. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  978. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  979. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  980. if plate_time:
  981. archive_data["print_time_seconds"] = plate_time
  982. # Gate both the grams headline AND the per-slot breakdown on the same
  983. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  984. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  985. # to the project-level grams the archive columns already provide rather
  986. # than ship a project-level headline next to an all-zero per-plate
  987. # breakdown.
  988. if plate_grams > 0:
  989. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  990. archive_data["filament_slots"] = [
  991. {
  992. "slot_id": s.get("slot_id"),
  993. "used_g": round((s.get("used_g") or 0) * scale, 1),
  994. "type": s.get("type", ""),
  995. "color": s.get("color", ""),
  996. }
  997. for s in plate_slots
  998. ]
  999. return archive_data
  1000. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1001. """Best-effort filament metadata from the MQTT print-start snapshot.
  1002. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1003. file during print, see #1533) so the fallback PrintArchive still has
  1004. enough filament info to support the inventory views and AMS-expansion
  1005. planning the operator opens it for. Returns a dict with optional
  1006. ``filament_type`` and ``filament_color`` keys in the same
  1007. comma-separated format the 3MF extractor produces, so the rest of the
  1008. codebase treats the fallback archive identically to a normal one.
  1009. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1010. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1011. entries). When supplied, only the slots actually consumed by this
  1012. print contribute. Without it the function falls back to every loaded
  1013. AMS slot — less accurate but still useful.
  1014. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1015. that the unit tests pass directly, AND the on_print_start callback
  1016. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1017. bambu_mqtt service hands to main.py at runtime. The original
  1018. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1019. handled the inner shape and silently returned ``{}`` for every real
  1020. print start, leaving fallback archives' filament fields NULL — the
  1021. exact regression the fix was meant to close. Reported with a log
  1022. proving the AMS state was right there at
  1023. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1024. """
  1025. result: dict[str, str] = {}
  1026. # Look at the on_print_start wrapper first, then the inner shape.
  1027. raw_data = (data or {}).get("raw_data")
  1028. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1029. if not isinstance(ams_root, dict):
  1030. ams_root = (data or {}).get("ams") or {}
  1031. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1032. if not isinstance(ams_units, list) or not ams_units:
  1033. return result
  1034. # Map global tray id (unit * 4 + tray) → (type, color).
  1035. loaded: dict[int, tuple[str, str]] = {}
  1036. for unit in ams_units:
  1037. if not isinstance(unit, dict):
  1038. continue
  1039. try:
  1040. unit_id = int(unit.get("id", 0))
  1041. except (TypeError, ValueError):
  1042. continue
  1043. for tray in unit.get("tray") or []:
  1044. if not isinstance(tray, dict):
  1045. continue
  1046. try:
  1047. tray_id = int(tray.get("id", 0))
  1048. except (TypeError, ValueError):
  1049. continue
  1050. ttype = (tray.get("tray_type") or "").strip()
  1051. tcolor = (tray.get("tray_color") or "").strip().upper()
  1052. if not ttype:
  1053. continue # Empty / unloaded slot.
  1054. loaded[unit_id * 4 + tray_id] = (ttype, tcolor)
  1055. if not loaded:
  1056. return result
  1057. if ams_mapping:
  1058. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1059. filaments = [loaded[g] for g in used_ids if g in loaded]
  1060. if not filaments:
  1061. return result # Mapping points entirely at slots we have no data for.
  1062. else:
  1063. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1064. types_joined = ",".join(f[0] for f in filaments)
  1065. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1066. # Column limits per backend/app/models/archive.py: filament_type=50,
  1067. # filament_color=200.
  1068. if types_joined:
  1069. result["filament_type"] = types_joined[:50]
  1070. if colors_joined:
  1071. result["filament_color"] = colors_joined[:200]
  1072. return result
  1073. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1074. """Start a layer-timelapse session for *archive_id* when the printer has
  1075. an external camera configured. Returns True if a session was started.
  1076. Three call sites in on_print_start (expected-archive promotion, fallback
  1077. archive creation, fresh-archive creation) used to inline this same
  1078. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1079. on the first pass). Centralising the conditional + call here makes the
  1080. contract testable in isolation and keeps the three sites locked in step.
  1081. """
  1082. if not (printer.external_camera_enabled and printer.external_camera_url):
  1083. return False
  1084. from backend.app.services.layer_timelapse import start_session
  1085. start_session(
  1086. printer_id,
  1087. archive_id,
  1088. printer.external_camera_url,
  1089. printer.external_camera_type or "mjpeg",
  1090. snapshot_url=printer.external_camera_snapshot_url,
  1091. rotation=getattr(printer, "camera_rotation", 0),
  1092. )
  1093. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1094. return True
  1095. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1096. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1097. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity.
  1098. The short code used for the hms_errors.py lookup table is 'MMMM_EEEE' — module
  1099. from attr bits 16-31, error from the numeric part of code. Falls back to the raw
  1100. short code when no description is on file. Returns None for an empty list so
  1101. callers can leave error_message unset.
  1102. """
  1103. if not hms_errors:
  1104. return None
  1105. from backend.app.services.hms_errors import get_error_description
  1106. parts: list[str] = []
  1107. for err in hms_errors:
  1108. try:
  1109. code_str = str(err.get("code", "")).replace("0x", "")
  1110. error_num = int(code_str, 16) if code_str else 0
  1111. module_num = (int(err.get("attr", 0)) >> 16) & 0xFFFF
  1112. short_code = f"{module_num:04X}_{error_num:04X}"
  1113. except (TypeError, ValueError):
  1114. continue
  1115. description = get_error_description(short_code)
  1116. parts.append(f"[{short_code}] {description}" if description else f"[{short_code}]")
  1117. return "; ".join(parts) if parts else None
  1118. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1119. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1120. print completes successfully. Gated to status=='completed': failed, cancelled
  1121. and aborted prints do not count as usage. Caller is responsible for committing
  1122. the session. No-op when the queue item has no linked library file (e.g. reprints
  1123. from an archive). See #1008."""
  1124. if queue_status != "completed" or item.library_file_id is None:
  1125. return
  1126. from backend.app.models.library import LibraryFile
  1127. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1128. if lib_file is None:
  1129. return
  1130. lib_file.print_count = (lib_file.print_count or 0) + 1
  1131. lib_file.last_printed_at = datetime.now(timezone.utc)
  1132. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1133. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1134. When on_print_complete fires with status 'failed' for a printer in this set we
  1135. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1136. rather than a 'print failed' notification.
  1137. """
  1138. _user_stopped_printers.add(printer_id)
  1139. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1140. _last_status_broadcast: dict[int, str] = {}
  1141. # Track printers where we've updated nozzle_count
  1142. _nozzle_count_updated: set[int] = set()
  1143. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1144. """Wait the debounce window then fire `on_printer_offline` if the printer
  1145. is still offline.
  1146. Scheduled by `on_printer_status_change` on the connected → disconnected
  1147. edge (#1752). Cancelled by the same handler if the printer reconnects
  1148. before the window elapses, so a single MQTT blip + recovery doesn't
  1149. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1150. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1151. route through the same status-change callback, so this covers both.
  1152. """
  1153. logger = logging.getLogger(__name__)
  1154. try:
  1155. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1156. still_offline = not printer_manager.is_connected(printer_id)
  1157. logger.info(
  1158. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1159. printer_id,
  1160. still_offline,
  1161. )
  1162. if not still_offline:
  1163. return
  1164. async with async_session() as db:
  1165. from backend.app.models.printer import Printer
  1166. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1167. printer = result.scalar_one_or_none()
  1168. if not printer:
  1169. logger.warning(
  1170. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1171. printer_id,
  1172. )
  1173. return
  1174. logger.info(
  1175. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1176. printer_id,
  1177. printer.name,
  1178. )
  1179. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1180. except asyncio.CancelledError:
  1181. raise
  1182. except Exception as e:
  1183. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1184. finally:
  1185. _printer_offline_notify_tasks.pop(printer_id, None)
  1186. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1187. """Handle printer status changes - broadcast via WebSocket."""
  1188. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1189. # transitions disconnected → connected — which covers both Bambuddy
  1190. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1191. # `reconcile_stale_active_prints` exactly once for this connection so
  1192. # any archive still in `status="printing"` that can't actually be
  1193. # running anymore (printer IDLE / different subtask / empty subtask)
  1194. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1195. # finished during a disconnect window + a smart-plug power cycle
  1196. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1197. # next boot. Reconciliation runs concurrently — it must not block the
  1198. # WebSocket dedup / broadcast logic below, and the connected edge is
  1199. # marked True BEFORE the await so concurrent status updates inside
  1200. # the same connection don't re-trigger reconciliation.
  1201. #
  1202. # Wait for a real push_status before reconciling (#1679): MQTT
  1203. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1204. # the connection, BEFORE `_request_push_all` round-trips. At that
  1205. # instant the `PrinterState` is still on construction defaults — most
  1206. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1207. # If reconcile spawns here, every in-flight archive falls through to
  1208. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1209. # creates a duplicate archive on the real PRINT COMPLETE and
  1210. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1211. # keeps the #1542 mechanism intact: once the first real push_status
  1212. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1213. # fires again with the flag still False — reconcile then runs against
  1214. # actual evidence.
  1215. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1216. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1217. _printer_reconciled_since_connect[printer_id] = True
  1218. spawn_background_task(
  1219. reconcile_stale_active_prints(printer_id),
  1220. name=f"reconcile-stale-prints-{printer_id}",
  1221. )
  1222. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1223. # Re-arm so the next reconnect triggers reconciliation again.
  1224. _printer_reconciled_since_connect[printer_id] = False
  1225. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1226. # connected → disconnected. The "back online" channel is already covered
  1227. # by the print-failure notification (firmware reports gcode_state=FAILED
  1228. # on reconnect of an interrupted print), so we don't add a symmetric
  1229. # online event here.
  1230. prev_connected = _printer_last_connected.get(printer_id)
  1231. _printer_last_connected[printer_id] = state.connected
  1232. if prev_connected is True and not state.connected:
  1233. existing = _printer_offline_notify_tasks.get(printer_id)
  1234. if existing is None or existing.done():
  1235. logging.getLogger(__name__).info(
  1236. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1237. printer_id,
  1238. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1239. )
  1240. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1241. _maybe_notify_printer_offline(printer_id),
  1242. name=f"printer-offline-notify-{printer_id}",
  1243. )
  1244. elif state.connected:
  1245. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1246. if pending is not None and not pending.done():
  1247. logging.getLogger(__name__).info(
  1248. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1249. printer_id,
  1250. )
  1251. pending.cancel()
  1252. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1253. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1254. temps = state.temperatures or {}
  1255. nozzle_temp = round(temps.get("nozzle", 0))
  1256. bed_temp = round(temps.get("bed", 0))
  1257. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1258. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1259. # Auto-detect dual-nozzle printers from MQTT temperature data
  1260. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1261. _nozzle_count_updated.add(printer_id)
  1262. # Update nozzle_count in database
  1263. async with async_session() as db:
  1264. from backend.app.models.printer import Printer
  1265. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1266. printer = result.scalar_one_or_none()
  1267. if printer and printer.nozzle_count != 2:
  1268. printer.nozzle_count = 2
  1269. await db.commit()
  1270. logging.getLogger(__name__).info(
  1271. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1272. )
  1273. # Include target temps for heating phase detection
  1274. bed_target = round(temps.get("bed_target", 0))
  1275. nozzle_target = round(temps.get("nozzle_target", 0))
  1276. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1277. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1278. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts
  1279. ams_dry_key = tuple(a.get("dry_time", 0) for a in (state.raw_data.get("ams") or [])) if state.raw_data else ()
  1280. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1281. #
  1282. # The filament identity fields are here because Configure Slot writes
  1283. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1284. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1285. # matched, this function returned before broadcasting, and the card kept
  1286. # showing the old filament until the 30s fallback poll or a page reload —
  1287. # even though the configure route asks the printer for a fresh pushall and
  1288. # that push does carry the new values. Reset always worked, because it
  1289. # clears tray_type.
  1290. #
  1291. # These fields only change when someone configures a slot or swaps a spool,
  1292. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1293. ams_tray_key = (
  1294. tuple(
  1295. (
  1296. t.get("id"),
  1297. t.get("tray_type", ""),
  1298. t.get("state"),
  1299. t.get("tray_color", ""),
  1300. t.get("tray_info_idx", ""),
  1301. t.get("tray_sub_brands", ""),
  1302. t.get("cali_idx"),
  1303. )
  1304. for a in (state.raw_data.get("ams") or [])
  1305. for t in a.get("tray", [])
  1306. )
  1307. if state.raw_data
  1308. else ()
  1309. )
  1310. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1311. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1312. # in the AMS change-hash (tray fields only, and widening that would fire
  1313. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1314. # screen changed no key at all and the card's inlet badges sat stale until a
  1315. # reload. Like the filament-backup flag, these only move when someone
  1316. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1317. fts_key = (
  1318. state.fila_switch.installed if state.fila_switch else False,
  1319. tuple(sorted(state.ams_switch_inlet.items())),
  1320. )
  1321. status_key = (
  1322. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1323. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1324. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1325. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1326. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1327. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1328. )
  1329. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1330. if not is_active_print:
  1331. _unauthorized_print_kill_sent.discard(printer_id)
  1332. elif printer_id in _unauthorized_print_kill_sent:
  1333. # stop_print() was already sent for this print; avoid all further
  1334. # ownership and settings work until the printer leaves an active state.
  1335. pass
  1336. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1337. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1338. _unauthorized_print_kill_sent.discard(printer_id)
  1339. else:
  1340. kill_switch_enabled = False
  1341. authorization: bool | None = None
  1342. status_logger = logging.getLogger(__name__)
  1343. try:
  1344. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1345. if kill_switch_enabled:
  1346. async with async_session() as db:
  1347. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1348. except Exception as e:
  1349. # Fail safe: a database/reconciliation error must never turn into an
  1350. # irreversible stop of a print whose ownership is still unknown.
  1351. authorization = None
  1352. status_logger.warning(
  1353. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1354. )
  1355. if not kill_switch_enabled or authorization is True:
  1356. _unauthorized_print_kill_sent.discard(printer_id)
  1357. elif authorization is None:
  1358. _unauthorized_print_kill_sent.discard(printer_id)
  1359. status_logger.debug(
  1360. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1361. printer_id,
  1362. )
  1363. else:
  1364. try:
  1365. stopped = printer_manager.stop_print(printer_id)
  1366. if stopped:
  1367. _unauthorized_print_kill_sent.add(printer_id)
  1368. printer_info = printer_manager.get_printer(printer_id)
  1369. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1370. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1371. notification_data = {
  1372. "status": "stopped",
  1373. "filename": state.gcode_file or state.current_print or "",
  1374. "subtask_name": state.subtask_name or "",
  1375. "progress": state.progress,
  1376. "reason": "unauthorized_print",
  1377. }
  1378. status_logger.warning(
  1379. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1380. printer_id,
  1381. state.state,
  1382. )
  1383. try:
  1384. await ws_manager.broadcast(
  1385. {
  1386. "type": "kill_switch_triggered",
  1387. "printer_id": printer_id,
  1388. "printer_name": printer_name,
  1389. "filename": filename,
  1390. "reason": "unauthorized_print",
  1391. }
  1392. )
  1393. except Exception as e:
  1394. status_logger.warning(
  1395. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1396. )
  1397. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1398. if previous_task is not None and not previous_task.done():
  1399. previous_task.cancel()
  1400. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1401. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1402. name=f"kill-switch-notification-{printer_id}",
  1403. )
  1404. else:
  1405. status_logger.warning(
  1406. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1407. printer_id,
  1408. state.state,
  1409. )
  1410. except Exception as e:
  1411. status_logger.warning(
  1412. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1413. )
  1414. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1415. try:
  1416. printer_info = printer_manager.get_printer(printer_id)
  1417. if printer_info:
  1418. await mqtt_relay.on_printer_status(
  1419. printer_id,
  1420. state,
  1421. printer_info.name,
  1422. printer_info.serial_number,
  1423. printer_manager.is_awaiting_plate_clear(printer_id),
  1424. )
  1425. except Exception:
  1426. pass # Don't fail status callback if MQTT fails
  1427. if _last_status_broadcast.get(printer_id) == status_key:
  1428. return # No change, skip WebSocket broadcast
  1429. _last_status_broadcast[printer_id] = status_key
  1430. # Check for progress milestone notifications (25%, 50%, 75%)
  1431. progress = state.progress or 0
  1432. is_printing = state.state in ("RUNNING", "PRINTING")
  1433. if is_printing and progress > 0:
  1434. # Determine which milestone we've reached
  1435. current_milestone = 0
  1436. if progress >= 75:
  1437. current_milestone = 75
  1438. elif progress >= 50:
  1439. current_milestone = 50
  1440. elif progress >= 25:
  1441. current_milestone = 25
  1442. last_milestone = _last_progress_milestone.get(printer_id, 0)
  1443. # If we've crossed a new milestone, send notification
  1444. if current_milestone > last_milestone:
  1445. _last_progress_milestone[printer_id] = current_milestone
  1446. try:
  1447. from backend.app.models.printer import Printer
  1448. # Read the printer in a short session and release the connection
  1449. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1450. # pinned a pooled connection per milestone, per printer (issue #2572).
  1451. async with async_session() as db:
  1452. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1453. printer = result.scalar_one_or_none()
  1454. printer_name = printer.name if printer else f"Printer {printer_id}"
  1455. filename = state.subtask_name or state.gcode_file or "Unknown"
  1456. # remaining_time is in minutes, convert to seconds for notification
  1457. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1458. # Capture camera snapshot for notification image attachment (no DB held).
  1459. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1460. # Notification send needs a session (provider/template lookups).
  1461. async with async_session() as db:
  1462. await notification_service.on_print_progress(
  1463. printer_id,
  1464. printer_name,
  1465. filename,
  1466. current_milestone,
  1467. db,
  1468. remaining_time_seconds,
  1469. image_data=image_data,
  1470. )
  1471. except Exception as e:
  1472. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1473. elif progress < 5:
  1474. # Reset milestone tracking when print restarts or new print begins
  1475. _last_progress_milestone[printer_id] = 0
  1476. _first_layer_notified[printer_id] = False
  1477. # HMS error codes that should not trigger notifications even though they
  1478. # have known descriptions (e.g. user-initiated actions, not real errors).
  1479. _HMS_NOTIFICATION_SUPPRESS = {
  1480. "0500_400E", # Printing was cancelled (user action, not an error)
  1481. }
  1482. # Check for new HMS errors and send notifications
  1483. current_hms_errors = getattr(state, "hms_errors", []) or []
  1484. if current_hms_errors:
  1485. # Build set of current error codes (using attr for uniqueness)
  1486. current_error_codes = {f"{e.attr:08x}" for e in current_hms_errors}
  1487. previously_notified = _notified_hms_errors.get(printer_id, set())
  1488. # Find new errors that haven't been notified yet
  1489. new_error_codes = current_error_codes - previously_notified
  1490. # Update tracking immediately to prevent duplicate notifications from concurrent callbacks
  1491. _notified_hms_errors[printer_id] = current_error_codes
  1492. _hms_last_seen[printer_id] = time.time()
  1493. if new_error_codes:
  1494. # Get the actual new errors for the notification
  1495. # Filter to severity >= 2 (skip informational/status messages like H2D sends)
  1496. new_errors = [e for e in current_hms_errors if f"{e.attr:08x}" in new_error_codes and e.severity >= 2]
  1497. try:
  1498. from backend.app.models.printer import Printer
  1499. # Read the printer in a short session and release the connection
  1500. # BEFORE the ~15s camera snapshot below (issue #2572).
  1501. async with async_session() as db:
  1502. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1503. printer = result.scalar_one_or_none()
  1504. printer_name = printer.name if printer else f"Printer {printer_id}"
  1505. # Format error details for notification
  1506. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1507. module_names = {
  1508. 0x03: "Print/Task",
  1509. 0x05: "Nozzle/Extruder",
  1510. 0x07: "AMS/Filament",
  1511. 0x0C: "Motion Controller",
  1512. 0x12: "Chamber",
  1513. }
  1514. from backend.app.services.hms_errors import get_error_description
  1515. # Capture camera snapshot once for all error notifications (no DB held).
  1516. error_image_data = await _capture_snapshot_for_notification(
  1517. printer_id, printer, logging.getLogger(__name__)
  1518. )
  1519. # Notification sends need a session (provider/template lookups).
  1520. async with async_session() as db:
  1521. sent_count = 0
  1522. for error in new_errors:
  1523. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  1524. # Build short code like "0700_8010"
  1525. # Mask to 16 bits to handle printers that send larger values
  1526. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  1527. error_code_masked = error_code_int & 0xFFFF
  1528. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  1529. # Only notify for errors with known descriptions — printers
  1530. # send many undocumented/phantom codes that aren't real errors.
  1531. description = get_error_description(short_code)
  1532. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  1533. continue
  1534. error_type = f"{module_name} Error"
  1535. error_detail = description
  1536. await notification_service.on_printer_error(
  1537. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  1538. )
  1539. sent_count += 1
  1540. if sent_count:
  1541. logging.getLogger(__name__).info(
  1542. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  1543. )
  1544. # Also publish to MQTT relay (no DB).
  1545. printer_info = printer_manager.get_printer(printer_id)
  1546. if printer_info:
  1547. errors_data = [
  1548. {
  1549. "code": e.code,
  1550. "attr": e.attr,
  1551. "module": e.module,
  1552. "severity": e.severity,
  1553. }
  1554. for e in new_errors
  1555. ]
  1556. await mqtt_relay.on_printer_error(
  1557. printer_id, printer_info.name, printer_info.serial_number, errors_data
  1558. )
  1559. except Exception as e:
  1560. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  1561. else:
  1562. # No HMS errors — only clear tracking after a grace period to prevent
  1563. # flapping errors (brief hms:[] gaps) from re-triggering notifications.
  1564. # Some HMS codes (e.g. chamber temp regulation during PETG prints) toggle
  1565. # on/off every few seconds as conditions fluctuate around thresholds.
  1566. if printer_id in _notified_hms_errors:
  1567. last_seen = _hms_last_seen.get(printer_id, 0)
  1568. if time.time() - last_seen >= _HMS_CLEAR_GRACE_SECONDS:
  1569. _notified_hms_errors.pop(printer_id, None)
  1570. _hms_last_seen.pop(printer_id, None)
  1571. await ws_manager.send_printer_status(
  1572. printer_id,
  1573. printer_state_to_dict(
  1574. state,
  1575. printer_id,
  1576. printer_manager.get_model(printer_id),
  1577. printer_manager.get_drying_targets(printer_id),
  1578. ),
  1579. )
  1580. def _is_bambu_uuid(tray_uuid: str) -> bool:
  1581. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  1582. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  1583. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  1584. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  1585. K-profiles are per-nozzle and the printer's calibration table is numbered
  1586. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  1587. switch's other inlet therefore silently invalidates every configured slot in
  1588. it: the index stays put and now resolves against the other nozzle's table.
  1589. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  1590. and 0.020 on the right kept the left profile after the move, and a manual
  1591. RFID re-read only re-asserted the same wrong one.
  1592. Configuring a slot is a deliberate preparation step, so this re-selects
  1593. rather than re-configures: only the calibration binding moves, and only for
  1594. slots whose spool already has a stored profile for the new nozzle. A slot
  1595. Bambuddy knows nothing about is left exactly as the operator left it.
  1596. """
  1597. logger = logging.getLogger(__name__)
  1598. target_extruder = extruder_for_inlet(inlet)
  1599. if target_extruder is None:
  1600. return
  1601. client = printer_manager.get_client(printer_id)
  1602. state = printer_manager.get_status(printer_id)
  1603. if not client or not state or not state.raw_data:
  1604. return
  1605. nozzle_diameter = "0.4"
  1606. if state.nozzles and state.nozzles[0].nozzle_diameter:
  1607. nozzle_diameter = state.nozzles[0].nozzle_diameter
  1608. ams_raw = state.raw_data.get("ams")
  1609. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  1610. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  1611. if not unit:
  1612. return
  1613. try:
  1614. async with async_session() as db:
  1615. for tray in unit.get("tray", []):
  1616. tray_id = int(tray.get("id", -1))
  1617. if tray_id < 0 or not tray.get("tray_type"):
  1618. continue
  1619. current_idx = tray.get("cali_idx")
  1620. profile = await find_slot_kprofile_for_extruder(
  1621. db, printer_id, ams_id, tray_id, target_extruder, nozzle_diameter
  1622. )
  1623. if profile is None or profile.cali_idx is None:
  1624. continue
  1625. if current_idx == profile.cali_idx:
  1626. continue # Already on the right one.
  1627. logger.info(
  1628. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  1629. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  1630. printer_id,
  1631. ams_id,
  1632. tray_id,
  1633. inlet,
  1634. target_extruder,
  1635. profile.name,
  1636. current_idx,
  1637. profile.cali_idx,
  1638. profile.k_value,
  1639. )
  1640. client.extrusion_cali_sel(
  1641. ams_id=ams_id,
  1642. tray_id=tray_id,
  1643. cali_idx=profile.cali_idx,
  1644. filament_id=profile.filament_id or tray.get("tray_info_idx", "") or "",
  1645. nozzle_diameter=nozzle_diameter,
  1646. )
  1647. except Exception as e:
  1648. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  1649. async def on_ams_change(printer_id: int, ams_data: list):
  1650. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  1651. logger = logging.getLogger(__name__)
  1652. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  1653. # on_print_complete may pop _active_sessions during our awaits (#880).
  1654. from backend.app.services.usage_tracker import _active_sessions
  1655. _print_active = printer_id in _active_sessions
  1656. # A slot that reports empty while a print is running is a filament runout,
  1657. # not a spool swap: the spool is still physically in the AMS, just
  1658. # consumed. Dropping either inventory backend's slot link there loses the
  1659. # only record of which spool fed the print, so the completion path can't
  1660. # charge the runout segment to anything. Both cleanup passes below consult
  1661. # this; computed once, up front, so neither depends on the other having run.
  1662. _unlink_state = printer_manager.get_status(printer_id)
  1663. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  1664. # MQTT relay - publish AMS change
  1665. try:
  1666. printer_info = printer_manager.get_printer(printer_id)
  1667. if printer_info:
  1668. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  1669. except Exception:
  1670. pass # Don't fail AMS callback if MQTT fails
  1671. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  1672. # This ensures frontend gets immediate updates when AMS slots are configured
  1673. try:
  1674. state = printer_manager.get_status(printer_id)
  1675. if state:
  1676. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  1677. await ws_manager.send_printer_status(
  1678. printer_id,
  1679. printer_state_to_dict(
  1680. state,
  1681. printer_id,
  1682. printer_manager.get_model(printer_id),
  1683. printer_manager.get_drying_targets(printer_id),
  1684. ),
  1685. )
  1686. except Exception as e:
  1687. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  1688. from backend.app.utils.color_utils import colors_similar as _colors_similar
  1689. # Auto-unlink spool assignments with stale fingerprints
  1690. try:
  1691. async with async_session() as db:
  1692. from sqlalchemy.orm import selectinload
  1693. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  1694. from backend.app.models.spool import Spool as _Spool
  1695. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1696. result = await db.execute(
  1697. select(SA)
  1698. .where(SA.printer_id == printer_id)
  1699. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  1700. )
  1701. # ``printing_now`` (top of this function) keeps a runout from
  1702. # unlinking the spool that fed the print — the next idle-time pass
  1703. # unlinks it if the user really did take it out.
  1704. stale = []
  1705. for assignment in result.scalars().all():
  1706. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  1707. if assignment.ams_id == 255:
  1708. ps = printer_manager.get_status(printer_id)
  1709. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  1710. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  1711. current_tray = None
  1712. for vt in vt_tray_raw:
  1713. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  1714. current_tray = vt
  1715. break
  1716. if not current_tray:
  1717. # vt_tray data may not have arrived yet — keep assignment
  1718. continue
  1719. else:
  1720. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  1721. if not current_tray:
  1722. if printing_now:
  1723. logger.info(
  1724. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  1725. assignment.spool_id,
  1726. assignment.ams_id,
  1727. assignment.tray_id,
  1728. )
  1729. continue
  1730. logger.info(
  1731. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  1732. assignment.spool_id,
  1733. assignment.ams_id,
  1734. assignment.tray_id,
  1735. )
  1736. stale.append(assignment) # Slot empty
  1737. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  1738. # A Bambu Lab spool is in this slot — check if it's the same spool
  1739. # that's currently assigned. If yes, keep the assignment (avoids
  1740. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  1741. # the printer's filament preset on every startup).
  1742. tray_uuid = current_tray.get("tray_uuid", "")
  1743. tag_uid = current_tray.get("tag_uid", "")
  1744. spool = assignment.spool
  1745. spool_matches = False
  1746. if spool:
  1747. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  1748. spool.tag_uid
  1749. and tag_uid
  1750. and tag_uid != "0000000000000000"
  1751. and spool.tag_uid.upper() == tag_uid.upper()
  1752. ):
  1753. spool_matches = True
  1754. if spool_matches:
  1755. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  1756. cur_color = current_tray.get("tray_color", "")
  1757. cur_type = current_tray.get("tray_type", "")
  1758. fp_color = assignment.fingerprint_color or ""
  1759. fp_type = assignment.fingerprint_type or ""
  1760. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  1761. assignment.fingerprint_color = cur_color
  1762. assignment.fingerprint_type = cur_type
  1763. logger.debug(
  1764. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  1765. assignment.spool_id,
  1766. assignment.ams_id,
  1767. assignment.tray_id,
  1768. )
  1769. continue
  1770. # Different BL spool or unrecognized — unlink so auto-assign can match
  1771. logger.info(
  1772. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  1773. assignment.spool_id,
  1774. assignment.ams_id,
  1775. assignment.tray_id,
  1776. tray_uuid,
  1777. )
  1778. stale.append(assignment)
  1779. else:
  1780. cur_color = current_tray.get("tray_color", "")
  1781. cur_type = current_tray.get("tray_type", "")
  1782. cur_state = current_tray.get("state")
  1783. fp_color = assignment.fingerprint_color or ""
  1784. fp_type = assignment.fingerprint_type or ""
  1785. # SpoolBuddy pre-config replay: fingerprint_type empty means
  1786. # the slot was empty when the user pre-assigned via SpoolBuddy
  1787. # (the firmware drops ams_filament_setting on empty slots, so
  1788. # MQTT was deferred). The moment any filament gets inserted
  1789. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  1790. # reconfigured spool — fire the deferred configuration.
  1791. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  1792. # extruder" code) OR, on firmwares that don't use the state
  1793. # enum meaningfully, a non-empty tray_type when state is
  1794. # NOT one of the firmware's explicit empty signals (9, 10).
  1795. # state-only was wrong for firmwares that never set 11 — A1
  1796. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  1797. # always report state=3 — so the replay never fired for them
  1798. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  1799. # explicit "empty" signals authoritative over any stale
  1800. # tray_type that might survive the relay's auto-clearing.
  1801. loaded = cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  1802. if not fp_type.strip() and loaded and assignment.spool:
  1803. try:
  1804. from backend.app.api.routes.inventory import (
  1805. apply_spool_to_slot_via_mqtt,
  1806. )
  1807. await apply_spool_to_slot_via_mqtt(
  1808. db=db,
  1809. current_user=None,
  1810. spool=assignment.spool,
  1811. printer_id=printer_id,
  1812. ams_id=assignment.ams_id,
  1813. tray_id=assignment.tray_id,
  1814. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  1815. current_tray_type=cur_type,
  1816. )
  1817. logger.info(
  1818. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  1819. assignment.spool_id,
  1820. printer_id,
  1821. assignment.ams_id,
  1822. assignment.tray_id,
  1823. )
  1824. except Exception:
  1825. logger.exception(
  1826. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  1827. assignment.spool_id,
  1828. printer_id,
  1829. assignment.ams_id,
  1830. assignment.tray_id,
  1831. )
  1832. assignment.fingerprint_color = cur_color
  1833. assignment.fingerprint_type = cur_type
  1834. continue
  1835. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  1836. # Blank tray data mid-print is a runout, not a swap: the
  1837. # firmware clears colour and type when it unloads a spool
  1838. # it just emptied. Unlinking here would erase the record
  1839. # of which spool fed the print so far.
  1840. if printing_now and not cur_color.strip() and not cur_type.strip():
  1841. logger.info(
  1842. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  1843. "(runout?)",
  1844. assignment.spool_id,
  1845. assignment.ams_id,
  1846. assignment.tray_id,
  1847. )
  1848. continue
  1849. # Fingerprint mismatch — but check if tray now matches the
  1850. # assigned spool (e.g. auto-configure changed the tray).
  1851. spool = assignment.spool
  1852. if spool:
  1853. spool_color = (spool.rgba or "FFFFFFFF").upper()
  1854. spool_type = (spool.material or "").upper()
  1855. if _colors_similar(cur_color, spool_color) and cur_type.upper() == spool_type:
  1856. logger.info(
  1857. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  1858. assignment.spool_id,
  1859. assignment.ams_id,
  1860. assignment.tray_id,
  1861. )
  1862. assignment.fingerprint_color = cur_color
  1863. assignment.fingerprint_type = cur_type
  1864. continue
  1865. logger.info(
  1866. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  1867. assignment.spool_id,
  1868. assignment.ams_id,
  1869. assignment.tray_id,
  1870. cur_color,
  1871. cur_type,
  1872. fp_color,
  1873. fp_type,
  1874. spool.rgba if spool else "?",
  1875. spool.material if spool else "?",
  1876. )
  1877. stale.append(assignment) # Spool changed
  1878. # Snapshot slots before delete — ORM attribute access after the
  1879. # commit would refresh against a deleted row.
  1880. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  1881. for a in stale:
  1882. await db.delete(a)
  1883. if stale:
  1884. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  1885. # Commit any changes (stale deletions and/or fingerprint updates)
  1886. await db.commit()
  1887. # Tell open browsers the assignment is gone (#2575). Only the manual
  1888. # REST assign/unassign endpoints broadcast this event; without it the
  1889. # frontend's spool-assignments cache keeps rendering the unlinked
  1890. # spool on the slot until an unrelated refetch — which reads exactly
  1891. # like "the fix didn't work" (reporter verified: a browser refresh
  1892. # after the swap showed the correct state all along).
  1893. for ams_id, tray_id in unlinked_slots:
  1894. await ws_manager.broadcast(
  1895. {
  1896. "type": "spool_assignment_changed",
  1897. "printer_id": printer_id,
  1898. "ams_id": ams_id,
  1899. "tray_id": tray_id,
  1900. }
  1901. )
  1902. except Exception as e:
  1903. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  1904. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  1905. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  1906. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  1907. # "no existing assignment" for the same (printer, ams, tray) and race to
  1908. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  1909. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  1910. # bug stayed latent there. See _ams_assignment_locks comment for details.
  1911. try:
  1912. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  1913. from backend.app.api.routes.settings import get_setting
  1914. from backend.app.models.spool import Spool
  1915. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1916. from backend.app.services.spool_tag_matcher import (
  1917. auto_assign_spool,
  1918. create_spool_from_tray,
  1919. find_matching_untagged_spool,
  1920. get_spool_by_tag,
  1921. is_bambu_tag,
  1922. is_valid_tag,
  1923. link_tag_to_inventory_spool,
  1924. )
  1925. _spoolman_on = await get_setting(db, "spoolman_enabled")
  1926. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  1927. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  1928. if not _spoolman_on or _spoolman_on.lower() != "true":
  1929. for ams_unit in ams_data:
  1930. if not isinstance(ams_unit, dict):
  1931. continue
  1932. ams_id = int(ams_unit.get("id", 0))
  1933. for tray in ams_unit.get("tray", []):
  1934. if not isinstance(tray, dict):
  1935. continue
  1936. tray_id = int(tray.get("id", 0))
  1937. tag_uid = tray.get("tag_uid", "")
  1938. tray_uuid = tray.get("tray_uuid", "")
  1939. tray_info_idx = tray.get("tray_info_idx", "")
  1940. if not tray.get("tray_type"):
  1941. # Slot reported empty — drop any cached unknown-tag
  1942. # broadcast so reinserting the same spool re-prompts.
  1943. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  1944. continue # Empty slot
  1945. # Check if assignment already exists for this slot
  1946. existing = await db.execute(
  1947. select(SA)
  1948. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  1949. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  1950. )
  1951. existing_assignment = existing.scalar_one_or_none()
  1952. if existing_assignment:
  1953. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  1954. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  1955. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  1956. # Skip during active prints: the usage tracker handles deduction
  1957. # precisely via 3MF data on print completion. Without this guard the
  1958. # AMS remain% SET and the usage tracker ADD both fire from the same
  1959. # MQTT message, doubling the deduction (#880).
  1960. if _print_active:
  1961. continue
  1962. remain_raw = tray.get("remain")
  1963. if (
  1964. remain_raw is not None
  1965. and existing_assignment.spool
  1966. and not existing_assignment.spool.weight_locked
  1967. ):
  1968. try:
  1969. remain_val = int(remain_raw)
  1970. except (TypeError, ValueError):
  1971. remain_val = -1
  1972. if 1 <= remain_val <= 100:
  1973. lw = existing_assignment.spool.label_weight or 1000
  1974. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  1975. current_used = existing_assignment.spool.weight_used or 0
  1976. if new_used > current_used + 1:
  1977. logger.info(
  1978. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  1979. existing_assignment.spool_id,
  1980. current_used,
  1981. new_used,
  1982. remain_val,
  1983. )
  1984. existing_assignment.spool.weight_used = new_used
  1985. await db.commit()
  1986. # Re-apply stored K-profile when the live tray's
  1987. # cali_idx drifted from the spool's stored profile.
  1988. # This catches "reset slot → re-read" and any other
  1989. # path where the firmware loses the user's K-profile
  1990. # selection while the SpoolAssignment row persists.
  1991. # Per the maintainer's rule: any time a spool tag is
  1992. # identified and matches inventory, the slot must be
  1993. # configured with the spool's stored settings. Without
  1994. # this block the existing-assignment branch only ran
  1995. # weight-sync and let the firmware-default cali_idx win.
  1996. try:
  1997. spool = existing_assignment.spool
  1998. if (
  1999. spool is not None
  2000. and is_bambu_tag(tag_uid, tray_uuid, tray_info_idx)
  2001. and spool.k_profiles
  2002. ):
  2003. state = printer_manager.get_status(printer_id)
  2004. nozzle_diameter = "0.4"
  2005. if state and state.nozzles:
  2006. nd = state.nozzles[0].nozzle_diameter
  2007. if nd:
  2008. nozzle_diameter = nd
  2009. slot_extruder = resolve_slot_extruder(
  2010. ams_id,
  2011. tray_id,
  2012. state.ams_extruder_map if state else None,
  2013. state.ams_switch_inlet if state else None,
  2014. )
  2015. # Prefer exact extruder match, fall back to
  2016. # extruder-agnostic kp for the same printer +
  2017. # nozzle. Avoids hard-skipping when the AMS is
  2018. # mapped differently than at calibration time.
  2019. matching_kp = None
  2020. fallback_kp = None
  2021. for kp in spool.k_profiles:
  2022. if (
  2023. kp.printer_id != printer_id
  2024. or kp.nozzle_diameter != nozzle_diameter
  2025. or kp.cali_idx is None
  2026. ):
  2027. continue
  2028. if (
  2029. slot_extruder is not None
  2030. and kp.extruder is not None
  2031. and kp.extruder == slot_extruder
  2032. ):
  2033. matching_kp = kp
  2034. break
  2035. if fallback_kp is None:
  2036. fallback_kp = kp
  2037. chosen_kp = matching_kp or fallback_kp
  2038. if chosen_kp is not None:
  2039. live_cali_idx = tray.get("cali_idx")
  2040. # Only fire MQTT when the printer's live
  2041. # cali_idx differs from the stored value.
  2042. # Avoids spamming the broker on every
  2043. # MQTT push during steady-state operation.
  2044. if live_cali_idx != chosen_kp.cali_idx:
  2045. client = printer_manager.get_client(printer_id)
  2046. if client:
  2047. cali_filament_id = spool.slicer_filament or tray_info_idx or ""
  2048. client.extrusion_cali_sel(
  2049. ams_id=ams_id,
  2050. tray_id=tray_id,
  2051. cali_idx=chosen_kp.cali_idx,
  2052. filament_id=cali_filament_id,
  2053. nozzle_diameter=nozzle_diameter,
  2054. )
  2055. logger.info(
  2056. "Re-applied K-profile cali_idx=%d for spool %d "
  2057. "on printer %d AMS%d-T%d (live=%s drift detected)",
  2058. chosen_kp.cali_idx,
  2059. spool.id,
  2060. printer_id,
  2061. ams_id,
  2062. tray_id,
  2063. live_cali_idx,
  2064. )
  2065. except Exception:
  2066. logger.exception(
  2067. "K-profile re-apply failed for printer %d AMS%d-T%d",
  2068. printer_id,
  2069. ams_id,
  2070. tray_id,
  2071. )
  2072. continue
  2073. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2074. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2075. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2076. if not spool:
  2077. # Try matching an untagged inventory spool (same material/color)
  2078. spool = await find_matching_untagged_spool(db, tray)
  2079. if spool:
  2080. await link_tag_to_inventory_spool(db, spool, tray)
  2081. elif _auto_add_unknown:
  2082. spool = await create_spool_from_tray(db, tray)
  2083. else:
  2084. # Auto-add disabled: surface the slot so the
  2085. # user can add it manually via the UI.
  2086. await _broadcast_unknown_tag(
  2087. printer_id=printer_id,
  2088. ams_id=ams_id,
  2089. tray_id=tray_id,
  2090. tag_uid=tag_uid,
  2091. tray_uuid=tray_uuid,
  2092. tray_type=tray.get("tray_type"),
  2093. tray_color=tray.get("tray_color"),
  2094. tray_sub_brands=tray.get("tray_sub_brands"),
  2095. tray_count=len(ams_unit.get("tray", [])),
  2096. )
  2097. continue
  2098. # Slot matched (existing tag, untagged inventory
  2099. # match, or freshly auto-created spool) — drop any
  2100. # stale dedup so a future tag swap re-prompts.
  2101. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2102. await auto_assign_spool(
  2103. printer_id,
  2104. ams_id,
  2105. tray_id,
  2106. spool,
  2107. printer_manager,
  2108. db,
  2109. tray_info_idx=tray_info_idx,
  2110. )
  2111. await db.commit()
  2112. await ws_manager.broadcast(
  2113. {
  2114. "type": "spool_auto_assigned",
  2115. "printer_id": printer_id,
  2116. "ams_id": ams_id,
  2117. "tray_id": tray_id,
  2118. "spool_id": spool.id,
  2119. }
  2120. )
  2121. logger.info(
  2122. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2123. spool.id,
  2124. printer_id,
  2125. ams_id,
  2126. tray_id,
  2127. )
  2128. elif is_valid_tag(tag_uid, tray_uuid):
  2129. # Non-BL spool with some tag — let user choose
  2130. await _broadcast_unknown_tag(
  2131. printer_id=printer_id,
  2132. ams_id=ams_id,
  2133. tray_id=tray_id,
  2134. tag_uid=tag_uid,
  2135. tray_uuid=tray_uuid,
  2136. tray_type=tray.get("tray_type"),
  2137. tray_color=tray.get("tray_color"),
  2138. tray_sub_brands=tray.get("tray_sub_brands"),
  2139. tray_count=len(ams_unit.get("tray", [])),
  2140. )
  2141. # No-tag slots (generic non-RFID filament) are left alone:
  2142. # nothing to identify, prompting "+ Add" would just create
  2143. # ghost spools with empty tags on every confirm.
  2144. except Exception as e:
  2145. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2146. try:
  2147. async with async_session() as db:
  2148. from backend.app.api.routes.settings import get_setting
  2149. from backend.app.models.printer import Printer
  2150. # Check if Spoolman is enabled
  2151. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2152. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2153. return
  2154. # Check sync mode
  2155. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2156. if sync_mode and sync_mode != "auto":
  2157. return # Only sync on auto mode
  2158. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2159. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2160. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2161. # always owned by per-print tracking, never by AMS auto-sync. The
  2162. # setting is still read by the settings UI for backwards compat but
  2163. # has no effect on the sync path here.
  2164. # Get Spoolman URL
  2165. spoolman_url = await get_setting(db, "spoolman_url")
  2166. if not spoolman_url:
  2167. return
  2168. # Get or create Spoolman client
  2169. client = await get_spoolman_client()
  2170. if not client:
  2171. try:
  2172. client = await init_spoolman_client(spoolman_url)
  2173. except ValueError as exc:
  2174. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2175. return
  2176. # Check if Spoolman is reachable
  2177. if not await client.health_check():
  2178. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2179. return
  2180. # Get printer name for location
  2181. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2182. printer = result.scalar_one_or_none()
  2183. printer_name = printer.name if printer else f"Printer {printer_id}"
  2184. # OPTIMIZATION: Fetch all spools once before processing trays
  2185. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2186. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2187. try:
  2188. cached_spools = await client.get_spools()
  2189. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2190. except Exception as e:
  2191. logger.error(
  2192. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2193. printer_id,
  2194. e,
  2195. )
  2196. return
  2197. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2198. from sqlalchemy.orm import selectinload
  2199. from backend.app.models.spool_assignment import SpoolAssignment
  2200. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2201. inventory_weights: dict[tuple[int, int], float] = {}
  2202. try:
  2203. assign_result = await db.execute(
  2204. select(SpoolAssignment)
  2205. .options(selectinload(SpoolAssignment.spool))
  2206. .where(SpoolAssignment.printer_id == printer_id)
  2207. )
  2208. for assignment in assign_result.scalars().all():
  2209. spool = assignment.spool
  2210. if spool and spool.label_weight > 0:
  2211. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2212. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2213. except Exception as e:
  2214. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2215. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2216. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2217. try:
  2218. slot_result = await db.execute(
  2219. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2220. )
  2221. for slot in slot_result.scalars().all():
  2222. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2223. except Exception as e:
  2224. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2225. # Sync each AMS tray and collect slot changes for DB persistence
  2226. synced = 0
  2227. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2228. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2229. for ams_unit in ams_data:
  2230. if not isinstance(ams_unit, dict):
  2231. continue
  2232. ams_id = int(ams_unit.get("id", 0))
  2233. trays = ams_unit.get("tray", [])
  2234. for tray_data in trays:
  2235. if not isinstance(tray_data, dict):
  2236. continue
  2237. tray_id_raw = int(tray_data.get("id", 0))
  2238. tray = client.parse_ams_tray(ams_id, tray_data)
  2239. if not tray:
  2240. # Empty tray slot — record for local assignment cleanup
  2241. # and drop any cached unknown-tag broadcast so a
  2242. # reinserted spool re-prompts.
  2243. #
  2244. # Not during a running print: a slot that empties there
  2245. # is a filament runout, and the spool is still in the
  2246. # AMS. `spoolman_slot_assignments` is how a tag-less
  2247. # spool assigned through the Bambuddy UI is resolved at
  2248. # completion (#1459), so deleting the row mid-print
  2249. # loses the runout segment's usage — the same failure
  2250. # the internal inventory's auto-unlink had.
  2251. if not printing_now:
  2252. empty_slots.append((ams_id, tray_id_raw))
  2253. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2254. continue
  2255. spool_tag = (
  2256. tray.tray_uuid
  2257. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2258. else tray.tag_uid
  2259. )
  2260. # Provide the hint only when no RFID is available
  2261. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2262. try:
  2263. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2264. result = await client.sync_ams_tray(
  2265. tray,
  2266. printer_name,
  2267. # Per-print tracking is the only weight writer (#1119).
  2268. # AMS auto-sync still maintains spool metadata / slot
  2269. # assignments but no longer touches remaining_weight.
  2270. disable_weight_sync=True,
  2271. cached_spools=cached_spools,
  2272. inventory_remaining=inv_remaining,
  2273. spoolman_spool_id_hint=hint,
  2274. auto_add_unknown_rfid=auto_add_unknown_rfid,
  2275. )
  2276. if result is None and spool_tag and not auto_add_unknown_rfid:
  2277. # Spoolman skipped auto-create per user setting — surface
  2278. # the slot so the UI can offer "+ Add to inventory".
  2279. await _broadcast_unknown_tag(
  2280. printer_id=printer_id,
  2281. ams_id=ams_id,
  2282. tray_id=tray.tray_id,
  2283. tag_uid=tray.tag_uid or "",
  2284. tray_uuid=tray.tray_uuid or "",
  2285. tray_type=tray.tray_type,
  2286. tray_color=tray.tray_color,
  2287. tray_sub_brands=tray.tray_sub_brands,
  2288. tray_count=len(trays),
  2289. )
  2290. elif result:
  2291. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  2292. if result:
  2293. synced += 1
  2294. if result.get("id"):
  2295. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  2296. # If a new spool was created, add it to the cache
  2297. # so subsequent trays can find it if they reference the same tag
  2298. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  2299. if not spool_exists:
  2300. cached_spools.append(result)
  2301. logger.debug(
  2302. "[Printer %s] Added newly created spool %s to cache",
  2303. printer_id,
  2304. result["id"],
  2305. )
  2306. # Reconcile slot_preset_mappings (the same row internal
  2307. # mode keeps in sync via inventory + spool_tag_matcher).
  2308. # Without this the slot card surfaces the previous spool's
  2309. # preset name — same bug shape, different inventory mode.
  2310. from backend.app.services.slot_preset_writer import (
  2311. upsert_slot_preset_for_spoolman_spool,
  2312. )
  2313. await upsert_slot_preset_for_spoolman_spool(
  2314. db=db,
  2315. spoolman_spool=result,
  2316. tray_info_idx=tray.tray_info_idx or "",
  2317. tray_sub_brands=tray.tray_sub_brands or "",
  2318. tray_type=tray.tray_type or "",
  2319. printer_id=printer_id,
  2320. ams_id=ams_id,
  2321. tray_id=tray.tray_id,
  2322. )
  2323. except Exception as e:
  2324. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  2325. if synced > 0:
  2326. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  2327. # Persist slot assignment changes to the local table
  2328. if slot_changes or empty_slots:
  2329. try:
  2330. for ams_id, tray_id, spool_id in slot_changes:
  2331. await db.execute(
  2332. text(
  2333. "INSERT INTO spoolman_slot_assignments"
  2334. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  2335. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  2336. " ON CONFLICT(printer_id, ams_id, tray_id)"
  2337. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  2338. ),
  2339. {
  2340. "printer_id": printer_id,
  2341. "ams_id": ams_id,
  2342. "tray_id": tray_id,
  2343. "spool_id": spool_id,
  2344. },
  2345. )
  2346. for ams_id, tray_id in empty_slots:
  2347. await db.execute(
  2348. delete(SpoolmanSlotAssignment).where(
  2349. SpoolmanSlotAssignment.printer_id == printer_id,
  2350. SpoolmanSlotAssignment.ams_id == ams_id,
  2351. SpoolmanSlotAssignment.tray_id == tray_id,
  2352. )
  2353. )
  2354. await db.commit()
  2355. except Exception as e:
  2356. await db.rollback()
  2357. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  2358. except Exception as e:
  2359. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  2360. async def _capture_snapshot_for_notification(printer_id: int, printer, logger) -> bytes | None:
  2361. """Capture a camera snapshot for notification image attachment.
  2362. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  2363. Uses: external camera > buffered frame > fresh capture.
  2364. """
  2365. if not printer:
  2366. return None
  2367. try:
  2368. from backend.app.api.routes.settings import get_setting
  2369. async with async_session() as db:
  2370. capture_enabled = await get_setting(db, "capture_finish_photo")
  2371. if capture_enabled is not None and capture_enabled.lower() != "true":
  2372. return None
  2373. # Try external camera first
  2374. if printer.external_camera_enabled and printer.external_camera_url:
  2375. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  2376. from backend.app.api.routes.camera import live_frame_for_capture
  2377. from backend.app.services.external_camera import capture_frame
  2378. # An external camera allows one reader, so capturing while a viewer
  2379. # is attached fails (#2707). A None here falls through to the paths
  2380. # below exactly as a failed capture did.
  2381. defer, buffered = live_frame_for_capture(printer_id)
  2382. if defer:
  2383. frame_data = buffered
  2384. else:
  2385. frame_data = await capture_frame(
  2386. printer.external_camera_url,
  2387. printer.external_camera_type or "mjpeg",
  2388. snapshot_url=printer.external_camera_snapshot_url,
  2389. )
  2390. if frame_data and len(frame_data) <= 2_500_000:
  2391. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  2392. return _apply_camera_rotation(frame_data, printer, logger)
  2393. # Try buffered frame from active stream
  2394. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  2395. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  2396. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  2397. buffered_frame = get_buffered_frame(printer_id)
  2398. if (active_for_printer or active_chamber) and buffered_frame:
  2399. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  2400. if len(buffered_frame) <= 2_500_000:
  2401. return _apply_camera_rotation(buffered_frame, printer, logger)
  2402. # Fresh capture from printer camera
  2403. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  2404. from backend.app.services.camera import capture_camera_frame_bytes
  2405. frame_data = await capture_camera_frame_bytes(
  2406. printer.ip_address, printer.access_code, printer.model, timeout=15
  2407. )
  2408. if frame_data and len(frame_data) <= 2_500_000:
  2409. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  2410. return _apply_camera_rotation(frame_data, printer, logger)
  2411. except Exception as e:
  2412. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  2413. return None
  2414. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  2415. """#1867: bank a recent in-print camera frame for the finish photo.
  2416. Called on every layer change and (#2547) on every print-progress advance.
  2417. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  2418. path has a pre-End-G-code image for prints that end with a plate swap.
  2419. Both drivers are print telemetry that stops the instant printing ends: no
  2420. further layers, and progress freezes before the End G-code (e.g. SwapMod
  2421. plate swap) executes. So the last banked frame is always the finished print,
  2422. never the swapped plate — that property is what the #1867 path relies on and
  2423. it must survive any change to the throttle below.
  2424. Layer changes alone were not enough: they stop when the *final* layer
  2425. begins, which on a three-minute last layer left the bank stale by the whole
  2426. length of that layer (#2547). Progress keeps ticking through it.
  2427. Best-effort: any failure just leaves the previous banked frame.
  2428. """
  2429. logger = logging.getLogger(__name__)
  2430. client = printer_manager.get_client(printer_id)
  2431. state = client.state if client else None
  2432. if not state or state.state != "RUNNING":
  2433. return
  2434. # Only during actual extrusion — firmware ticks layer_num during the
  2435. # pre-print calibration sequence, whose sub-stages are non-zero.
  2436. if state.mc_print_sub_stage not in (None, 0):
  2437. return
  2438. # #2547: throttled uniformly, with no last-layer exemption. The old code
  2439. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  2440. # now that progress advances also drive banking, that exemption would fire a
  2441. # camera grab on every percent tick of the last layer. Bambu printers accept
  2442. # one RTSP client at a time, so each grab contends with the live view.
  2443. now = time.monotonic()
  2444. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  2445. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  2446. return
  2447. total = state.total_layers or 0
  2448. try:
  2449. async with async_session() as db:
  2450. from backend.app.models.printer import Printer
  2451. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2452. printer = result.scalar_one_or_none()
  2453. if not printer:
  2454. return
  2455. # Reuses the notification snapshot path, which honours the
  2456. # `capture_finish_photo` setting (returns None when disabled) so we
  2457. # don't bank frames the user never asked for.
  2458. frame = await _capture_snapshot_for_notification(printer_id, printer, logger)
  2459. if frame:
  2460. _inprint_frame_bank[printer_id] = frame
  2461. _inprint_frame_bank_ts[printer_id] = now
  2462. logger.debug(
  2463. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  2464. printer_id,
  2465. layer_num,
  2466. total,
  2467. len(frame),
  2468. )
  2469. except Exception as e:
  2470. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  2471. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  2472. """Apply camera rotation to snapshot image if configured."""
  2473. from backend.app.services.camera import apply_camera_rotation
  2474. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  2475. async def _send_print_start_notification(
  2476. printer_id: int,
  2477. data: dict,
  2478. archive_data: dict | None = None,
  2479. logger=None,
  2480. ):
  2481. """Helper to send print start notification with optional archive data."""
  2482. if logger is None:
  2483. logger = logging.getLogger(__name__)
  2484. try:
  2485. async with async_session() as db:
  2486. from backend.app.models.printer import Printer
  2487. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2488. printer = result.scalar_one_or_none()
  2489. printer_name = printer.name if printer else f"Printer {printer_id}"
  2490. # Capture camera snapshot for notification image attachment
  2491. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  2492. if image_data:
  2493. if archive_data is None:
  2494. archive_data = {}
  2495. archive_data["image_data"] = image_data
  2496. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  2497. # Send user-specific email notification for print start
  2498. if archive_data and archive_data.get("created_by_id"):
  2499. await notification_service.send_user_print_email(
  2500. event_type="user_print_start",
  2501. created_by_id=archive_data["created_by_id"],
  2502. printer_name=printer_name,
  2503. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  2504. db=db,
  2505. )
  2506. except Exception as e:
  2507. logger.warning("Notification on_print_start failed: %s", e)
  2508. async def _dispatch_user_print_email(
  2509. status: str,
  2510. created_by_id: int | None,
  2511. printer_name: str,
  2512. filename: str,
  2513. db,
  2514. ) -> None:
  2515. """Send a user-specific print-completion email based on print status.
  2516. Maps the normalised print status to the correct event type and delegates
  2517. to :meth:`NotificationService.send_user_print_email`. A single helper
  2518. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  2519. "stopped"`` dispatch block at every call site.
  2520. Does nothing if *created_by_id* is ``None``.
  2521. """
  2522. if created_by_id is None:
  2523. return
  2524. if status == "completed":
  2525. event_type = "user_print_complete"
  2526. elif status == "failed":
  2527. event_type = "user_print_failed"
  2528. elif status in ("stopped", "aborted", "cancelled"):
  2529. event_type = "user_print_stopped"
  2530. else:
  2531. return
  2532. await notification_service.send_user_print_email(
  2533. event_type=event_type,
  2534. created_by_id=created_by_id,
  2535. printer_name=printer_name,
  2536. filename=filename,
  2537. db=db,
  2538. )
  2539. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  2540. """Extract printable objects from an archive's 3MF file and store in printer state."""
  2541. try:
  2542. from backend.app.services.archive import extract_printable_objects_from_archive
  2543. client = printer_manager.get_client(printer_id)
  2544. if not client:
  2545. return
  2546. # Extract with positions for UI overlay, scoped to the plate that
  2547. # is printing — resolve_plate_id is the same resolver /cover uses,
  2548. # so the object list can't disagree with the thumbnail it is drawn
  2549. # over (#2522).
  2550. printable_objects, bbox_all = extract_printable_objects_from_archive(
  2551. app_settings.base_dir / archive.file_path,
  2552. plate_number=resolve_plate_id(client.state),
  2553. )
  2554. if printable_objects:
  2555. client.state.printable_objects = printable_objects
  2556. client.state.printable_objects_bbox_all = bbox_all
  2557. client.state.skipped_objects = []
  2558. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  2559. except Exception as e:
  2560. logger.debug("Failed to extract printable objects from archive: %s", e)
  2561. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  2562. """Put the skip-objects list back after a restart mid-print.
  2563. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  2564. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  2565. which the #1304 guard suppresses on the first RUNNING push after startup.
  2566. Everything else this hook restores (the archive, the usage-tracking session,
  2567. the timelapse baseline) was already handled; the object list was not, so a
  2568. restart mid-print took skip-objects away for the rest of that print.
  2569. Nothing recovered it either: the printer card gates its Skip button on the
  2570. object count, and the one endpoint that can rebuild the list is reachable
  2571. only from the modal that button opens.
  2572. Anchored on ``subtask_id``, which the firmware mints per print, so a
  2573. leftover ``status="printing"`` row from a completion we never saw cannot
  2574. hand this print someone else's objects. Without one, nothing is loaded
  2575. rather than guessed — the reload path on ``GET /print/objects`` covers that
  2576. case on demand.
  2577. """
  2578. client = printer_manager.get_client(printer_id)
  2579. if client is None or client.state.printable_objects:
  2580. return
  2581. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  2582. if subtask_id in ("", "0"):
  2583. return
  2584. from backend.app.models.archive import PrintArchive
  2585. archive = await db.scalar(
  2586. select(PrintArchive)
  2587. .where(
  2588. PrintArchive.printer_id == printer_id,
  2589. PrintArchive.status == "printing",
  2590. PrintArchive.subtask_id == subtask_id,
  2591. )
  2592. .order_by(PrintArchive.created_at.desc())
  2593. .limit(1)
  2594. )
  2595. if archive is not None:
  2596. _load_objects_from_archive(archive, printer_id, logger)
  2597. async def on_print_start(printer_id: int, data: dict):
  2598. """Handle print start - archive the 3MF file immediately."""
  2599. logger = logging.getLogger(__name__)
  2600. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  2601. # Clear any stale user-stopped flag from previous print cycles
  2602. _user_stopped_printers.discard(printer_id)
  2603. _kill_switch_notification_tasks.pop(printer_id, None)
  2604. # #1721: drop any leftover pre-captured finish frame from a prior print
  2605. # so a never-consumed cache entry can't bleed into the new print's photo.
  2606. _stage22_finish_frames.pop(printer_id, None)
  2607. # #1867: same for the in-print frame bank — a queued print must not reuse
  2608. # the previous job's banked frame.
  2609. _inprint_frame_bank.pop(printer_id, None)
  2610. _inprint_frame_bank_ts.pop(printer_id, None)
  2611. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  2612. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  2613. # print's flag instead of inheriting it.
  2614. print_dispatch_context.adopt(printer_id)
  2615. # Cancel any active bed cooldown waiter for this printer
  2616. if _bed_cool_waiters.pop(printer_id, None):
  2617. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  2618. # Clear cached cover images so the new print's thumbnail is fetched fresh
  2619. from backend.app.api.routes.printers import clear_cover_cache
  2620. clear_cover_cache(printer_id)
  2621. await ws_manager.send_print_start(printer_id, data)
  2622. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  2623. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  2624. # MQTT relay - publish print start
  2625. try:
  2626. printer_info = printer_manager.get_printer(printer_id)
  2627. if printer_info:
  2628. await mqtt_relay.on_print_start(
  2629. printer_id,
  2630. printer_info.name,
  2631. printer_info.serial_number,
  2632. data.get("filename", ""),
  2633. data.get("subtask_name", ""),
  2634. )
  2635. except Exception:
  2636. pass # Don't fail print start callback if MQTT fails
  2637. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  2638. # and mapping, and the seeded tray-change log.
  2639. #
  2640. # Unconditional, for both inventory backends. This only *captures* — the
  2641. # writing is still split, with the internal tracker skipped at completion
  2642. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  2643. # carries its plate-scoped 3MF figures and stored mapping, but not the
  2644. # tray-change log, and that log is the only record of which spool fed
  2645. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  2646. # it on one side only would leave Spoolman users with the mid-print
  2647. # restart bug this fixes for everyone else.
  2648. try:
  2649. async with async_session() as db:
  2650. from backend.app.api.routes.settings import get_setting
  2651. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  2652. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2653. await usage_on_print_start(
  2654. printer_id,
  2655. data,
  2656. printer_manager,
  2657. db=db,
  2658. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  2659. )
  2660. except Exception as e:
  2661. logger.warning("Usage tracker on_print_start failed: %s", e)
  2662. # Track if notification was sent (to avoid sending twice)
  2663. notification_sent = False
  2664. # Smart plug automation: turn on plug when print starts
  2665. try:
  2666. async with async_session() as db:
  2667. await smart_plug_manager.on_print_start(printer_id, db)
  2668. except Exception as e:
  2669. logger.warning("Smart plug on_print_start failed: %s", e)
  2670. async with async_session() as db:
  2671. from backend.app.models.printer import Printer
  2672. from backend.app.services.bambu_ftp import list_files_async
  2673. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2674. printer = result.scalar_one_or_none()
  2675. # Plate detection check - pause if objects detected on build plate
  2676. logger.info(
  2677. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  2678. )
  2679. if printer and printer.plate_detection_enabled:
  2680. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  2681. # Release the pooled DB connection before the plate-detection camera
  2682. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  2683. # printer SELECT has run so far — nothing to persist — so this commit
  2684. # is a data-noop that ends the read transaction and returns the
  2685. # connection to the pool during the I/O (issue #2572). expire_on_commit
  2686. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  2687. # archive lookups below re-acquire a fresh connection on next execute.
  2688. await db.commit()
  2689. try:
  2690. from backend.app.services.plate_detection import check_plate_empty
  2691. # Build ROI tuple from printer settings if available
  2692. roi = None
  2693. if all(
  2694. [
  2695. printer.plate_detection_roi_x is not None,
  2696. printer.plate_detection_roi_y is not None,
  2697. printer.plate_detection_roi_w is not None,
  2698. printer.plate_detection_roi_h is not None,
  2699. ]
  2700. ):
  2701. roi = (
  2702. printer.plate_detection_roi_x,
  2703. printer.plate_detection_roi_y,
  2704. printer.plate_detection_roi_w,
  2705. printer.plate_detection_roi_h,
  2706. )
  2707. # Auto-turn on chamber light if it's off for better detection
  2708. light_was_off = False
  2709. client = printer_manager.get_client(printer_id)
  2710. if client and client.state:
  2711. light_was_off = not client.state.chamber_light
  2712. if light_was_off:
  2713. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  2714. client.set_chamber_light(True)
  2715. # Wait for light to physically turn on and camera to adjust exposure
  2716. await asyncio.sleep(2.5)
  2717. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  2718. plate_result = await check_plate_empty(
  2719. printer_id=printer_id,
  2720. ip_address=printer.ip_address,
  2721. access_code=printer.access_code,
  2722. model=printer.model,
  2723. include_debug_image=False,
  2724. external_camera_url=printer.external_camera_url,
  2725. external_camera_type=printer.external_camera_type,
  2726. use_external=printer.external_camera_enabled,
  2727. roi=roi,
  2728. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  2729. )
  2730. # Restore chamber light to original state
  2731. if light_was_off and client:
  2732. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  2733. client.set_chamber_light(False)
  2734. if not plate_result.needs_calibration and not plate_result.is_empty:
  2735. # Objects detected - pause the print!
  2736. logger.warning(
  2737. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  2738. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  2739. )
  2740. client = printer_manager.get_client(printer_id)
  2741. if client:
  2742. client.pause_print()
  2743. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  2744. # Send notification about plate not empty
  2745. await ws_manager.broadcast(
  2746. {
  2747. "type": "plate_not_empty",
  2748. "printer_id": printer_id,
  2749. "printer_name": printer.name,
  2750. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  2751. }
  2752. )
  2753. # Also send push notification
  2754. try:
  2755. await notification_service.on_plate_not_empty(
  2756. printer_id=printer_id,
  2757. printer_name=printer.name,
  2758. db=db,
  2759. difference_percent=plate_result.difference_percent,
  2760. )
  2761. except Exception as notif_err:
  2762. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  2763. else:
  2764. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  2765. except Exception as plate_err:
  2766. # Don't block print on plate detection errors
  2767. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  2768. if not printer:
  2769. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  2770. if not notification_sent:
  2771. await _send_print_start_notification(printer_id, data, logger=logger)
  2772. return
  2773. if not printer.auto_archive:
  2774. # auto-archive disabled — check if there's an expected print (dispatched
  2775. # by BamBuddy via queue/reprint) that already has an archive to promote.
  2776. # If so, fall through to the expected-print handling below so the archive
  2777. # is tracked in _active_prints and usage tracking works at completion.
  2778. _fn = data.get("filename", "")
  2779. _sn = data.get("subtask_name", "")
  2780. _check_keys: list[tuple[int, str]] = []
  2781. if _sn:
  2782. _check_keys += [
  2783. (printer_id, _sn),
  2784. (printer_id, f"{_sn}.3mf"),
  2785. (printer_id, f"{_sn}.gcode.3mf"),
  2786. ]
  2787. if _fn:
  2788. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  2789. _check_keys.append((printer_id, _base_fn))
  2790. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  2791. _check_keys += [
  2792. (printer_id, _no_archive_base),
  2793. (printer_id, f"{_no_archive_base}.3mf"),
  2794. ]
  2795. _has_expected = any(k in _expected_prints for k in _check_keys)
  2796. if not _has_expected:
  2797. # No expected print — truly external print (started from slicer/touchscreen)
  2798. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  2799. if not notification_sent:
  2800. _no_archive_creator: int | None = None
  2801. for _key in _check_keys:
  2802. _expected_prints.pop(_key, None)
  2803. _expected_print_registered_at.pop(_key, None)
  2804. popped_creator = _expected_print_creators.pop(_key, None)
  2805. if _no_archive_creator is None:
  2806. _no_archive_creator = popped_creator
  2807. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  2808. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  2809. return
  2810. else:
  2811. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  2812. # Get the filename and subtask_name
  2813. filename = data.get("filename", "")
  2814. subtask_name = data.get("subtask_name", "")
  2815. # MQTT subtask_id uniquely identifies a print job on the printer. When
  2816. # present, it lets us match an archive across a backend restart (#972):
  2817. # same id → same print → resume the existing row instead of cancelling
  2818. # it and recreating from scratch (which loses started_at). Treat "0"
  2819. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  2820. raw_mqtt = data.get("raw_data") or {}
  2821. subtask_id = raw_mqtt.get("subtask_id")
  2822. if subtask_id is not None:
  2823. subtask_id = str(subtask_id).strip()
  2824. if subtask_id in ("", "0"):
  2825. subtask_id = None
  2826. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  2827. # Skip the printer's own jobs — a calibration run is not a user's print.
  2828. # See is_internal_printer_job for what counts and why both fields are
  2829. # tested; the pressure-advance line reports as a subtask name with no
  2830. # /usr/ path, which the old prefix-only test here missed entirely.
  2831. #
  2832. # No notification either. The event describes the printer calibrating
  2833. # itself, so "Print started" is as wrong as the archive was, and the
  2834. # matching completion is suppressed in on_print_complete for the same
  2835. # reason.
  2836. if is_internal_printer_job(filename, subtask_name):
  2837. logger.info(
  2838. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  2839. filename,
  2840. subtask_name,
  2841. )
  2842. return
  2843. if not filename and not subtask_name:
  2844. # Send notification without archive data (no filename)
  2845. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  2846. if not notification_sent:
  2847. await _send_print_start_notification(printer_id, data, logger=logger)
  2848. return
  2849. # Check if this is an expected print from reprint/scheduled
  2850. # Build list of possible keys to check
  2851. expected_keys = []
  2852. if subtask_name:
  2853. expected_keys.append((printer_id, subtask_name))
  2854. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  2855. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  2856. if filename:
  2857. fname = filename.split("/")[-1] if "/" in filename else filename
  2858. expected_keys.append((printer_id, fname))
  2859. # Strip extensions to match
  2860. base = fname.replace(".gcode", "").replace(".3mf", "")
  2861. expected_keys.append((printer_id, base))
  2862. expected_keys.append((printer_id, f"{base}.3mf"))
  2863. expected_archive_id = None
  2864. for key in expected_keys:
  2865. expected_archive_id = _expected_prints.pop(key, None)
  2866. _expected_print_registered_at.pop(key, None)
  2867. if expected_archive_id:
  2868. # Clean up other possible keys for this print
  2869. for other_key in expected_keys:
  2870. _expected_prints.pop(other_key, None)
  2871. _expected_print_registered_at.pop(other_key, None)
  2872. break
  2873. if expected_archive_id:
  2874. # This is a reprint/scheduled print - use existing archive, don't create new one
  2875. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  2876. from backend.app.models.archive import PrintArchive
  2877. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  2878. archive = result.scalar_one_or_none()
  2879. if archive:
  2880. # Update archive status to printing
  2881. archive.status = "printing"
  2882. archive.started_at = datetime.now(timezone.utc)
  2883. # Reprint of an archive reuses the source row. Without resetting
  2884. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  2885. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  2886. # extracts the *original* print's last frame, which then ships in
  2887. # the completion notification (#1707). Clear the path so the
  2888. # scanner runs fresh; also unlink the old video file so reprints
  2889. # don't accumulate orphans in the archive directory. Photos list
  2890. # is left alone — accumulating one finish photo per run is fine.
  2891. # The print-start baseline (#2704) is stale for the same reason:
  2892. # it describes the printer before the previous run. The capture
  2893. # below overwrites it, but clear it here too so an early failure
  2894. # can't leave the scan diffing against the wrong snapshot.
  2895. archive.timelapse_baseline = None
  2896. stale_timelapse_relpath = archive.timelapse_path
  2897. if stale_timelapse_relpath:
  2898. archive.timelapse_path = None
  2899. try:
  2900. stale_path = app_settings.base_dir / stale_timelapse_relpath
  2901. if stale_path.is_file():
  2902. stale_path.unlink()
  2903. logger.info(
  2904. "Deleted stale timelapse %s on reprint of archive %s",
  2905. stale_timelapse_relpath,
  2906. expected_archive_id,
  2907. )
  2908. except OSError as e:
  2909. logger.warning(
  2910. "Failed to delete stale timelapse %s on reprint: %s",
  2911. stale_timelapse_relpath,
  2912. e,
  2913. )
  2914. # Persist a restart-stable id so a later restart resumes this
  2915. # archive by subtask_id instead of name-matching + duplicating
  2916. # it (#1485). The printer often hasn't echoed subtask_id back
  2917. # this soon after dispatch, so fall back to the id Bambuddy
  2918. # minted when it sent the print command. Scoped to this
  2919. # expected-print branch on purpose: an expected match means
  2920. # Bambuddy dispatched this exact print in this process, so the
  2921. # client's last-dispatch id genuinely belongs to it — using it
  2922. # for an externally-started print could mis-tag the archive.
  2923. effective_subtask_id = subtask_id
  2924. if not effective_subtask_id:
  2925. _client = printer_manager.get_client(printer_id)
  2926. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  2927. if _dispatched:
  2928. effective_subtask_id = str(_dispatched).strip() or None
  2929. # Update on first-set OR on reprint (the queue dispatcher mints
  2930. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  2931. # the rewrite for reprints leaves the archive holding the FIRST
  2932. # run's id; if MQTT then reconnects mid-print, the reconciler
  2933. # (#1542) compares the stale stored id against the printer's
  2934. # live id, sees a mismatch, and synthesises a bogus PRINT
  2935. # COMPLETE — exactly the false-positive "Print Stopped" reported
  2936. # in #1807. Inequality check preserves the noop-on-stable-push
  2937. # behaviour the earlier `not archive.subtask_id` guard provided.
  2938. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  2939. archive.subtask_id = effective_subtask_id
  2940. # #1403 follow-up: VP-queue archives are created with
  2941. # printer_id=None at queue-add time (we don't know which
  2942. # printer will run the job yet). When the print actually
  2943. # starts on a specific printer the expected-archive lookup
  2944. # used to skip this assignment, leaving printer_id=None
  2945. # forever — which then disables the "Scan for timelapse"
  2946. # button in ArchivesPage (gated on !archive.printer_id).
  2947. if archive.printer_id != printer_id:
  2948. archive.printer_id = printer_id
  2949. await db.commit()
  2950. # Track as active print
  2951. _active_prints[(printer_id, archive.filename)] = archive.id
  2952. if subtask_name:
  2953. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  2954. # Start timelapse session if external camera is enabled (#1353).
  2955. # Queue / VP-dispatched prints land here in the expected-archive
  2956. # branch and used to skip start_session entirely — frames were
  2957. # never captured and the post-print stitch silently returned None.
  2958. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  2959. # Inject ams_mapping into usage tracker session — the session was created
  2960. # before expected-print promotion, so it may have ams_mapping=None when
  2961. # the MQTT request topic subscription failed (common on P1S/A1).
  2962. _stored_map = _print_ams_mappings.get(expected_archive_id)
  2963. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  2964. if _stored_map or _stored_plate_id is not None:
  2965. try:
  2966. from backend.app.services.usage_tracker import _active_sessions
  2967. _ut_session = _active_sessions.get(printer_id)
  2968. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  2969. _ut_session.ams_mapping = _stored_map
  2970. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  2971. # plate_id injection covers direct-Print of plate N of a multi-plate
  2972. # 3MF — queue prints already capture it via the on_print_start queue
  2973. # lookup, but direct-Print never goes through the queue (#1697).
  2974. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  2975. _ut_session.plate_id = _stored_plate_id
  2976. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  2977. except Exception:
  2978. pass
  2979. # Set up energy tracking (#941: persist start on archive row)
  2980. await _record_energy_start(archive, printer_id, db, context="expected-print")
  2981. await ws_manager.send_archive_updated(
  2982. {
  2983. "id": archive.id,
  2984. "status": "printing",
  2985. }
  2986. )
  2987. # Send notification with archive data (reprint/scheduled)
  2988. if not notification_sent:
  2989. # Use archive's created_by_id; fall back to the creator registered via
  2990. # register_expected_print (handles library-file-based queue items where
  2991. # the freshly-created archive has no created_by_id yet).
  2992. # Pop ALL matching keys so no stale entries remain in the dict.
  2993. fallback_creator = None
  2994. for key in expected_keys:
  2995. popped = _expected_print_creators.pop(key, None)
  2996. if fallback_creator is None:
  2997. fallback_creator = popped
  2998. archive_data = {
  2999. "print_time_seconds": archive.print_time_seconds,
  3000. "created_by_id": archive.created_by_id or fallback_creator,
  3001. }
  3002. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3003. # Extract printable objects from the archived 3MF file
  3004. _load_objects_from_archive(archive, printer_id, logger)
  3005. # Store Spoolman tracking data for per-filament usage reporting
  3006. try:
  3007. await _store_spoolman_print_data(
  3008. printer_id,
  3009. archive.id,
  3010. archive.file_path,
  3011. db,
  3012. printer_manager,
  3013. ams_mapping=_get_start_ams_mapping(data, archive.id),
  3014. plate_id=_get_start_plate_id(archive.id),
  3015. )
  3016. except Exception as e:
  3017. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  3018. # Capture timelapse file baseline for snapshot-diff on completion
  3019. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  3020. # hit this branch — without the baseline the completion-time scan
  3021. # falls into its "take baseline now" fallback, which snapshots
  3022. # AFTER the new MP4 already exists and never matches a diff
  3023. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  3024. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  3025. return # Skip creating a new archive
  3026. # Check if there's already a "printing" archive for this printer/file
  3027. # This prevents duplicates when backend restarts during an active print
  3028. from backend.app.models.archive import PrintArchive
  3029. existing_archive: PrintArchive | None = None
  3030. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  3031. # across a backend restart for the same print, so this is the most
  3032. # reliable way to reattach. We also accept a previously stale-cancelled
  3033. # archive here so users upgrading mid-print get revived when the row
  3034. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  3035. if subtask_id:
  3036. by_id = await db.execute(
  3037. select(PrintArchive)
  3038. .where(PrintArchive.printer_id == printer_id)
  3039. .where(PrintArchive.subtask_id == subtask_id)
  3040. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  3041. .order_by(PrintArchive.created_at.desc())
  3042. .limit(1)
  3043. )
  3044. candidate = by_id.scalar_one_or_none()
  3045. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  3046. existing_archive = candidate
  3047. # Fallback match: name-based lookup. Kept as-is for prints whose
  3048. # subtask_id is missing ("0" / local / non-cloud prints).
  3049. if existing_archive is None:
  3050. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  3051. existing = await db.execute(
  3052. select(PrintArchive)
  3053. .where(PrintArchive.printer_id == printer_id)
  3054. .where(PrintArchive.status == "printing")
  3055. .where(
  3056. or_(
  3057. PrintArchive.print_name == check_name,
  3058. PrintArchive.filename.in_(
  3059. [
  3060. f"{check_name}.3mf",
  3061. f"{check_name}.gcode.3mf",
  3062. ]
  3063. ),
  3064. )
  3065. )
  3066. .order_by(PrintArchive.created_at.desc())
  3067. .limit(1)
  3068. )
  3069. existing_archive = existing.scalar_one_or_none()
  3070. if existing_archive:
  3071. # subtask_id match → always resume, regardless of age. Same print,
  3072. # just a backend restart. Revive if it was previously stale-cancelled.
  3073. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  3074. if subtask_match:
  3075. if existing_archive.status == "cancelled":
  3076. logger.warning(
  3077. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  3078. existing_archive.id,
  3079. subtask_id,
  3080. )
  3081. existing_archive.status = "printing"
  3082. existing_archive.failure_reason = None
  3083. await db.commit()
  3084. else:
  3085. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  3086. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  3087. if existing_archive.energy_start_kwh is None:
  3088. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  3089. if not notification_sent:
  3090. archive_data = {
  3091. "print_time_seconds": existing_archive.print_time_seconds,
  3092. "created_by_id": existing_archive.created_by_id,
  3093. }
  3094. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3095. _load_objects_from_archive(existing_archive, printer_id, logger)
  3096. return
  3097. # Name-match only (no subtask_id to anchor on): decide resume vs.
  3098. # stale from the printer's *current* progress, not wall-clock age.
  3099. # A genuinely long print used to trip a blind 4h cutoff and have its
  3100. # live archive cancelled + duplicated on every backend restart
  3101. # (#1485). If the printer reports real progress, this name-matched
  3102. # 'printing' archive IS that ongoing print — resume it whatever its
  3103. # age. Only treat it as a stale leftover when the printer clearly
  3104. # shows a different, freshly-started print: near-0% progress on an
  3105. # archive far too old to still be at 0%. Unknown progress (printer
  3106. # not connected) never cancels — resuming is the safe default.
  3107. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  3108. live_status = printer_manager.get_status(printer_id)
  3109. live_progress = getattr(live_status, "progress", None) if live_status else None
  3110. looks_stale = (
  3111. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  3112. )
  3113. if looks_stale:
  3114. logger.warning(
  3115. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}, "
  3116. f"printer progress {live_progress:.0f}%) — marking cancelled and creating new archive"
  3117. )
  3118. existing_archive.status = "cancelled"
  3119. existing_archive.failure_reason = "Stale - print likely cancelled or failed without status update"
  3120. await db.commit()
  3121. # Fall through to create new archive (don't return)
  3122. else:
  3123. logger.info(
  3124. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  3125. )
  3126. # Track this as the active print
  3127. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  3128. # Attach subtask_id retroactively so future restarts can resume.
  3129. # Compare for inequality (not "is empty") to also pick up reprint
  3130. # dispatches that mint a fresh id — see #1807 for the bogus
  3131. # "Print Stopped" the strict-empty guard caused on reconnect.
  3132. if subtask_id and existing_archive.subtask_id != subtask_id:
  3133. existing_archive.subtask_id = subtask_id
  3134. await db.commit()
  3135. # Also set up energy tracking if not already tracked (#941: persisted column)
  3136. if existing_archive.energy_start_kwh is None:
  3137. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  3138. # Send notification with archive data (existing archive)
  3139. if not notification_sent:
  3140. archive_data = {
  3141. "print_time_seconds": existing_archive.print_time_seconds,
  3142. "created_by_id": existing_archive.created_by_id,
  3143. }
  3144. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3145. # Extract printable objects from the archived 3MF file
  3146. _load_objects_from_archive(existing_archive, printer_id, logger)
  3147. return
  3148. # Build list of possible 3MF filenames to try
  3149. possible_names = []
  3150. # Bambu printers typically store files as "Name.gcode.3mf"
  3151. # The subtask_name is usually the best source for the filename
  3152. if subtask_name:
  3153. # Try common Bambu naming patterns
  3154. possible_names.append(f"{subtask_name}.gcode.3mf")
  3155. possible_names.append(f"{subtask_name}.3mf")
  3156. # Try original filename with .3mf extension
  3157. if filename:
  3158. # Extract just the filename part, not the full path
  3159. fname = filename.split("/")[-1] if "/" in filename else filename
  3160. if fname.endswith(".3mf"):
  3161. possible_names.append(fname)
  3162. elif fname.endswith(".gcode"):
  3163. base = fname.rsplit(".", 1)[0]
  3164. possible_names.append(f"{base}.gcode.3mf")
  3165. possible_names.append(f"{base}.3mf")
  3166. else:
  3167. possible_names.append(f"{fname}.gcode.3mf")
  3168. possible_names.append(f"{fname}.3mf")
  3169. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  3170. space_variants = []
  3171. for name in possible_names:
  3172. if " " in name:
  3173. space_variants.append(name.replace(" ", "_"))
  3174. possible_names.extend(space_variants)
  3175. # Remove duplicates while preserving order
  3176. seen = set()
  3177. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  3178. logger.info("Trying filenames: %s", possible_names)
  3179. # Release the pooled DB connection before the 3MF FTP download. Reaching
  3180. # here means none of the expected-/existing-archive write branches ran
  3181. # (they all return earlier) — only SELECTs have executed on this path, so
  3182. # this commit persists nothing; it ends the read transaction so the
  3183. # connection returns to the pool during the download. That download tries
  3184. # up to five remote paths per candidate filename with retry/backoff and
  3185. # can run for minutes under FTP contention; holding the session across it
  3186. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  3187. # work runs during the download — the new-archive writes below re-acquire
  3188. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  3189. await db.commit()
  3190. # Try to find and download the 3MF file
  3191. temp_path = None
  3192. downloaded_filename = None
  3193. # Cache check: cover endpoint may have already pulled this 3MF during
  3194. # the print (frontend opens the card and shows the thumbnail) — reuse
  3195. # that file instead of re-downloading 36MB over the same FTP link that
  3196. # just served it (#972). The cache keys on a normalized filename so
  3197. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  3198. for try_filename in possible_names:
  3199. if not try_filename.endswith(".3mf"):
  3200. continue
  3201. cached = get_cached_3mf(printer_id, try_filename)
  3202. if cached:
  3203. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  3204. temp_path = cached
  3205. downloaded_filename = try_filename
  3206. break
  3207. # Does this printer keep the sliced file somewhere FTPS can reach? On
  3208. # H2-series and P2S the answer is routinely no — the file stays on
  3209. # internal eMMC and port 990 only ever serves external storage — and
  3210. # then the whole sweep below (six filenames x five directories x four
  3211. # retries, then the directory walk) is ~110 connections that cannot
  3212. # succeed. Skip it and say why (#2780).
  3213. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  3214. # Get FTP retry settings
  3215. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  3216. # ...but "the printer put it on eMMC" is where it went, not whether we
  3217. # can read it. An H2D with a card in mirrors the job to /cache and
  3218. # serves it happily, and skipping on the URL alone cost that reporter
  3219. # every archive for two days (#2856). So ask the printer instead of
  3220. # guessing: the dispatch named the exact file, which is one connection
  3221. # walking five paths rather than the sweep's ~110. Only when the probe
  3222. # comes back empty does the verdict's reason stand.
  3223. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  3224. if ftps_handshake_blocked(printer.ip_address):
  3225. logger.debug(
  3226. "Not probing for %s on printer %s: its file service is not answering over TLS",
  3227. storage.probe_filename,
  3228. printer_id,
  3229. )
  3230. else:
  3231. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  3232. probe_path.parent.mkdir(parents=True, exist_ok=True)
  3233. try:
  3234. probe_hit = await download_file_try_paths_async(
  3235. printer.ip_address,
  3236. printer.access_code,
  3237. ftp_probe_paths(storage.probe_filename),
  3238. probe_path,
  3239. socket_timeout=ftp_timeout,
  3240. printer_model=printer.model,
  3241. )
  3242. except Exception as e:
  3243. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  3244. probe_hit = False
  3245. if probe_hit:
  3246. downloaded_filename = storage.probe_filename
  3247. temp_path = probe_path
  3248. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  3249. # Naming the path, not just the file: a printer that keeps
  3250. # uploads around for weeks can serve a same-named copy of an
  3251. # earlier slice, and without the directory in the log that
  3252. # mismatch is invisible rather than merely rare (#1820).
  3253. logger.info(
  3254. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  3255. downloaded_filename,
  3256. probe_hit,
  3257. printer_id,
  3258. storage.reason,
  3259. )
  3260. if not storage.reachable and not downloaded_filename:
  3261. # Same opening words whether or not a probe ran, because that is
  3262. # the phrase support asks people to grep for — only the tail says
  3263. # which of the two happened.
  3264. logger.info(
  3265. "Skipping the 3MF lookup for printer %s: %s — %s",
  3266. printer_id,
  3267. storage.reason,
  3268. "no copy of it on external storage either"
  3269. if storage.probe_filename
  3270. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  3271. )
  3272. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  3273. if not try_filename.endswith(".3mf"):
  3274. continue
  3275. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  3276. # printers, so try it first — deferring it to last cost #972's reporter
  3277. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  3278. # landing on the path that actually had the file.
  3279. remote_paths = [
  3280. f"/{try_filename}",
  3281. f"/cache/{try_filename}",
  3282. f"/model/{try_filename}",
  3283. f"/data/{try_filename}",
  3284. f"/data/Metadata/{try_filename}",
  3285. ]
  3286. temp_path = app_settings.archive_dir / "temp" / try_filename
  3287. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3288. for remote_path in remote_paths:
  3289. if ftps_handshake_blocked(printer.ip_address):
  3290. # The printer's FTPS service is not completing a TLS
  3291. # handshake, so it has no path we could reach — walking the
  3292. # remaining candidates only re-runs the same failure
  3293. # (#2780). Fall through to the no-3MF archive now.
  3294. logger.warning(
  3295. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  3296. printer_id,
  3297. )
  3298. break
  3299. logger.debug("Trying FTP download: %s", remote_path)
  3300. try:
  3301. if ftp_retry_enabled:
  3302. downloaded = await with_ftp_retry(
  3303. download_file_async,
  3304. printer.ip_address,
  3305. printer.access_code,
  3306. remote_path,
  3307. temp_path,
  3308. timeout=ftp_timeout,
  3309. socket_timeout=ftp_timeout,
  3310. printer_model=printer.model,
  3311. max_retries=ftp_retry_count,
  3312. retry_delay=ftp_retry_delay,
  3313. operation_name=f"Download 3MF from {remote_path}",
  3314. non_retry_exceptions=(FileNotOnPrinterError,),
  3315. )
  3316. else:
  3317. downloaded = await download_file_async(
  3318. printer.ip_address,
  3319. printer.access_code,
  3320. remote_path,
  3321. temp_path,
  3322. timeout=ftp_timeout,
  3323. socket_timeout=ftp_timeout,
  3324. printer_model=printer.model,
  3325. )
  3326. if downloaded:
  3327. downloaded_filename = try_filename
  3328. logger.info("Downloaded: %s", remote_path)
  3329. # Populate shared cache so the cover endpoint (if it
  3330. # runs next) doesn't refetch the same 36MB over FTP.
  3331. cache_3mf_download(printer_id, try_filename, temp_path)
  3332. break
  3333. except FileNotOnPrinterError:
  3334. # 550 — file isn't at this path. Advance to next candidate
  3335. # without burning the retry budget.
  3336. logger.debug("3MF not at %s (550), trying next path", remote_path)
  3337. except Exception as e:
  3338. logger.debug("FTP download failed for %s: %s", remote_path, e)
  3339. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  3340. break
  3341. # If still not found, try listing directories to find matching file
  3342. # Different printer models use different directory structures. Skipped
  3343. # when the printer's FTPS handshake is failing — the directory walk is
  3344. # five more connections that cannot get further than the download did.
  3345. if (
  3346. not downloaded_filename
  3347. and storage.reachable
  3348. and (filename or subtask_name)
  3349. and not ftps_handshake_blocked(printer.ip_address)
  3350. ):
  3351. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  3352. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  3353. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  3354. for search_dir in search_dirs:
  3355. if downloaded_filename:
  3356. break
  3357. try:
  3358. dir_files = await list_files_async(
  3359. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  3360. )
  3361. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  3362. if threemf_files:
  3363. logger.info(
  3364. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  3365. )
  3366. for f in dir_files:
  3367. if f.get("is_directory"):
  3368. continue
  3369. fname = f.get("name", "")
  3370. # Normalize both for comparison (spaces and underscores are equivalent)
  3371. fname_normalized = fname.lower().replace(" ", "_")
  3372. search_normalized = search_term.replace(" ", "_")
  3373. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  3374. logger.info("Found matching file in %s: %s", search_dir, fname)
  3375. temp_path = app_settings.archive_dir / "temp" / fname
  3376. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3377. remote_full_path = posixpath.join(search_dir, fname)
  3378. if ftp_retry_enabled:
  3379. downloaded = await with_ftp_retry(
  3380. download_file_async,
  3381. printer.ip_address,
  3382. printer.access_code,
  3383. remote_full_path,
  3384. temp_path,
  3385. timeout=ftp_timeout,
  3386. socket_timeout=ftp_timeout,
  3387. printer_model=printer.model,
  3388. max_retries=ftp_retry_count,
  3389. retry_delay=ftp_retry_delay,
  3390. operation_name=f"Download 3MF from {remote_full_path}",
  3391. )
  3392. else:
  3393. downloaded = await download_file_async(
  3394. printer.ip_address,
  3395. printer.access_code,
  3396. remote_full_path,
  3397. temp_path,
  3398. timeout=ftp_timeout,
  3399. socket_timeout=ftp_timeout,
  3400. printer_model=printer.model,
  3401. )
  3402. if downloaded:
  3403. downloaded_filename = fname
  3404. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  3405. cache_3mf_download(printer_id, fname, temp_path)
  3406. break
  3407. except Exception as e:
  3408. logger.debug("Failed to list %s: %s", search_dir, e)
  3409. # Validate the downloaded 3MF actually matches the plate that's running
  3410. # (#1204): subtask_name lags across consecutive plates of the same model,
  3411. # so the first FTP candidate (built from subtask_name) can land on the
  3412. # previous plate's still-resident upload. Cross-check the slice_info
  3413. # plate index against the plate parsed from gcode_file (always fresh —
  3414. # it's the field whose change triggered this callback).
  3415. if downloaded_filename and temp_path:
  3416. expected_plate = parse_plate_id(filename)
  3417. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  3418. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  3419. logger.warning(
  3420. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  3421. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  3422. downloaded_filename,
  3423. actual_plate,
  3424. expected_plate,
  3425. subtask_name,
  3426. )
  3427. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  3428. retry_succeeded = False
  3429. if corrected_subtask and corrected_subtask != subtask_name:
  3430. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  3431. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  3432. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  3433. for remote_path in (
  3434. f"/{try_filename}",
  3435. f"/cache/{try_filename}",
  3436. f"/model/{try_filename}",
  3437. f"/data/{try_filename}",
  3438. f"/data/Metadata/{try_filename}",
  3439. ):
  3440. try:
  3441. if ftp_retry_enabled:
  3442. downloaded = await with_ftp_retry(
  3443. download_file_async,
  3444. printer.ip_address,
  3445. printer.access_code,
  3446. remote_path,
  3447. retry_temp_path,
  3448. timeout=ftp_timeout,
  3449. socket_timeout=ftp_timeout,
  3450. printer_model=printer.model,
  3451. max_retries=ftp_retry_count,
  3452. retry_delay=ftp_retry_delay,
  3453. operation_name=f"Re-download 3MF from {remote_path}",
  3454. non_retry_exceptions=(FileNotOnPrinterError,),
  3455. )
  3456. else:
  3457. downloaded = await download_file_async(
  3458. printer.ip_address,
  3459. printer.access_code,
  3460. remote_path,
  3461. retry_temp_path,
  3462. timeout=ftp_timeout,
  3463. socket_timeout=ftp_timeout,
  3464. printer_model=printer.model,
  3465. )
  3466. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  3467. logger.info(
  3468. "[CALLBACK] Re-download succeeded with corrected name %s "
  3469. "(plate %s) — replacing wrong file",
  3470. try_filename,
  3471. expected_plate,
  3472. )
  3473. try:
  3474. temp_path.unlink(missing_ok=True)
  3475. except OSError:
  3476. pass
  3477. temp_path = retry_temp_path
  3478. downloaded_filename = try_filename
  3479. subtask_name = corrected_subtask
  3480. cache_3mf_download(printer_id, try_filename, temp_path)
  3481. retry_succeeded = True
  3482. break
  3483. elif downloaded:
  3484. # Wrong plate again — discard and keep trying
  3485. try:
  3486. retry_temp_path.unlink(missing_ok=True)
  3487. except OSError:
  3488. pass
  3489. except FileNotOnPrinterError:
  3490. continue
  3491. except Exception as e:
  3492. logger.debug("Re-download failed for %s: %s", remote_path, e)
  3493. if retry_succeeded:
  3494. break
  3495. # If the retry didn't find a matching file, drop the wrong 3MF
  3496. # so the no-3MF fallback below creates an archive whose name
  3497. # at least reflects the right plate.
  3498. if not retry_succeeded:
  3499. logger.warning(
  3500. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  3501. expected_plate,
  3502. )
  3503. try:
  3504. temp_path.unlink(missing_ok=True)
  3505. except OSError:
  3506. pass
  3507. temp_path = None
  3508. downloaded_filename = None
  3509. # Override the stale subtask_name so the fallback archive's
  3510. # print_name reflects the correct plate. Prefer the swapped
  3511. # name when we have one; otherwise let filename win.
  3512. if corrected_subtask:
  3513. subtask_name = corrected_subtask
  3514. else:
  3515. subtask_name = ""
  3516. if not downloaded_filename or not temp_path:
  3517. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  3518. # Create a fallback archive without 3MF data so the print is still tracked
  3519. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  3520. try:
  3521. from backend.app.models.archive import PrintArchive
  3522. # Derive print name from subtask_name or filename
  3523. print_name = subtask_name or filename
  3524. if print_name:
  3525. # Clean up the name (remove extensions, path parts)
  3526. print_name = print_name.split("/")[-1]
  3527. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  3528. else:
  3529. print_name = "Unknown Print"
  3530. # Recover estimated print time from MQTT (best-effort for notifications)
  3531. fallback_print_time = None
  3532. mqtt_remaining = data.get("remaining_time")
  3533. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  3534. fallback_print_time = int(mqtt_remaining)
  3535. if fallback_print_time is None:
  3536. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  3537. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  3538. fallback_print_time = int(mc_remaining * 60)
  3539. # Best-effort filament metadata from MQTT — see
  3540. # _extract_filament_data_from_mqtt. Without this the fallback
  3541. # archive's filament fields stayed NULL even though the AMS
  3542. # state at print start was sitting right there in `data`.
  3543. # The slicer's ams_mapping (when present) narrows the result
  3544. # to slots actually used by the print (#1533).
  3545. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  3546. # Create minimal archive entry
  3547. fallback_archive = PrintArchive(
  3548. printer_id=printer_id,
  3549. filename=filename or f"{print_name}.3mf",
  3550. file_path="", # Empty - no 3MF file available
  3551. file_size=0,
  3552. print_name=print_name,
  3553. print_time_seconds=fallback_print_time,
  3554. status="printing",
  3555. started_at=datetime.now(timezone.utc),
  3556. subtask_id=subtask_id,
  3557. filament_type=mqtt_filament_meta.get("filament_type"),
  3558. filament_color=mqtt_filament_meta.get("filament_color"),
  3559. extra_data={
  3560. "no_3mf_available": True,
  3561. # Why the card is empty, when we know. The banner reads
  3562. # this to stop telling H2/P2 owners to switch on a
  3563. # setting that is already on and would not help (#2780).
  3564. "no_3mf_reason": storage.reason,
  3565. "original_subtask": subtask_name,
  3566. "_print_data": data,
  3567. },
  3568. )
  3569. db.add(fallback_archive)
  3570. await db.commit()
  3571. await db.refresh(fallback_archive)
  3572. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  3573. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  3574. # Track as active print
  3575. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  3576. if filename:
  3577. _active_prints[(printer_id, filename)] = fallback_archive.id
  3578. if subtask_name:
  3579. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  3580. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  3581. # Record starting energy if smart plug available (#941: persisted column)
  3582. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  3583. # Send WebSocket notification
  3584. await ws_manager.send_archive_created(
  3585. {
  3586. "id": fallback_archive.id,
  3587. "printer_id": fallback_archive.printer_id,
  3588. "filename": fallback_archive.filename,
  3589. "print_name": fallback_archive.print_name,
  3590. "status": fallback_archive.status,
  3591. }
  3592. )
  3593. # MQTT relay - publish archive created
  3594. try:
  3595. await mqtt_relay.on_archive_created(
  3596. archive_id=fallback_archive.id,
  3597. print_name=fallback_archive.print_name,
  3598. printer_name=printer.name,
  3599. status=fallback_archive.status,
  3600. )
  3601. except Exception:
  3602. pass # Don't fail if MQTT fails
  3603. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  3604. try:
  3605. await _store_spoolman_print_data(
  3606. printer_id,
  3607. fallback_archive.id,
  3608. fallback_archive.file_path,
  3609. db,
  3610. printer_manager,
  3611. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  3612. plate_id=_get_start_plate_id(fallback_archive.id),
  3613. )
  3614. except Exception as e:
  3615. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  3616. # Send notification without archive data (file not found)
  3617. if not notification_sent:
  3618. await _send_print_start_notification(printer_id, data, logger=logger)
  3619. return
  3620. except Exception as e:
  3621. logger.error("Failed to create fallback archive: %s", e)
  3622. # Send notification without archive data (file not found)
  3623. if not notification_sent:
  3624. await _send_print_start_notification(printer_id, data, logger=logger)
  3625. return
  3626. try:
  3627. # Archive the file with status "printing"
  3628. service = ArchiveService(db)
  3629. archive = await service.archive_print(
  3630. printer_id=printer_id,
  3631. source_file=temp_path,
  3632. print_data={**data, "status": "printing"},
  3633. subtask_id=subtask_id,
  3634. )
  3635. if archive:
  3636. # Track this active print (use both original filename and downloaded filename)
  3637. _active_prints[(printer_id, downloaded_filename)] = archive.id
  3638. if filename and filename != downloaded_filename:
  3639. _active_prints[(printer_id, filename)] = archive.id
  3640. if subtask_name:
  3641. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  3642. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  3643. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  3644. # Record starting energy from smart plug if available (#941: persisted column)
  3645. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  3646. await ws_manager.send_archive_created(
  3647. {
  3648. "id": archive.id,
  3649. "printer_id": archive.printer_id,
  3650. "filename": archive.filename,
  3651. "print_name": archive.print_name,
  3652. "status": archive.status,
  3653. }
  3654. )
  3655. # MQTT relay - publish archive created
  3656. try:
  3657. await mqtt_relay.on_archive_created(
  3658. archive_id=archive.id,
  3659. print_name=archive.print_name,
  3660. printer_name=printer.name,
  3661. status=archive.status,
  3662. )
  3663. except Exception:
  3664. pass # Don't fail if MQTT fails
  3665. # Send notification with archive data (new archive created)
  3666. if not notification_sent:
  3667. archive_data = {
  3668. "print_time_seconds": archive.print_time_seconds,
  3669. "created_by_id": archive.created_by_id,
  3670. }
  3671. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3672. # Extract printable objects for skip object functionality
  3673. try:
  3674. from backend.app.services.archive import extract_printable_objects_from_3mf
  3675. client = printer_manager.get_client(printer_id)
  3676. if client:
  3677. with open(temp_path, "rb") as f:
  3678. threemf_data = f.read()
  3679. # Extract with positions for UI overlay, scoped to the
  3680. # plate that is printing — an all-plates 3MF carries
  3681. # every plate's objects (#2522).
  3682. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  3683. threemf_data,
  3684. plate_number=resolve_plate_id(client.state),
  3685. include_positions=True,
  3686. )
  3687. if printable_objects:
  3688. # Store objects in printer state
  3689. client.state.printable_objects = printable_objects
  3690. client.state.printable_objects_bbox_all = bbox_all
  3691. client.state.skipped_objects = [] # Reset skipped objects for new print
  3692. logger.info(
  3693. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  3694. )
  3695. except Exception as e:
  3696. logger.debug("Failed to extract printable objects: %s", e)
  3697. # Store Spoolman tracking data for per-filament usage reporting
  3698. try:
  3699. await _store_spoolman_print_data(
  3700. printer_id,
  3701. archive.id,
  3702. archive.file_path,
  3703. db,
  3704. printer_manager,
  3705. ams_mapping=_get_start_ams_mapping(data, archive.id),
  3706. plate_id=_get_start_plate_id(archive.id),
  3707. )
  3708. except Exception as e:
  3709. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  3710. # Capture timelapse file baseline for snapshot-diff on completion
  3711. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  3712. finally:
  3713. # Keep temp_path around until print completes so the cover endpoint
  3714. # can reuse it (#972). Cache eviction in on_print_complete deletes
  3715. # the file. If the cache entry was evicted early (file vanished),
  3716. # clean up any stragglers here to avoid leaking disk on retries.
  3717. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  3718. if temp_path and temp_path.exists() and cached_now != temp_path:
  3719. temp_path.unlink()
  3720. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  3721. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  3722. # tests can shrink them without waiting out real delays.
  3723. #
  3724. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  3725. # looking. Across 247 support bundles the attempt that found the video was #1
  3726. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  3727. # decaying one, which is the signature of a budget that expires while files are
  3728. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  3729. # prints make big videos and the printer writes them after the print ends, so
  3730. # the poll now runs for minutes and costs one FTP LIST per round.
  3731. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  3732. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  3733. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  3734. def _timelapse_scan_max_attempts() -> int:
  3735. """Round cap for the poll, derived from the wall-clock budget.
  3736. The deadline alone is not a sufficient bound: it assumes each round really
  3737. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  3738. and an FTP list that fails immediately would otherwise spin against the
  3739. printer at full speed for the whole window. Whichever bound is reached
  3740. first ends the poll.
  3741. """
  3742. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  3743. # A zero interval makes the wall-clock budget meaningless; fall back to
  3744. # the round count the production interval would have given.
  3745. return 32
  3746. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  3747. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  3748. """Video filenames already attached to some other archive of this printer.
  3749. Used to disambiguate when more than one file is new since the baseline —
  3750. which happens when a previous print's video landed after this print's
  3751. baseline was taken. Ordering the candidates would be the obvious fix and is
  3752. the wrong one: it can only be done on mtime or on the filename timestamp,
  3753. both of which come from the printer's own clock, and a LAN-only printer
  3754. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  3755. ``attach_timelapse`` saves the video into the archive directory under the
  3756. printer's original filename, and the later MP4 conversion keeps the stem,
  3757. so the stem of ``timelapse_path`` recovers what was claimed.
  3758. """
  3759. from backend.app.models.archive import PrintArchive
  3760. rows = await db.execute(
  3761. select(PrintArchive.timelapse_path).where(
  3762. PrintArchive.printer_id == printer_id,
  3763. PrintArchive.id != exclude_archive_id,
  3764. PrintArchive.timelapse_path.is_not(None),
  3765. )
  3766. )
  3767. return {Path(p).stem for p in rows.scalars().all() if p}
  3768. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  3769. """List video files from printer's timelapse directory.
  3770. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  3771. Returns (video_files, found_path) where video_files is a list of file dicts
  3772. and found_path is the directory where they were found, or ([], None).
  3773. """
  3774. from backend.app.services.bambu_ftp import list_files_async
  3775. logger = logging.getLogger(__name__)
  3776. # No card in the slot means no /timelapse to walk — four connections that
  3777. # can only fail, on a path whose failures are swallowed and so would go on
  3778. # costing time silently forever (#2780).
  3779. #
  3780. # ``getattr`` rather than ``printer.id``: every dereference below happens
  3781. # inside the loop's own try/except, so a caller that passed something
  3782. # unexpected used to get an empty listing rather than an exception. Keep
  3783. # that, instead of making this gate the first thing that can raise here.
  3784. printer_id = getattr(printer, "id", None)
  3785. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  3786. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  3787. return [], None
  3788. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  3789. try:
  3790. found_files = await list_files_async(
  3791. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  3792. )
  3793. if found_files:
  3794. video_files = [
  3795. f
  3796. for f in found_files
  3797. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  3798. ]
  3799. if video_files:
  3800. return video_files, timelapse_path
  3801. except Exception as e:
  3802. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  3803. continue
  3804. return [], None
  3805. async def _capture_timelapse_baseline_at_start(
  3806. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  3807. ) -> None:
  3808. """Snapshot the printer's timelapse directory at print start so the
  3809. completion-time scan can pick the new file by set-difference.
  3810. Must be called from every on_print_start path that proceeds to a real
  3811. print — both the new-archive branch and the expected-archive branch (which
  3812. queue / VP-dispatched prints take). Without a baseline,
  3813. _scan_for_timelapse_with_retries falls into its "take baseline now"
  3814. fallback that runs AFTER the new MP4 has already landed on the SD card,
  3815. so the new file ends up in the "baseline" set and no diff ever matches.
  3816. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  3817. unreliable — the snapshot-diff approach sidesteps that entirely.
  3818. When ``archive_id`` is known the baseline is also written to the archive
  3819. row, so it survives a restart and the manual "Scan for Timelapse" button
  3820. can run the same diff instead of falling back to clock-based matching
  3821. (#2704). Only baselines taken at print start are persisted — one taken at
  3822. completion already contains the new video and would poison a later scan.
  3823. """
  3824. names: set[str] | None = None
  3825. try:
  3826. baseline_files, _ = await _list_timelapse_videos(printer)
  3827. names = {f.get("name", "") for f in baseline_files}
  3828. _timelapse_baselines[printer_id] = names
  3829. logger.info(
  3830. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  3831. len(names),
  3832. printer_id,
  3833. )
  3834. except Exception as e:
  3835. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  3836. if archive_id is None:
  3837. return
  3838. try:
  3839. async with async_session() as db:
  3840. from backend.app.models.archive import PrintArchive
  3841. archive = await db.get(PrintArchive, archive_id)
  3842. if archive is not None:
  3843. # Written even when the listing failed, and then as NULL. A
  3844. # reprint reuses the archive row, so leaving the previous run's
  3845. # baseline in place would have the scan diff this print against
  3846. # the state of the printer before the *last* one — and a stale
  3847. # baseline reads as authoritative, where NULL correctly falls
  3848. # back to a fresh snapshot.
  3849. archive.timelapse_baseline = sorted(names) if names is not None else None
  3850. await db.commit()
  3851. except Exception as e:
  3852. # In-memory baseline still covers the normal completion path.
  3853. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  3854. async def _scan_for_timelapse_with_retries(archive_id: int, baseline_names: set[str] | None = None):
  3855. """Poll the printer for this print's timelapse and attach it.
  3856. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  3857. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  3858. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  3859. (#2704). Comparing the current listing against the set of filenames that
  3860. existed when the print started needs no clock at all, because the printer
  3861. writes the video only once the print has ended.
  3862. Baseline precedence: the caller's in-memory set, then the one persisted on
  3863. the archive at print start, then a snapshot taken now. The last of those is
  3864. a poor substitute — by completion the new video may already be on the card,
  3865. in which case it lands in the "baseline" and no diff can ever match — but it
  3866. is all that is available for a print that began before Bambuddy started.
  3867. On success the video is deleted from the printer, which keeps ``/timelapse``
  3868. down to the unclaimed files and makes the next diff unambiguous.
  3869. """
  3870. logger = logging.getLogger(__name__)
  3871. # --- Phase 1: establish the baseline -------------------------------------
  3872. try:
  3873. async with async_session() as db:
  3874. from backend.app.models.printer import Printer
  3875. service = ArchiveService(db)
  3876. archive = await service.get_archive(archive_id)
  3877. if not archive:
  3878. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  3879. return
  3880. if archive.timelapse_path:
  3881. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  3882. return
  3883. if not archive.printer_id:
  3884. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  3885. return
  3886. if baseline_names is not None:
  3887. logger.info(
  3888. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  3889. len(baseline_names),
  3890. archive_id,
  3891. )
  3892. elif archive.timelapse_baseline is not None:
  3893. # Persisted at print start — survives a restart mid-print.
  3894. baseline_names = set(archive.timelapse_baseline)
  3895. logger.info(
  3896. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  3897. len(baseline_names),
  3898. archive_id,
  3899. )
  3900. else:
  3901. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  3902. printer = result.scalar_one_or_none()
  3903. if not printer:
  3904. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  3905. return
  3906. baseline_files, _ = await _list_timelapse_videos(printer)
  3907. baseline_names = {f.get("name", "") for f in baseline_files}
  3908. logger.info(
  3909. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  3910. len(baseline_names),
  3911. archive_id,
  3912. )
  3913. except Exception as e:
  3914. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  3915. return
  3916. # --- Phase 2: poll for a file that was not there when the print began -----
  3917. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  3918. max_attempts = _timelapse_scan_max_attempts()
  3919. seen_names: set[str] = set()
  3920. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  3921. attempt = 0
  3922. while True:
  3923. await asyncio.sleep(delay)
  3924. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  3925. attempt += 1
  3926. try:
  3927. from backend.app.models.printer import Printer
  3928. # Read phase: fetch archive + printer in a short session and release
  3929. # the pooled connection BEFORE the FTP list/download below. Holding it
  3930. # across the FTP round-trips left one connection idle-in-transaction per
  3931. # in-flight scan (issue #2572).
  3932. async with async_session() as db:
  3933. service = ArchiveService(db)
  3934. archive = await service.get_archive(archive_id)
  3935. if not archive:
  3936. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  3937. return
  3938. if archive.timelapse_path:
  3939. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  3940. return
  3941. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  3942. printer = result.scalar_one_or_none()
  3943. if not printer:
  3944. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  3945. return
  3946. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  3947. # I/O phase (no DB connection held): FTP list + download.
  3948. video_files, found_path = await _list_timelapse_videos(printer)
  3949. # The poll can run for dozens of rounds, so only narrate a round
  3950. # that saw something change. Repeating the whole listing every 30 s
  3951. # would bury the one interesting line in the support bundle.
  3952. names_now = {f.get("name", "") for f in video_files}
  3953. changed = attempt == 1 or names_now != seen_names
  3954. seen_names = names_now
  3955. speak = logger.info if changed else logger.debug
  3956. if video_files:
  3957. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  3958. if changed:
  3959. for f in video_files[:5]:
  3960. logger.info("[TIMELAPSE] - %s", f.get("name"))
  3961. attached = await _attach_first_unclaimed_timelapse(
  3962. archive_id, printer, video_files, baseline_names, claimed, attempt, logger, quiet=not changed
  3963. )
  3964. if attached:
  3965. return
  3966. else:
  3967. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  3968. except Exception as e:
  3969. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  3970. if attempt >= max_attempts or time.monotonic() >= deadline:
  3971. break
  3972. # No name-match fallback: it compared the print name against the filename,
  3973. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  3974. # bundles it fired 159 times and matched zero times, so all it added was a
  3975. # misleading log line before giving up.
  3976. logger.warning(
  3977. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  3978. archive_id,
  3979. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  3980. )
  3981. async def _attach_first_unclaimed_timelapse(
  3982. archive_id: int,
  3983. printer,
  3984. video_files: list[dict],
  3985. baseline_names: set[str],
  3986. claimed: set[str],
  3987. attempt: int,
  3988. logger: logging.Logger,
  3989. *,
  3990. quiet: bool = False,
  3991. ) -> bool:
  3992. """Download and attach the one video that belongs to this print.
  3993. A candidate is any file absent from the print-start baseline. More than one
  3994. can qualify when a previous print's video landed late, after this print's
  3995. baseline was taken — those are filtered out by name, because they are
  3996. already attached to another archive. Sorting the candidates instead would
  3997. mean sorting on mtime or on the filename timestamp, both of which come from
  3998. the printer's unsynced clock.
  3999. Returns True once a video is attached. The printer's copy is deleted only
  4000. after the attach succeeds on bytes whose length matched the listing.
  4001. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  4002. already seen this exact listing — the poll runs for many rounds and only the
  4003. rounds where something changed are worth an INFO line.
  4004. """
  4005. from backend.app.services.bambu_ftp import (
  4006. delete_archived_timelapse,
  4007. download_file_bytes_async,
  4008. remote_file_settled,
  4009. )
  4010. speak = logger.debug if quiet else logger.info
  4011. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  4012. if not new_files:
  4013. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  4014. return False
  4015. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  4016. if not candidates:
  4017. speak(
  4018. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  4019. attempt,
  4020. len(new_files),
  4021. )
  4022. return False
  4023. if len(candidates) > 1:
  4024. logger.warning(
  4025. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  4026. "the rest stay on the printer for manual selection",
  4027. attempt,
  4028. len(candidates),
  4029. ", ".join(str(f.get("name")) for f in candidates),
  4030. )
  4031. target = candidates[0]
  4032. file_name = target.get("name")
  4033. remote_path = target.get("path") or f"/timelapse/{file_name}"
  4034. logger.info(
  4035. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  4036. attempt,
  4037. file_name,
  4038. archive_id,
  4039. )
  4040. # The listing always carries a size (`list_files` skips entries it can't
  4041. # parse), but read it explicitly: the delete below is destructive and must
  4042. # depend on a size we actually had, not on one we hoped was there.
  4043. expected_size = target.get("size")
  4044. timelapse_data = await download_file_bytes_async(
  4045. printer.ip_address,
  4046. printer.access_code,
  4047. remote_path,
  4048. printer_model=printer.model,
  4049. expected_size=expected_size,
  4050. )
  4051. if not timelapse_data:
  4052. # Short or failed transfer. The printer keeps its copy, so the next
  4053. # round can try again — which is exactly why the delete below is
  4054. # gated on a verified download.
  4055. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  4056. return False
  4057. # The length check above proves we got what the listing said, not that the
  4058. # printer had finished writing. A video still being written can be listed
  4059. # short, served short, and pass — so confirm it has stopped growing before
  4060. # committing to it and deleting the original (#2704).
  4061. if not await remote_file_settled(
  4062. printer.ip_address,
  4063. printer.access_code,
  4064. remote_path,
  4065. len(timelapse_data),
  4066. printer_model=printer.model,
  4067. ):
  4068. return False
  4069. # Write phase: attach in a fresh short-lived session.
  4070. async with async_session() as db:
  4071. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, file_name)
  4072. if not success:
  4073. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  4074. return False
  4075. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  4076. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  4077. await delete_archived_timelapse(
  4078. printer.ip_address,
  4079. printer.access_code,
  4080. remote_path,
  4081. verified=expected_size is not None,
  4082. printer_model=printer.model,
  4083. printer_name=printer.name,
  4084. )
  4085. return True
  4086. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  4087. # module-level so tests can monkeypatch them down to ~0 without timing out.
  4088. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  4089. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  4090. # How long the *background* upgrade keeps waiting after the notification has
  4091. # already gone out (#2704 follow-up). The short bound above exists so a slow
  4092. # printer can't hold up the print-complete notification; this one exists so the
  4093. # archive still ends up with the better frame afterwards.
  4094. #
  4095. # Measured across 261 attaches in the support bundles, the video lands a median
  4096. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  4097. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  4098. # was 546s. Every other model was inside 26s. The long budget is therefore
  4099. # almost entirely for P1-series users; on everything else the short wait already
  4100. # wins and this task never runs.
  4101. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  4102. async def _capture_finish_photo_from_timelapse(
  4103. archive_id: int,
  4104. archive_dir: Path,
  4105. timeout: float | None = None,
  4106. rotation: int = 0,
  4107. ) -> tuple[str | None, bool]:
  4108. """Wait for the per-print timelapse to land on the archive and extract its
  4109. last frame as the finish photo (#1397).
  4110. Bambu firmware stops timelapse recording after the toolhead parks but
  4111. before the bed-drop end-gcode runs, so the last frame frames the finished
  4112. print correctly. A live camera grab at gcode_state=FINISH captures the
  4113. bed already lowered.
  4114. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  4115. ``archive.timelapse_path`` when the file lands. This function polls for
  4116. that field.
  4117. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  4118. the wait ran out with no video on the archive yet — i.e. the video may
  4119. still be coming and a later attempt could succeed. It is False when the
  4120. video landed (whether or not extraction worked), because in that case
  4121. waiting longer changes nothing. The caller uses that to decide between
  4122. falling back permanently and scheduling a background upgrade.
  4123. ``rotation`` is the printer's camera_rotation, applied to the extracted
  4124. still (#2708) so this source agrees with every other finish-photo source.
  4125. The archived video itself is the printer's own file and is left alone —
  4126. rotating it would mean re-encoding it.
  4127. """
  4128. import uuid
  4129. from backend.app.models.archive import PrintArchive
  4130. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  4131. logger = logging.getLogger(__name__)
  4132. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  4133. deadline = asyncio.get_event_loop().time() + budget
  4134. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  4135. while True:
  4136. async with async_session() as db:
  4137. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  4138. archive = result.scalar_one_or_none()
  4139. timelapse_relpath = archive.timelapse_path if archive else None
  4140. if timelapse_relpath:
  4141. video_path = app_settings.base_dir / timelapse_relpath
  4142. if video_path.exists() and video_path.stat().st_size > 0:
  4143. photos_dir = archive_dir / "photos"
  4144. photos_dir.mkdir(parents=True, exist_ok=True)
  4145. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  4146. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  4147. output_path = photos_dir / filename
  4148. if await extract_video_last_frame(video_path, output_path):
  4149. await apply_camera_rotation_to_file(output_path, rotation, logger)
  4150. logger.info(
  4151. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  4152. video_path.name,
  4153. archive_id,
  4154. )
  4155. return filename, False
  4156. logger.warning(
  4157. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  4158. video_path.name,
  4159. archive_id,
  4160. )
  4161. return None, False
  4162. if asyncio.get_event_loop().time() >= deadline:
  4163. logger.info(
  4164. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  4165. archive_id,
  4166. budget,
  4167. )
  4168. return None, True
  4169. await asyncio.sleep(poll_interval)
  4170. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  4171. """Add the timelapse's last frame to an archive after the fact (#2704).
  4172. The print-complete notification waits only ~60s for the video, because
  4173. holding a notification for minutes is worse than sending it with a live
  4174. camera grab. On a P1-series printer the video often lands well after that,
  4175. so the archive used to be stuck with the live grab — which is taken at
  4176. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  4177. the worse photo of the two.
  4178. This keeps waiting in the background and, when the video arrives, extracts
  4179. the frame and puts it *first* in the archive's photo list, so opening the
  4180. gallery shows it. The live grab is deliberately kept: the notification that
  4181. already went out links to that exact file, and deleting it would leave a
  4182. broken image in Discord or Telegram.
  4183. """
  4184. logger = logging.getLogger(__name__)
  4185. filename, _ = await _capture_finish_photo_from_timelapse(
  4186. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  4187. )
  4188. if not filename:
  4189. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  4190. return
  4191. try:
  4192. async with async_session() as db:
  4193. from backend.app.models.archive import PrintArchive
  4194. archive = await db.get(PrintArchive, archive_id)
  4195. if archive is None:
  4196. return
  4197. photos = list(archive.photos or [])
  4198. if filename in photos:
  4199. return
  4200. # Front of the list: PhotoGalleryModal opens at index 0.
  4201. archive.photos = [filename, *photos]
  4202. await db.commit()
  4203. except Exception as e:
  4204. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  4205. return
  4206. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  4207. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  4208. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  4209. """Put the filament-attribution context back after a restart mid-print.
  4210. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  4211. both die with the process. The print keeps running, so at completion the
  4212. tracker would fall back to whatever the printer reports *now* — and AMS
  4213. filament backup makes "now" the substitute tray, charging the whole print
  4214. to the spool that only finished it.
  4215. The persisted row is only trusted when its print name still matches what
  4216. the printer says it is running: a row left behind by a completion we never
  4217. saw must not attach itself to the next print.
  4218. """
  4219. try:
  4220. from backend.app.api.routes.settings import get_setting
  4221. from backend.app.services.usage_tracker import (
  4222. clear_persisted_session,
  4223. get_persisted_print_name,
  4224. restore_session,
  4225. )
  4226. persisted_name = await get_persisted_print_name(db, printer_id)
  4227. current_name = (state.subtask_name or "").strip()
  4228. if persisted_name and current_name and persisted_name.strip() != current_name:
  4229. logger.info(
  4230. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  4231. printer_id,
  4232. persisted_name,
  4233. current_name,
  4234. )
  4235. await clear_persisted_session(db, printer_id)
  4236. # Fall through to seeding: the print on the printer is real, it just
  4237. # isn't the one the row described.
  4238. persisted_log = None
  4239. else:
  4240. # Spoolman users get the tray-change log back but no in-memory
  4241. # session — see ``on_print_start`` on why that dict is load-bearing
  4242. # for the remain%-sync guard.
  4243. _spoolman_on = await get_setting(db, "spoolman_enabled")
  4244. persisted_log = await restore_session(
  4245. db,
  4246. printer_id,
  4247. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  4248. )
  4249. if persisted_log:
  4250. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  4251. # Anything this process already observed goes after the persisted
  4252. # history — the log is ordered by layer, and a fresh process can
  4253. # only have seen changes from later in the print.
  4254. for entry in state.tray_change_log or []:
  4255. if tuple(entry) not in restored:
  4256. restored.append(tuple(entry))
  4257. state.tray_change_log = restored
  4258. tray_now = state.tray_now
  4259. if 0 <= tray_now <= 254:
  4260. if not state.tray_change_log:
  4261. # No persisted history — a print that started before this build,
  4262. # or before the row existed. Seed with the tray feeding right
  4263. # now so the remainder of the print is at least attributable to
  4264. # the right spool.
  4265. state.tray_change_log = [(tray_now, state.layer_num)]
  4266. logger.info(
  4267. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  4268. printer_id,
  4269. tray_now,
  4270. state.layer_num,
  4271. )
  4272. # The tray handler updates ``last_loaded_tray`` on every push
  4273. # regardless of whether it logged a change, so re-align it to avoid
  4274. # a duplicate entry on the next push. Only ever with a real tray:
  4275. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  4276. # 255" fallback, and writing 255 into it would defeat that.
  4277. state.last_loaded_tray = tray_now
  4278. except Exception:
  4279. # Never let attribution recovery cost the caller its timelapse
  4280. # baseline — that capture has to happen before the printer uploads
  4281. # the in-flight MP4 and there is no second chance at it.
  4282. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  4283. async def on_print_running_observed(printer_id: int, data: dict):
  4284. """Restart-recovery for a print that started before Bambuddy came up.
  4285. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  4286. after Bambuddy startup (#1304 guard, prevents duplicate archive
  4287. creation). This hook restores the persisted archive into ``_active_prints``
  4288. and captures the timelapse baseline that normally hangs off print start.
  4289. Fires once per session, in lieu of on_print_start when restart-recovery
  4290. kicks in. The printer doesn't upload the timelapse until after PRINT
  4291. COMPLETE, so a baseline captured any time during the print is still
  4292. pre-upload.
  4293. """
  4294. logger = logging.getLogger(__name__)
  4295. async with async_session() as db:
  4296. from backend.app.models.printer import Printer
  4297. state = printer_manager.get_status(printer_id)
  4298. if state is not None:
  4299. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  4300. if authorization is True:
  4301. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  4302. await _restore_usage_tracking_session(printer_id, state, db, logger)
  4303. await _restore_printable_objects(printer_id, state, db, logger)
  4304. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4305. printer = result.scalar_one_or_none()
  4306. if not printer:
  4307. logger.warning(
  4308. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  4309. printer_id,
  4310. )
  4311. return
  4312. # Avoid double-capture: ownership reconciliation above must still run when
  4313. # a baseline already exists, but the camera work itself is one-shot.
  4314. if printer_id in _timelapse_baselines:
  4315. logger.debug(
  4316. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  4317. printer_id,
  4318. )
  4319. return
  4320. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  4321. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  4322. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  4323. against the printer's current MQTT state.
  4324. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  4325. COMPLETE events, typically a print finishing during an MQTT disconnect
  4326. window followed by a smart-plug power cycle):
  4327. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  4328. provably not running anymore — only branch that should fire under
  4329. normal disconnect-then-reconnect timing.
  4330. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  4331. firmware mints a fresh ``subtask_id`` for each print, including the
  4332. ghost replay it runs after a power cycle from a leftover SD file —
  4333. so a mismatch unambiguously means the in-DB archive is no longer
  4334. the print on the printer.
  4335. 3. Printer is running but ``subtask_name`` is empty. The printer
  4336. doesn't know what it's running; the archive's reference to it is
  4337. already broken.
  4338. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  4339. with matching subtask_id+subtask_name is left alone. The cost of a false
  4340. positive is a duplicate archive on the next real PRINT COMPLETE — the
  4341. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  4342. clears on synthesis, so the real completion creates a fresh row instead
  4343. of overwriting the synthesised one (#1679). The cost of a false negative
  4344. is the ghost-print loop in #1542.
  4345. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  4346. MQTT has connected but the first ``push_status`` response hasn't been
  4347. applied yet — ``PrinterState`` is sitting on its construction defaults.
  4348. The reconcile caller in ``on_printer_status_change`` is already gated
  4349. on a real ``state.state``, so in normal operation this branch is
  4350. unreachable; it's kept as belt-and-braces for future callers and for
  4351. the narrow window where a partial state update could arrive
  4352. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  4353. ``not stale`` on degenerate input is strictly conservative: a real
  4354. stale archive will still be caught by the next push_status arriving
  4355. with terminal state.
  4356. """
  4357. current_state = (state.state or "").upper()
  4358. if current_state in ("", "UNKNOWN"):
  4359. # No real push_status yet — PrinterState defaults are not evidence.
  4360. return False, ""
  4361. if current_state in ("IDLE", "FINISH", "FAILED"):
  4362. return True, f"printer state {current_state}"
  4363. # Below here the printer is in a running / pre-running state (RUNNING /
  4364. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  4365. current_subtask_id = (state.subtask_id or "").strip()
  4366. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  4367. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  4368. current_subtask_name = (state.subtask_name or "").strip()
  4369. if not current_subtask_name:
  4370. return True, "printer subtask_name empty"
  4371. return False, ""
  4372. async def reconcile_stale_active_prints(printer_id: int) -> int:
  4373. """Synthesise ``on_print_complete`` for archives whose print can't be
  4374. running on the printer anymore.
  4375. Called once per MQTT (re)connection (from on_printer_status_change when
  4376. the connected edge flips False → True) and at Bambuddy startup (from
  4377. the FastAPI lifespan). Without this, a print that completes during a
  4378. disconnect window — followed by a smart-plug-driven power cycle — leaves
  4379. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  4380. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  4381. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  4382. power cycle until the operator notices (#1542 follow-up). Reconciliation
  4383. closes the loop by faking the missed PRINT COMPLETE — the existing
  4384. cleanup chain handles SD-file deletion, status updates, usage tracking,
  4385. and notifications.
  4386. Synthesised ``status="aborted"`` is the conservative label: we have no
  4387. proof the print finished successfully (and no progress evidence to
  4388. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  4389. fires later, overwrites the status with the correct value.
  4390. Returns the number of archives reconciled.
  4391. """
  4392. state = printer_manager.get_status(printer_id)
  4393. if not state:
  4394. return 0
  4395. # Don't reconcile while disconnected — we'd be making a decision against
  4396. # stale cached state. The connected → reconcile edge handles this.
  4397. if not state.connected:
  4398. return 0
  4399. from backend.app.models.archive import PrintArchive
  4400. reconciled = 0
  4401. async with async_session() as db:
  4402. result = await db.execute(
  4403. select(PrintArchive).where(
  4404. PrintArchive.printer_id == printer_id,
  4405. PrintArchive.status == "printing",
  4406. )
  4407. )
  4408. active = list(result.scalars().all())
  4409. if not active:
  4410. return 0
  4411. logger = logging.getLogger(__name__)
  4412. for archive in active:
  4413. is_stale, reason = _is_active_archive_stale(archive, state)
  4414. if not is_stale:
  4415. continue
  4416. logger.info(
  4417. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  4418. printer_id,
  4419. archive.id,
  4420. archive.filename,
  4421. reason,
  4422. )
  4423. # Synthesised payload: minimal fields the on_print_complete chain
  4424. # needs. `_reconciled` marker lets downstream code distinguish this
  4425. # from a real MQTT-driven completion if it ever needs to (e.g. for
  4426. # metrics / debug logging). raw_data is the live printer state so
  4427. # the usage tracker can compare end-of-print remain% against the
  4428. # captured start values.
  4429. try:
  4430. await on_print_complete(
  4431. printer_id,
  4432. {
  4433. "status": "aborted",
  4434. "filename": archive.filename,
  4435. "subtask_name": archive.print_name or "",
  4436. "subtask_id": archive.subtask_id or "",
  4437. "raw_data": state.raw_data or {},
  4438. "_reconciled": True,
  4439. },
  4440. )
  4441. reconciled += 1
  4442. except Exception as e:
  4443. # Catch-all: a reconciliation failure must not block the
  4444. # printer's normal status flow. The archive stays in
  4445. # ``status="printing"`` and the next reconnect retries.
  4446. logger.warning(
  4447. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  4448. archive.id,
  4449. e,
  4450. )
  4451. return reconciled
  4452. # #2547: clearance left between the nozzle and the top of the print when the
  4453. # plate is commanded back into camera framing. The nozzle is parked away from
  4454. # the part by then, so this is belt-and-braces against a max_z_height that
  4455. # under-reports (e.g. a slicer that excludes a final Z hop).
  4456. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  4457. # How far below the restored position to drop the plate again afterwards, so
  4458. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  4459. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  4460. # on machines with less headroom.
  4461. _PLATE_PARK_DROP_MM = 100.0
  4462. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  4463. # this axis, so it is a proven-safe speed for the full travel.
  4464. _PLATE_RESTORE_FEEDRATE = 600
  4465. # Time allowed for the plate to reach the restored position before the camera
  4466. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  4467. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  4468. # How long `_background_finish_photo` waits for this producer. Must cover the
  4469. # settle window plus a worst-case RTSP grab (15s), and stay below the
  4470. # notification path's own photo wait so a slow producer degrades to a
  4471. # photo-less notification rather than a missed one.
  4472. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  4473. async def _max_z_for_current_print(printer_id: int, data: dict, logger) -> float | None:
  4474. """Height of the print that just finished on ``printer_id``, or None (#2547).
  4475. This number becomes the target of a real Z move, so every step here refuses
  4476. rather than guesses. A height belonging to some *other* print is the one
  4477. failure that could drive the nozzle into the model: 20 mm carried onto a
  4478. 200 mm print would command the plate up through the part.
  4479. Two independent things therefore have to agree before a height is returned:
  4480. 1. **Identity.** The archive is matched by the finished print's own
  4481. ``subtask_name``, by equality rather than a ``LIKE``, so "Cube" can never
  4482. resolve to "Cube v2". Matching on "most recent archive for this printer"
  4483. is not good enough — ``on_print_complete`` pops the ``_active_prints``
  4484. binding concurrently with us, and a print Bambuddy failed to archive
  4485. would silently resolve to its predecessor.
  4486. 2. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  4487. match the layer count the printer itself reported over MQTT for the print
  4488. that just ended. These come from genuinely different sources, so a
  4489. mismatch means the row is not this print, whatever its name says.
  4490. ``completed`` is accepted alongside ``printing`` only because
  4491. ``on_print_complete`` may already have flipped the status by the time we
  4492. run; the identity check above is what actually selects the row.
  4493. """
  4494. subtask_name = (data.get("subtask_name") or "").strip()
  4495. if not subtask_name:
  4496. # Nothing to identify the print by — refuse rather than fall back to
  4497. # "whatever ran last on this printer".
  4498. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  4499. return None
  4500. try:
  4501. from backend.app.models.archive import PrintArchive
  4502. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  4503. async with async_session() as db:
  4504. result = await db.execute(
  4505. select(PrintArchive)
  4506. .where(
  4507. PrintArchive.printer_id == printer_id,
  4508. PrintArchive.status.in_(("printing", "completed")),
  4509. PrintArchive.deleted_at.is_(None),
  4510. or_(
  4511. PrintArchive.print_name == subtask_name,
  4512. PrintArchive.filename == subtask_name,
  4513. PrintArchive.filename == f"{subtask_name}.3mf",
  4514. PrintArchive.filename == f"{subtask_name}.gcode.3mf",
  4515. ),
  4516. )
  4517. .order_by(PrintArchive.id.desc())
  4518. .limit(1)
  4519. )
  4520. archive = result.scalar_one_or_none()
  4521. if archive is None or not archive.file_path:
  4522. logger.info("[PLATE-RESTORE] printer %s: no archive matches %r — skipping", printer_id, subtask_name)
  4523. return None
  4524. client = printer_manager.get_client(printer_id)
  4525. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  4526. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  4527. logger.warning(
  4528. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  4529. "— refusing to move the plate on a height that may not be this print's",
  4530. printer_id,
  4531. archive.id,
  4532. archive.total_layers,
  4533. reported_layers,
  4534. )
  4535. return None
  4536. path = Path(archive.file_path)
  4537. if not path.is_absolute():
  4538. path = Path(app_settings.data_dir) / path
  4539. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, archive.plate_id or 1)
  4540. except Exception as e:
  4541. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  4542. return None
  4543. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  4544. """Raise the plate back into camera framing before the finish photo (#2547).
  4545. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  4546. the time ``gcode_state`` reaches FINISH the finished print sits far below
  4547. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  4548. This commands an absolute ``G1 Z`` back to just above the last printed
  4549. layer.
  4550. Absolute, not relative, is the whole safety argument. ``max_z_height +
  4551. clearance`` is a height the toolhead was physically at seconds earlier, so
  4552. it is inside the travel limits by construction and leaves the nozzle above
  4553. the part. It is also unambiguous across model families: Z is the
  4554. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  4555. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  4556. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  4557. (#2579).
  4558. Returns True if the move was sent and waited out, False if it was skipped.
  4559. """
  4560. client = printer_manager.get_client(printer_id)
  4561. if client is None:
  4562. return False
  4563. # Re-read state immediately before commanding motion. If the queue has
  4564. # already started the next print, the printer is no longer ours to move.
  4565. state = getattr(client, "state", None)
  4566. if state is None or state.state != "FINISH":
  4567. logger.info(
  4568. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  4569. printer_id,
  4570. getattr(state, "state", "unknown"),
  4571. )
  4572. return False
  4573. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  4574. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  4575. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  4576. return False
  4577. logger.info(
  4578. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  4579. printer_id,
  4580. target_z,
  4581. max_z_height,
  4582. _PLATE_RESTORE_CLEARANCE_MM,
  4583. _PLATE_RESTORE_SETTLE_SECONDS,
  4584. )
  4585. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  4586. return True
  4587. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  4588. """Drop the plate again after the finish photo (#2547).
  4589. Without this the user walks up to a finished print sitting just under the
  4590. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  4591. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  4592. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  4593. print homes anyway.
  4594. """
  4595. client = printer_manager.get_client(printer_id)
  4596. state = getattr(client, "state", None) if client else None
  4597. if client is None or state is None or state.state != "FINISH":
  4598. return
  4599. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  4600. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  4601. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  4602. """True if a queue item is about to take this printer (#2547).
  4603. The scheduler dispatches the next job the moment a print completes, and a
  4604. plate move interleaved with a print start is not a race worth having. The
  4605. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  4606. this window; this closes the head of it.
  4607. """
  4608. try:
  4609. from backend.app.models.print_queue import PrintQueueItem
  4610. async with async_session() as db:
  4611. result = await db.execute(
  4612. select(PrintQueueItem.id)
  4613. .where(
  4614. PrintQueueItem.printer_id == printer_id,
  4615. PrintQueueItem.status.in_(("pending", "printing")),
  4616. )
  4617. .limit(1)
  4618. )
  4619. return result.scalar_one_or_none() is not None
  4620. except Exception as e:
  4621. # Fail closed: if we can't tell, don't move the plate.
  4622. logging.getLogger(__name__).debug(
  4623. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  4624. )
  4625. return True
  4626. async def on_finish_photo_moment(printer_id: int, data: dict):
  4627. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  4628. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  4629. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  4630. fallback for prints that skip stage 22 (cancel, external-spool-only,
  4631. HMS halt, firmware variants). Grabs one frame via the same
  4632. external-camera / RTSP path the post-completion fallback uses, stores
  4633. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  4634. ``_background_finish_photo`` consume the cached bytes when it runs.
  4635. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  4636. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  4637. set to Smooth (#1721). No force-on now means the user's explicit
  4638. timelapse=off in the slicer send dialog is respected.
  4639. """
  4640. logger = logging.getLogger(__name__)
  4641. trigger = data.get("trigger", "unknown")
  4642. timelapse_was_active = bool(data.get("timelapse_was_active"))
  4643. logger.info(
  4644. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  4645. printer_id,
  4646. trigger,
  4647. timelapse_was_active,
  4648. )
  4649. # If a timelapse is actively recording, skip the pre-capture — the
  4650. # post-completion path will extract the last frame from the recorded
  4651. # video, which still provides the best framing (toolhead parked,
  4652. # before bed drop) without the per-layer parking side effects.
  4653. if timelapse_was_active:
  4654. logger.info(
  4655. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  4656. printer_id,
  4657. )
  4658. return
  4659. # #1790: register the producer-done event BEFORE the first await so the
  4660. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  4661. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  4662. # The `finally` below guarantees `set()` runs on every exit, including
  4663. # early returns and exceptions, so the consumer's bounded wait can't hang.
  4664. producer_done = asyncio.Event()
  4665. _stage22_finish_in_flight[printer_id] = producer_done
  4666. # #2547: set once the plate has actually been raised, and read by the
  4667. # `finally` below. Declared out here so a failure anywhere after the move —
  4668. # a camera timeout, a DB error — still lowers the plate again.
  4669. restore_max_z: float | None = None
  4670. try:
  4671. async with async_session() as db:
  4672. from backend.app.api.routes.settings import get_setting
  4673. from backend.app.models.printer import Printer
  4674. capture_setting = await get_setting(db, "capture_finish_photo")
  4675. if capture_setting is not None and capture_setting.lower() != "true":
  4676. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  4677. return
  4678. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  4679. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  4680. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4681. printer = result.scalar_one_or_none()
  4682. if printer is None:
  4683. logger.warning(
  4684. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  4685. printer_id,
  4686. )
  4687. return
  4688. frame_bytes: bytes | None = None
  4689. # #2708: the banked frame arrives already rotated — it comes from
  4690. # `_capture_snapshot_for_notification`, which rotates before returning.
  4691. # Every other source below is a raw grab. Tracking which lets us store
  4692. # exactly one rotation in `_stage22_finish_frames` either way.
  4693. frame_already_rotated = False
  4694. # On the FINISH-state path the End G-code has already run, and two very
  4695. # different situations arrive here needing opposite answers.
  4696. #
  4697. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  4698. # snippet may have ejected the plate — the scene in front of the camera
  4699. # is no longer the finished print, and no amount of moving the plate
  4700. # brings it back. Use the banked in-print frame instead.
  4701. #
  4702. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  4703. # than the camera frames well, and the toolhead is parked out of the
  4704. # way. That is the *best* moment available on firmware that never emits
  4705. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  4706. # back. Preferring the bank here unconditionally, as this code used to,
  4707. # is what shipped a mid-print photo with the toolhead over the part.
  4708. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  4709. banked = _inprint_frame_bank.get(printer_id)
  4710. if banked:
  4711. frame_bytes = banked
  4712. frame_already_rotated = True
  4713. logger.info(
  4714. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  4715. "frame (%d bytes) instead of a post-swap live grab",
  4716. len(banked),
  4717. )
  4718. else:
  4719. logger.warning(
  4720. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  4721. "in-print bank is empty — falling back to a live grab, which may show a "
  4722. "swapped or empty plate",
  4723. printer_id,
  4724. )
  4725. # `restore_max_z` is set only once the plate is actually up, because the
  4726. # `finally` reads it to decide whether it owes a move back down.
  4727. #
  4728. # Never on a print whose End G-code Bambuddy injected, even when the bank
  4729. # came up empty above: that machine may have just ejected its plate, and
  4730. # driving Z into whatever a swap mechanism is doing is not a risk worth
  4731. # taking for a photo of a bed we already know may be bare.
  4732. if (
  4733. frame_bytes is None
  4734. and trigger == "finish_state"
  4735. and restore_plate_enabled
  4736. and not print_dispatch_context.end_gcode_injected(printer_id)
  4737. ):
  4738. wants_restore = await _max_z_for_current_print(printer_id, data, logger)
  4739. if wants_restore is None:
  4740. logger.info(
  4741. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  4742. printer_id,
  4743. )
  4744. elif await _plate_restore_is_blocked_by_queue(printer_id):
  4745. logger.info(
  4746. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  4747. printer_id,
  4748. )
  4749. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  4750. restore_max_z = wants_restore
  4751. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  4752. from backend.app.api.routes.camera import live_frame_for_capture
  4753. from backend.app.services.external_camera import capture_frame
  4754. # #2707: this used to collide with the live view and fail, which is
  4755. # how finish-photo notifications went out with no image attached.
  4756. # Leaving frame_bytes None keeps the rest of the fallback chain.
  4757. defer, buffered = live_frame_for_capture(printer_id)
  4758. if defer:
  4759. frame_bytes = buffered
  4760. else:
  4761. frame_bytes = await capture_frame(
  4762. printer.external_camera_url,
  4763. printer.external_camera_type or "mjpeg",
  4764. snapshot_url=printer.external_camera_snapshot_url,
  4765. )
  4766. if frame_bytes:
  4767. logger.info(
  4768. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  4769. len(frame_bytes),
  4770. )
  4771. elif frame_bytes is None:
  4772. from backend.app.api.routes.camera import get_buffered_frame
  4773. buffered = get_buffered_frame(printer_id)
  4774. if buffered:
  4775. frame_bytes = buffered
  4776. logger.info(
  4777. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  4778. len(frame_bytes),
  4779. )
  4780. else:
  4781. from backend.app.services.camera import capture_camera_frame_bytes
  4782. frame_bytes = await capture_camera_frame_bytes(
  4783. ip_address=printer.ip_address,
  4784. access_code=printer.access_code,
  4785. model=printer.model,
  4786. timeout=15,
  4787. )
  4788. if frame_bytes:
  4789. logger.info(
  4790. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  4791. len(frame_bytes),
  4792. )
  4793. if frame_bytes:
  4794. if not frame_already_rotated:
  4795. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  4796. _stage22_finish_frames[printer_id] = frame_bytes
  4797. else:
  4798. logger.warning(
  4799. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  4800. printer_id,
  4801. )
  4802. except Exception as e:
  4803. logger.warning(
  4804. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  4805. printer_id,
  4806. e,
  4807. )
  4808. finally:
  4809. # #2547: we raised the plate, so we own lowering it — including when the
  4810. # capture above failed or threw partway through.
  4811. if restore_max_z is not None:
  4812. try:
  4813. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  4814. except Exception as e:
  4815. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  4816. # #1790: always unblock the consumer's bounded wait — whether we stored
  4817. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  4818. # dict entry by the consumer doesn't affect signalling.
  4819. producer_done.set()
  4820. def _subtask_name_from_filename(filename: str) -> str:
  4821. """Recover the subtask name a print command would have carried for *filename*.
  4822. The dispatcher derives the printer-facing subtask name from the archive's
  4823. file name, so stripping the extensions back off gives the value MQTT echoes
  4824. on completion. Only the two extensions Bambuddy actually stores are removed,
  4825. and in the order they nest (``.gcode.3mf``), so a model whose own name
  4826. contains a dot -- ``My.Model.3mf`` -- keeps it.
  4827. """
  4828. name = PurePosixPath(filename).name
  4829. for suffix in (".3mf", ".gcode"):
  4830. if name.lower().endswith(suffix):
  4831. name = name[: -len(suffix)]
  4832. return name
  4833. # How the printer marks a subtask name it had to cut short. Observed on real
  4834. # hardware at ~100 characters, but the cut-off is not a fixed character count
  4835. # (a name with multibyte characters came back at 98), so match the marker
  4836. # rather than a length.
  4837. _SUBTASK_TRUNCATION_MARKER = "..."
  4838. def _normalise_subtask_name(name: str) -> str:
  4839. """Canonical form for comparing a dispatched name against MQTT's echo.
  4840. The printer does not echo the name back verbatim: it substitutes
  4841. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  4842. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  4843. The 3MF lookup in this module has always known that -- it builds
  4844. space-to-underscore variants of every candidate filename, and its
  4845. directory search normalises both sides before comparing. This exists so
  4846. the completion check reads the same rule from the same place instead of
  4847. growing its own, which is exactly how it came to disagree (#2829).
  4848. """
  4849. return name.strip().replace(" ", "_").casefold()
  4850. def _subtask_names_match(expected: str, observed: str) -> bool:
  4851. """Whether two subtask names describe the same print.
  4852. Beyond the space/underscore substitution, the printer truncates long names
  4853. and marks the cut with ``...``. A truncated echo has to count as a match or
  4854. every print with a long name strands its queue item the same way.
  4855. """
  4856. expected_n = _normalise_subtask_name(expected)
  4857. observed_n = _normalise_subtask_name(observed)
  4858. if expected_n == observed_n:
  4859. return True
  4860. # Either side can be the truncated one: the printer truncates what it
  4861. # echoes, and an archive whose own filename was recorded from a previous
  4862. # truncated echo carries the marker too.
  4863. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  4864. if cut.endswith(_SUBTASK_TRUNCATION_MARKER) and full.startswith(cut[: -len(_SUBTASK_TRUNCATION_MARKER)]):
  4865. return True
  4866. return False
  4867. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  4868. """Whether this completion event is plausibly about *item*'s print.
  4869. The caller finds its queue row by printer and ``status='printing'`` alone,
  4870. which is all a completion event gives it -- there is no run identifier in
  4871. the MQTT payload to match on. That makes the lookup indiscriminate: any
  4872. completion delivered for this printer closes whichever row happens to be
  4873. printing, however unrelated. Comparing the subtask name against the archive
  4874. the row was dispatched with costs one primary-key load and rules that out.
  4875. Deliberately permissive: it answers False only on a positive disagreement
  4876. between two names we actually have. A row with no archive, an archive with
  4877. no file name, or an event with no subtask name is unverifiable rather than
  4878. wrong, and refusing those would strand the item in ``printing`` and wedge
  4879. the printer's queue -- a worse failure than the one being prevented.
  4880. """
  4881. observed = (data.get("subtask_name") or "").strip()
  4882. if not observed or item.archive_id is None:
  4883. return True
  4884. from backend.app.models.archive import PrintArchive
  4885. archive = await db.get(PrintArchive, item.archive_id)
  4886. if archive is None or not archive.filename:
  4887. return True
  4888. expected = _subtask_name_from_filename(archive.filename)
  4889. if not expected or _subtask_names_match(expected, observed):
  4890. return True
  4891. logging.getLogger(__name__).warning(
  4892. "Ignoring print completion for queue item %s: it was dispatched as %r "
  4893. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  4894. "printing rather than closing a run this event is not about.",
  4895. item.id,
  4896. expected,
  4897. archive.id,
  4898. archive.filename,
  4899. observed,
  4900. )
  4901. return False
  4902. async def on_print_complete(printer_id: int, data: dict):
  4903. """Handle print completion - update the archive status."""
  4904. import time
  4905. logger = logging.getLogger(__name__)
  4906. start_time = time.time()
  4907. def log_timing(section: str):
  4908. elapsed = time.time() - start_time
  4909. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  4910. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  4911. # A kill-switch stop sends its provider notification immediately. Keep the
  4912. # task so the later notification path can await it and avoid a duplicate;
  4913. # if that immediate attempt failed, the regular completion path retries.
  4914. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  4915. # Drop the 3MF download cache for this printer (#972). The print is over,
  4916. # nothing else legitimately needs the bytes; keeping them would only risk
  4917. # handing a stale file to the next print if it reuses the same name.
  4918. clear_3mf_cache(printer_id)
  4919. try:
  4920. ws_data = {
  4921. "status": data.get("status"),
  4922. "filename": data.get("filename"),
  4923. "subtask_name": data.get("subtask_name"),
  4924. "timelapse_was_active": data.get("timelapse_was_active"),
  4925. }
  4926. await ws_manager.send_print_complete(printer_id, ws_data)
  4927. log_timing("WebSocket send_print_complete")
  4928. except Exception as e:
  4929. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  4930. # Capture user info before clearing (needed for print log entry)
  4931. _print_user_info = printer_manager.get_current_print_user(printer_id)
  4932. # Clear current print user tracking (Issue #206)
  4933. printer_manager.clear_current_print_user(printer_id)
  4934. # If the user explicitly stopped this print from the queue UI the printer will
  4935. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  4936. # correct "print stopped" notification/email is sent instead of a failure alert.
  4937. _raw_status = data.get("status", "completed")
  4938. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  4939. logger.info(
  4940. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  4941. _raw_status,
  4942. printer_id,
  4943. )
  4944. data = {**data, "status": "cancelled"}
  4945. _user_stopped_printers.discard(printer_id)
  4946. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  4947. # may have left material on the bed: a user can cancel ten hours into a
  4948. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  4949. # touchscreen-stop reports `aborted` rather than `cancelled` because
  4950. # `_user_stopped_printers` is only populated when the user stops via the
  4951. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  4952. # which auto-dispatched the next queued print onto a fouled bed two seconds
  4953. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  4954. # Auto Off power cycles and Bambuddy restarts.
  4955. _final_status = data.get("status", "completed")
  4956. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  4957. printer_manager.set_awaiting_plate_clear(printer_id, True)
  4958. # MQTT relay - publish print complete
  4959. try:
  4960. printer_info = printer_manager.get_printer(printer_id)
  4961. if printer_info:
  4962. await mqtt_relay.on_print_complete(
  4963. printer_id,
  4964. printer_info.name,
  4965. printer_info.serial_number,
  4966. data.get("filename", ""),
  4967. data.get("subtask_name", ""),
  4968. data.get("status", "completed"),
  4969. )
  4970. except Exception:
  4971. pass # Don't fail print complete callback if MQTT fails
  4972. filename = data.get("filename", "")
  4973. subtask_name = data.get("subtask_name", "")
  4974. if not filename and not subtask_name:
  4975. logger.warning("Print complete without filename or subtask_name")
  4976. return
  4977. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  4978. # Build list of possible keys to try (matching how they were registered in on_print_start)
  4979. possible_keys = []
  4980. # Try subtask_name variations first (most reliable for matching)
  4981. if subtask_name:
  4982. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  4983. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  4984. possible_keys.append((printer_id, subtask_name))
  4985. # Try filename variations
  4986. if filename:
  4987. # Extract just the filename if it's a path
  4988. fname = filename.split("/")[-1] if "/" in filename else filename
  4989. if fname.endswith(".3mf"):
  4990. possible_keys.append((printer_id, fname))
  4991. elif fname.endswith(".gcode"):
  4992. base_name = fname.rsplit(".", 1)[0]
  4993. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  4994. possible_keys.append((printer_id, f"{base_name}.3mf"))
  4995. possible_keys.append((printer_id, fname))
  4996. else:
  4997. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  4998. possible_keys.append((printer_id, f"{fname}.3mf"))
  4999. possible_keys.append((printer_id, fname))
  5000. # Also try full path versions
  5001. if filename.endswith(".3mf"):
  5002. possible_keys.append((printer_id, filename))
  5003. elif filename.endswith(".gcode"):
  5004. base_name = filename.rsplit(".", 1)[0]
  5005. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5006. possible_keys.append((printer_id, filename))
  5007. else:
  5008. possible_keys.append((printer_id, f"{filename}.3mf"))
  5009. possible_keys.append((printer_id, filename))
  5010. # Find the archive for this print
  5011. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  5012. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  5013. archive_id = None
  5014. for key in possible_keys:
  5015. archive_id = _active_prints.pop(key, None)
  5016. if archive_id:
  5017. logger.info("Found archive %s with key %s", archive_id, key)
  5018. # Also clean up any other keys pointing to this archive
  5019. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  5020. for k in keys_to_remove:
  5021. _active_prints.pop(k, None)
  5022. break
  5023. if not archive_id:
  5024. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  5025. async with async_session() as db:
  5026. from backend.app.models.archive import PrintArchive
  5027. # Try matching by subtask_name (stored as print_name) first
  5028. if subtask_name:
  5029. result = await db.execute(
  5030. select(PrintArchive)
  5031. .where(PrintArchive.printer_id == printer_id)
  5032. .where(PrintArchive.status == "printing")
  5033. .where(
  5034. or_(
  5035. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  5036. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  5037. )
  5038. )
  5039. .order_by(PrintArchive.created_at.desc())
  5040. .limit(1)
  5041. )
  5042. archive = result.scalar_one_or_none()
  5043. if archive:
  5044. archive_id = archive.id
  5045. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  5046. # Also try by filename
  5047. if not archive_id and filename:
  5048. result = await db.execute(
  5049. select(PrintArchive)
  5050. .where(PrintArchive.printer_id == printer_id)
  5051. .where(PrintArchive.filename == filename)
  5052. .where(PrintArchive.status == "printing")
  5053. .order_by(PrintArchive.created_at.desc())
  5054. .limit(1)
  5055. )
  5056. archive = result.scalar_one_or_none()
  5057. if archive:
  5058. archive_id = archive.id
  5059. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  5060. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  5061. # auto-start files found in root on power cycle, causing ghost prints.
  5062. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  5063. try:
  5064. if subtask_name:
  5065. archive_filename: str | None = None
  5066. async with async_session() as db:
  5067. from backend.app.models.archive import PrintArchive
  5068. from backend.app.models.printer import Printer
  5069. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5070. printer = result.scalar_one_or_none()
  5071. if archive_id:
  5072. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  5073. archive_filename = archive_row.scalar_one_or_none()
  5074. if printer:
  5075. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  5076. from backend.app.utils.filename import derive_remote_filename
  5077. # Primary candidate: the exact path the dispatcher uploaded to
  5078. # (derived from archive.filename via the same rule as upload).
  5079. # Without it, a library row that ended up with a doubled
  5080. # .gcode.3mf (#1542) leaves the real file behind because the
  5081. # subtask_name + ext fallbacks below don't match what's on the
  5082. # SD card. Fallbacks remain for archive-less prints (subtask
  5083. # never resolved to an archive) and for older naming variants.
  5084. candidate_paths: list[str] = []
  5085. if archive_filename:
  5086. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  5087. for ext in (".3mf", ".gcode"):
  5088. fallback = f"/{subtask_name}{ext}"
  5089. if fallback not in candidate_paths:
  5090. candidate_paths.append(fallback)
  5091. # Three outcomes track across all candidates so the final log
  5092. # line reflects what actually happened. The A1 in #1721 always
  5093. # ends here with ``any_not_found=True`` and the others False
  5094. # — its firmware auto-cleans the SD card before our cleanup
  5095. # runs, every candidate FTP-DELE returns 550, and the old
  5096. # code burned 3 retries × 2 s × 3 candidates per print
  5097. # logging a misleading "may linger" WARNING on a successful
  5098. # print.
  5099. any_deleted = False
  5100. any_real_failure = False
  5101. any_not_found = False
  5102. for remote_path in candidate_paths:
  5103. # Retry only the FAILED case — 550 NOT_FOUND will never
  5104. # recover by waiting, so a "file isn't here" answer
  5105. # advances immediately to the next candidate without
  5106. # consuming the retry budget.
  5107. for attempt in range(1, 4):
  5108. try:
  5109. delete_result = await delete_file_async(
  5110. printer.ip_address,
  5111. printer.access_code,
  5112. remote_path,
  5113. printer_model=printer.model,
  5114. )
  5115. except Exception as e:
  5116. delete_result = DeleteResult.FAILED
  5117. logger.warning(
  5118. "SD card cleanup attempt %d/3 raised for %s: %s",
  5119. attempt,
  5120. remote_path,
  5121. e,
  5122. )
  5123. if delete_result == DeleteResult.DELETED:
  5124. any_deleted = True
  5125. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  5126. break
  5127. if delete_result == DeleteResult.NOT_FOUND:
  5128. any_not_found = True
  5129. break # 550 will not recover; try next candidate
  5130. # FAILED: real error — retry with backoff, then give up
  5131. if attempt < 3:
  5132. await asyncio.sleep(2)
  5133. else:
  5134. any_real_failure = True
  5135. logger.warning(
  5136. "SD card cleanup failed after 3 attempts for %s "
  5137. "(network/auth/transient error — file may linger on SD card)",
  5138. remote_path,
  5139. )
  5140. if not any_deleted and not any_real_failure and any_not_found:
  5141. # Every candidate said "not here." Either the printer
  5142. # firmware swept the SD card itself (common on A1) or the
  5143. # dispatcher's upload path doesn't match our candidate
  5144. # rule. Either way: nothing to clean up, no warning.
  5145. logger.debug(
  5146. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  5147. "(printer likely self-cleaned)",
  5148. printer.name,
  5149. )
  5150. except Exception as e:
  5151. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  5152. log_timing("SD card cleanup")
  5153. # Update queue item status early — must run before the archive_id early-return
  5154. # so queue items don't get stuck in "printing" when archive lookup fails.
  5155. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  5156. queue_item_id = None
  5157. billing_run_id: str | None = None
  5158. billing_user_id: int | None = None
  5159. billing_cost_center_id: int | None = None
  5160. billing_plate_id: int | None = None
  5161. queue_status = None
  5162. queue_auto_off = False
  5163. try:
  5164. from backend.app.core.database import run_with_retry
  5165. from backend.app.models.print_queue import PrintQueueItem
  5166. async def _update_queue_status(db):
  5167. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  5168. nonlocal queue_item_id, queue_status, queue_auto_off
  5169. result = await db.execute(
  5170. select(PrintQueueItem)
  5171. .where(PrintQueueItem.printer_id == printer_id)
  5172. .where(PrintQueueItem.status == "printing")
  5173. )
  5174. printing_items = list(result.scalars().all())
  5175. if len(printing_items) > 1:
  5176. logger.warning(
  5177. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  5178. printer_id,
  5179. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  5180. )
  5181. item = printing_items[0] if printing_items else None
  5182. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  5183. return
  5184. if item:
  5185. queue_status = data.get("status", "completed")
  5186. # MQTT sends "aborted" for cancelled prints; normalise to
  5187. # "cancelled" so it matches the queue schema Literal.
  5188. if queue_status == "aborted":
  5189. queue_status = "cancelled"
  5190. item.status = queue_status
  5191. item.completed_at = datetime.now(timezone.utc)
  5192. if queue_status == "failed" and not item.error_message:
  5193. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  5194. # Bump usage counters on the source library file so admins can
  5195. # sort by "last printed" and (eventually) auto-purge stale
  5196. # files — #1008.
  5197. await _bump_library_file_usage_if_completed(db, item, queue_status)
  5198. await db.commit()
  5199. queue_item_id = item.id
  5200. billing_run_id = item.billing_run_id
  5201. billing_user_id = item.created_by_id
  5202. billing_cost_center_id = item.cost_center_id
  5203. billing_plate_id = item.plate_id
  5204. queue_auto_off = item.auto_off_after
  5205. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  5206. await run_with_retry(_update_queue_status, label="queue status update")
  5207. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  5208. # their own sessions and have their own error handling — no retry needed.
  5209. if queue_item_id is not None:
  5210. # Batch orders (#342): this run may have been the last one an order
  5211. # owed. Re-evaluate here rather than lazily on read, so a finished
  5212. # order reports itself complete without someone opening the page.
  5213. try:
  5214. from backend.app.services.print_batch import refresh_batch_status_for_item
  5215. async with async_session() as db:
  5216. await refresh_batch_status_for_item(db, queue_item_id)
  5217. await db.commit()
  5218. except Exception as e:
  5219. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  5220. # MQTT relay - publish queue job completed
  5221. try:
  5222. printer_info = printer_manager.get_printer(printer_id)
  5223. await mqtt_relay.on_queue_job_completed(
  5224. job_id=queue_item_id,
  5225. filename=filename or subtask_name,
  5226. printer_id=printer_id,
  5227. printer_name=printer_info.name if printer_info else "Unknown",
  5228. status=queue_status,
  5229. )
  5230. except Exception:
  5231. pass # Don't fail if MQTT fails
  5232. # Check if queue is now empty and send notification
  5233. try:
  5234. from sqlalchemy import func as sa_func
  5235. async with async_session() as db:
  5236. count_result = await db.execute(
  5237. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  5238. )
  5239. pending_count = count_result.scalar() or 0
  5240. if pending_count == 0:
  5241. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  5242. completed_result = await db.execute(
  5243. select(sa_func.count(PrintQueueItem.id)).where(
  5244. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  5245. PrintQueueItem.completed_at >= today_start,
  5246. )
  5247. )
  5248. completed_count = completed_result.scalar() or 1
  5249. await notification_service.on_queue_completed(
  5250. completed_count=completed_count,
  5251. db=db,
  5252. )
  5253. except Exception:
  5254. pass # Don't fail if notification fails
  5255. # Handle auto_off_after - power off printer if the queue item opted
  5256. # in. Delegates to the smart-plug manager so the off honours each
  5257. # plug's configured strategy (time delay or temperature threshold),
  5258. # is cancelled if the printer starts printing again, and never cuts
  5259. # power on a loaded print (#1890). Previously an inline block here
  5260. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  5261. # timeout regardless of print state — cutting a touchscreen reprint.
  5262. if queue_auto_off:
  5263. try:
  5264. async with async_session() as db:
  5265. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  5266. except Exception as e:
  5267. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  5268. except Exception as e:
  5269. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  5270. log_timing("Queue item update")
  5271. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  5272. # Must run before archive_id early-return so it fires for all prints (including
  5273. # prints started from BambuStudio/touchscreen that have no archive).
  5274. if data.get("status") == "completed":
  5275. try:
  5276. from backend.app.api.routes.settings import get_setting
  5277. async with async_session() as db:
  5278. threshold_str = await get_setting(db, "bed_cooled_threshold")
  5279. threshold = float(threshold_str) if threshold_str else 35.0
  5280. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  5281. async with async_session() as db:
  5282. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  5283. if providers:
  5284. _bed_cool_waiters[printer_id] = {
  5285. "threshold": threshold,
  5286. "filename": filename or subtask_name or "",
  5287. "registered_at": time.time(),
  5288. }
  5289. logger.info(
  5290. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  5291. printer_id,
  5292. threshold,
  5293. )
  5294. else:
  5295. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  5296. except Exception as e:
  5297. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  5298. # Capture the slicer estimate before usage tracking runs. The tracker may
  5299. # update archive.cost with this run's measured cost; billing partial runs
  5300. # against that already-partial value would discount the charge twice.
  5301. billing_planned_grams: float | None = None
  5302. billing_base_cost: float | None = None
  5303. if archive_id:
  5304. try:
  5305. async with async_session() as db:
  5306. from backend.app.models.archive import PrintArchive
  5307. billing_archive = await db.get(PrintArchive, archive_id)
  5308. if billing_archive:
  5309. billing_path = (
  5310. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  5311. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  5312. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  5313. billing_archive,
  5314. billing_path,
  5315. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  5316. )
  5317. except Exception as e:
  5318. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  5319. # --- Track filament consumption (must run before archive_id early-return so usage
  5320. # is recorded even when auto-archive is disabled) ---
  5321. usage_results: list[dict] = []
  5322. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  5323. stored_ams_mapping = data.get("ams_mapping")
  5324. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  5325. if not stored_ams_mapping and archive_id:
  5326. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  5327. # Always drain the plate_id register on completion — the session already
  5328. # consumed it at print-start injection; leaving it would leak into the next
  5329. # print on the same archive_id (rare but possible with reprints) (#1697).
  5330. # Capture the popped value so the completion notification can scope the
  5331. # archive-level (summed-across-plates per #1593) filament + time totals
  5332. # down to the single plate that was actually printed (#1785).
  5333. notify_plate_id: int | None = None
  5334. if archive_id:
  5335. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  5336. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  5337. try:
  5338. async with async_session() as db:
  5339. from backend.app.api.routes.settings import get_setting
  5340. _spoolman_on = await get_setting(db, "spoolman_enabled")
  5341. if not _spoolman_on or _spoolman_on.lower() != "true":
  5342. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  5343. async with async_session() as db:
  5344. usage_results = await usage_on_print_complete(
  5345. printer_id,
  5346. data,
  5347. printer_manager,
  5348. db,
  5349. archive_id=archive_id,
  5350. ams_mapping=stored_ams_mapping,
  5351. )
  5352. if usage_results:
  5353. await ws_manager.broadcast(
  5354. {
  5355. "type": "spool_usage_logged",
  5356. "printer_id": printer_id,
  5357. "usage": usage_results,
  5358. }
  5359. )
  5360. log_timing("Usage tracker")
  5361. except Exception as e:
  5362. logger.warning("Usage tracker on_print_complete failed: %s", e)
  5363. # Drop the print-start context unconditionally — the Spoolman branch above
  5364. # skips the internal tracker entirely, so nothing else would clear what
  5365. # print start captured, and a row surviving its print would be restored
  5366. # onto the next one after a restart.
  5367. try:
  5368. from backend.app.services.usage_tracker import discard_session
  5369. async with async_session() as db:
  5370. await discard_session(db, printer_id)
  5371. except Exception as e:
  5372. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  5373. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  5374. if archive_id:
  5375. if data.get("status") == "completed":
  5376. try:
  5377. await _report_spoolman_usage(printer_id, archive_id)
  5378. log_timing("Spoolman usage report")
  5379. except Exception as e:
  5380. logger.warning("Spoolman usage reporting failed: %s", e)
  5381. else:
  5382. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  5383. try:
  5384. async with async_session() as db:
  5385. await _cleanup_spoolman_tracking(
  5386. printer_id,
  5387. archive_id,
  5388. db,
  5389. last_layer_num=data.get("last_layer_num"),
  5390. last_progress=data.get("last_progress"),
  5391. )
  5392. except Exception as e:
  5393. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  5394. log_timing("Filament usage tracking")
  5395. if not archive_id:
  5396. # The printer's own calibration run has no archive by design, so this
  5397. # arrives here every time one finishes. Returning before the no-archive
  5398. # notification is not just noise control: that path attributes an
  5399. # unmatched completion to any queue item this printer finished in the
  5400. # last five minutes, which for a calibration that runs alongside a real
  5401. # print means emailing its owner that their print is done, twice and
  5402. # early. Everything above this point has already run — the plate-clear
  5403. # gate, the queue reconciliation, the SD-card cleanup — so only the
  5404. # notification is skipped.
  5405. if is_internal_printer_job(filename, subtask_name):
  5406. logger.info(
  5407. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  5408. filename,
  5409. subtask_name,
  5410. )
  5411. return
  5412. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  5413. # Still send print-complete/failed/stopped notifications even without an archive.
  5414. # Try to enrich with queue/library-file data so user-specific emails work too.
  5415. async def _notify_no_archive():
  5416. try:
  5417. async with async_session() as db:
  5418. from backend.app.models.library import LibraryFile
  5419. from backend.app.models.print_queue import PrintQueueItem
  5420. from backend.app.models.printer import Printer
  5421. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5422. printer_obj = result.scalar_one_or_none()
  5423. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  5424. # Try to find the most-recent queue item for this printer so we can
  5425. # recover created_by_id and estimated print time.
  5426. # NOTE: By the time this task runs the queue item status has already
  5427. # been updated to a terminal state (completed/failed/cancelled), so
  5428. # we look for recently-completed items (within the last 5 minutes).
  5429. no_archive_data: dict | None = None
  5430. try:
  5431. cutoff = datetime.now(timezone.utc) - timedelta(minutes=5)
  5432. q_result = await db.execute(
  5433. select(PrintQueueItem)
  5434. .where(PrintQueueItem.printer_id == printer_id)
  5435. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled"]))
  5436. .where(PrintQueueItem.completed_at >= cutoff)
  5437. .order_by(PrintQueueItem.completed_at.desc())
  5438. .limit(1)
  5439. )
  5440. queue_item = q_result.scalar_one_or_none()
  5441. if queue_item:
  5442. no_archive_data = {"created_by_id": queue_item.created_by_id}
  5443. # Pull estimated time from library file when available
  5444. if queue_item.library_file_id:
  5445. lib_result = await db.execute(
  5446. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  5447. )
  5448. lib_file = lib_result.scalar_one_or_none()
  5449. if lib_file and lib_file.print_time_seconds:
  5450. no_archive_data["print_time_seconds"] = lib_file.print_time_seconds
  5451. except Exception as lookup_err:
  5452. logger.debug(
  5453. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  5454. )
  5455. # Enrich with usage tracker results (captured in enclosing scope)
  5456. if usage_results:
  5457. if no_archive_data is None:
  5458. no_archive_data = {}
  5459. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  5460. if total_from_usage > 0:
  5461. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  5462. no_archive_data["usage_results"] = usage_results
  5463. # Try MQTT remaining_time for print duration when no queue/library data
  5464. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  5465. mqtt_remaining = data.get("remaining_time")
  5466. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5467. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  5468. ps = data.get("status", "completed")
  5469. logger.info(
  5470. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  5471. )
  5472. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  5473. await notification_service.on_print_complete(
  5474. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  5475. )
  5476. else:
  5477. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  5478. # Send user-specific email if we have a created_by_id
  5479. if no_archive_data and no_archive_data.get("created_by_id"):
  5480. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  5481. await _dispatch_user_print_email(
  5482. ps,
  5483. no_archive_data["created_by_id"],
  5484. p_name,
  5485. raw_filename,
  5486. db,
  5487. )
  5488. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  5489. except Exception as e:
  5490. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  5491. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  5492. return
  5493. log_timing("Archive lookup")
  5494. # Update archive status
  5495. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  5496. try:
  5497. async with async_session() as db:
  5498. service = ArchiveService(db)
  5499. status = data.get("status", "completed")
  5500. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  5501. if hms_errors:
  5502. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  5503. failure_reason = derive_failure_reason(status, hms_errors)
  5504. if data.get("_reconciled"):
  5505. # A reconciled completion closes out a stale archive at
  5506. # reconnect — it is not a user action, so don't mislabel it
  5507. # "User cancelled". The "Stale" prefix matches the existing
  5508. # stale-cleanup convention and records that the real end time
  5509. # is unknown, which is also why its logged duration is 0 (#2592).
  5510. failure_reason = "Stale - reconciled after reconnect, end time unknown"
  5511. if failure_reason:
  5512. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  5513. elif status == "failed" and hms_errors:
  5514. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  5515. await service.update_archive_status(
  5516. archive_id,
  5517. status=status,
  5518. completed_at=(
  5519. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  5520. ),
  5521. failure_reason=failure_reason,
  5522. )
  5523. logger.info(
  5524. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  5525. )
  5526. await ws_manager.send_archive_updated(
  5527. {
  5528. "id": archive_id,
  5529. "status": status,
  5530. }
  5531. )
  5532. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  5533. # MQTT relay - publish archive updated
  5534. try:
  5535. await mqtt_relay.on_archive_updated(
  5536. archive_id=archive_id,
  5537. print_name=filename or subtask_name,
  5538. status=status,
  5539. )
  5540. except Exception:
  5541. pass # Don't fail if MQTT fails
  5542. except Exception as e:
  5543. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  5544. # Continue with other operations even if archive update fails
  5545. log_timing("Archive status update")
  5546. # Apply finance wallet charge or release reservations once. For all partial
  5547. # terminal states (failed, aborted at the printer display, or cancelled via
  5548. # Bambuddy) use this run's measured spool delta, falling back to the last
  5549. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  5550. # estimate and therefore cannot represent an interrupted run.
  5551. try:
  5552. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  5553. async with async_session() as db:
  5554. from backend.app.models.archive import PrintArchive
  5555. from backend.app.services.finance_billing import apply_print_charge_for_archive
  5556. archive = await db.get(PrintArchive, archive_id)
  5557. if archive and billing_run_id is None:
  5558. billing_run_id = getattr(archive, "billing_run_id", None)
  5559. if archive and archive.created_by_id is None and _print_user_info:
  5560. archive.created_by_id = _print_user_info.get("user_id")
  5561. await db.flush()
  5562. run_status = data.get("status", "completed")
  5563. last_progress = data.get("last_progress")
  5564. if last_progress is None:
  5565. last_progress = data.get("progress")
  5566. actual_run_grams = _compute_run_filament_grams(
  5567. run_status,
  5568. billing_planned_grams,
  5569. last_progress,
  5570. usage_results,
  5571. )
  5572. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  5573. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  5574. charged = await apply_print_charge_for_archive(
  5575. db,
  5576. archive_id,
  5577. charged_user_id=billing_user_id,
  5578. cost_center_id=(
  5579. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  5580. ),
  5581. print_queue_id=queue_item_id,
  5582. print_run_id=billing_run_id,
  5583. base_cost_override=billing_base_cost,
  5584. filament_usage=filament_usage,
  5585. )
  5586. await db.commit()
  5587. if charged:
  5588. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  5589. except Exception as e:
  5590. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  5591. printer_info = printer_manager.get_printer(printer_id)
  5592. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  5593. billing_filename = filename or subtask_name or "Unknown"
  5594. billing_error = str(e)
  5595. try:
  5596. await ws_manager.broadcast(
  5597. {
  5598. "type": "billing_charge_failed",
  5599. "printer_id": printer_id,
  5600. "printer_name": billing_printer_name,
  5601. "filename": billing_filename,
  5602. "archive_id": archive_id,
  5603. }
  5604. )
  5605. except Exception as notification_error:
  5606. logger.error(
  5607. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  5608. archive_id,
  5609. notification_error,
  5610. )
  5611. async def _notify_billing_charge_failed() -> None:
  5612. try:
  5613. async with async_session() as notification_db:
  5614. await notification_service.on_billing_charge_failed(
  5615. printer_id,
  5616. billing_printer_name,
  5617. billing_filename,
  5618. archive_id,
  5619. billing_error,
  5620. notification_db,
  5621. )
  5622. except Exception as provider_error:
  5623. logger.error(
  5624. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  5625. archive_id,
  5626. provider_error,
  5627. exc_info=True,
  5628. )
  5629. spawn_background_task(
  5630. _notify_billing_charge_failed(),
  5631. name=f"billing-charge-failed-{archive_id}",
  5632. )
  5633. log_timing("Finance charge update")
  5634. # Write independent print log entry (separate table, never touches archives)
  5635. try:
  5636. async with async_session() as db:
  5637. from backend.app.models.archive import PrintArchive
  5638. from backend.app.services.print_log import write_log_entry
  5639. archive = await db.get(PrintArchive, archive_id)
  5640. if archive:
  5641. # Back-fill created_by_id on reprint (#730): reprint reuses the
  5642. # source archive row rather than creating a new one, so an
  5643. # archive that was auto-created from a printer-initiated
  5644. # print (created_by_id=NULL) would otherwise stay unattributed
  5645. # forever. When we have a print-session user AND the archive
  5646. # has no attribution yet, credit the current user. Never
  5647. # overwrite an existing attribution — the original uploader
  5648. # keeps ownership.
  5649. _print_user_id = _print_user_info.get("user_id") if _print_user_info else None
  5650. if archive.created_by_id is None and _print_user_id is not None:
  5651. archive.created_by_id = _print_user_id
  5652. p_info = printer_manager.get_printer(printer_id)
  5653. # Per-run actuals — written to PrintLogEntry so stats reflect
  5654. # what THIS print actually used, not the source archive's
  5655. # first-run values (#1378). Helper handles the partial-print
  5656. # math (failed / cancelled / stopped get scaled to progress
  5657. # or to tracked spool deltas).
  5658. _run_status = data.get("status", "completed")
  5659. # #2614: scope the per-run estimate to the printed plate. For a
  5660. # multi-plate 3MF dispatched one plate at a time, the archive's
  5661. # filament/cost are the whole-file totals; the PrintLogEntry must
  5662. # reflect only this plate. No effect on single-plate archives (the
  5663. # plate estimate equals the whole-file value) or on the tracker
  5664. # path (measured spool deltas win in _compute_run_filament_grams).
  5665. _est_full_path = (
  5666. app_settings.base_dir / archive.file_path if archive.file_path else None
  5667. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  5668. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path)
  5669. _run_grams = _compute_run_filament_grams(
  5670. _run_status,
  5671. _est_grams,
  5672. data.get("last_progress", data.get("progress")),
  5673. usage_results,
  5674. )
  5675. # Per-run cost — prefer usage_results sum. For partial prints
  5676. # we deliberately skip the topup-to-estimate logic in
  5677. # usage_tracker (which assumes the print completed); the raw
  5678. # tracked-spool sum is closer to what THIS run actually cost.
  5679. _run_cost: float | None = None
  5680. if usage_results:
  5681. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  5682. if _run_cost is None and _run_status == "completed":
  5683. _run_cost = _est_cost
  5684. await write_log_entry(
  5685. db,
  5686. archive_id=archive.id,
  5687. # Captured by _update_queue_status above; None for
  5688. # printer-initiated prints with no queue row. Batch
  5689. # cost/energy roll-up joins on it (#342).
  5690. queue_item_id=queue_item_id,
  5691. status=_run_status,
  5692. print_name=archive.print_name,
  5693. printer_name=p_info.name if p_info else None,
  5694. printer_id=printer_id,
  5695. started_at=archive.started_at,
  5696. completed_at=archive.completed_at,
  5697. filament_type=archive.filament_type,
  5698. filament_color=archive.filament_color,
  5699. filament_used_grams=_run_grams,
  5700. cost=_run_cost,
  5701. failure_reason=archive.failure_reason,
  5702. thumbnail_path=archive.thumbnail_path,
  5703. created_by_id=archive.created_by_id,
  5704. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  5705. # Reconciled completions have an unknown real end time —
  5706. # log 0 duration instead of the whole disconnect gap (#2592).
  5707. reconciled=bool(data.get("_reconciled")),
  5708. )
  5709. await db.commit()
  5710. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  5711. except Exception as e:
  5712. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  5713. log_timing("Print log entry")
  5714. # Run slow operations as background tasks to avoid blocking the event loop
  5715. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  5716. async def _background_energy_calculation():
  5717. """Calculate and save energy usage in background.
  5718. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  5719. backend restart no longer loses per-print energy data).
  5720. """
  5721. try:
  5722. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  5723. async with async_session() as db:
  5724. from backend.app.models.archive import PrintArchive
  5725. archive = await db.get(PrintArchive, archive_id)
  5726. if archive is None:
  5727. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  5728. return
  5729. starting_kwh = archive.energy_start_kwh
  5730. if starting_kwh is None:
  5731. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  5732. return
  5733. candidates = await energy_plug_candidates(db, printer_id)
  5734. if not candidates:
  5735. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  5736. return
  5737. # Same ordering as the start reading, so the delta below is
  5738. # against the counter that produced `starting_kwh` (#2859).
  5739. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  5740. if selected is None:
  5741. logger.warning(
  5742. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  5743. printer_id,
  5744. ", ".join(plug.name for plug in candidates),
  5745. )
  5746. return
  5747. plug, energy = selected
  5748. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  5749. energy_used = round(energy["total"] - starting_kwh, 4)
  5750. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  5751. if energy_used < 0:
  5752. logger.warning(
  5753. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  5754. archive_id,
  5755. starting_kwh,
  5756. energy["total"],
  5757. )
  5758. return
  5759. from backend.app.api.routes.settings import get_setting
  5760. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  5761. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  5762. energy_cost_value = round(energy_used * cost_per_kwh, 3)
  5763. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  5764. # reprint doesn't visually clobber the source archive's energy data
  5765. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  5766. from sqlalchemy import func
  5767. from backend.app.models.print_log import PrintLogEntry
  5768. existing_runs = await db.scalar(
  5769. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  5770. )
  5771. if (existing_runs or 0) <= 1:
  5772. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  5773. # we just wrote for THIS print. Either way it's the first run.
  5774. archive.energy_kwh = energy_used
  5775. archive.energy_cost = energy_cost_value
  5776. # Backfill the latest PrintLogEntry for this archive with energy
  5777. # (write_log_entry above ran before this background task completed,
  5778. # so energy fields are still NULL on that row).
  5779. latest_run = await db.execute(
  5780. select(PrintLogEntry)
  5781. .where(PrintLogEntry.archive_id == archive_id)
  5782. .order_by(PrintLogEntry.id.desc())
  5783. .limit(1)
  5784. )
  5785. run_row = latest_run.scalar_one_or_none()
  5786. if run_row is not None:
  5787. run_row.energy_kwh = energy_used
  5788. run_row.energy_cost = energy_cost_value
  5789. await db.commit()
  5790. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  5791. except Exception as e:
  5792. logger.warning("[ENERGY-BG] Failed: %s", e)
  5793. async def _background_finish_photo() -> str | None:
  5794. """Capture finish photo in background. Returns photo filename if captured."""
  5795. # #2547: set once this function has raised the plate itself (the
  5796. # timelapse path, where the moment producer returned without doing it).
  5797. # Declared out here so the `finally` can lower it again no matter where
  5798. # the capture below fails.
  5799. plate_restored_z: float | None = None
  5800. try:
  5801. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  5802. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  5803. # Read phase: settings + printer + archive in a short session, released
  5804. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  5805. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  5806. # tens of seconds; holding this session across it pinned one pooled
  5807. # connection idle-in-transaction per finishing print (issue #2572).
  5808. async with async_session() as db:
  5809. from backend.app.api.routes.settings import get_setting
  5810. from backend.app.models.archive import PrintArchive
  5811. from backend.app.models.printer import Printer
  5812. capture_enabled = await get_setting(db, "capture_finish_photo")
  5813. if capture_enabled is not None and capture_enabled.lower() != "true":
  5814. return None
  5815. if not archive_id:
  5816. return None
  5817. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  5818. archive = (
  5819. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5820. ).scalar_one_or_none()
  5821. if not printer or not archive:
  5822. return None
  5823. import uuid
  5824. from datetime import datetime
  5825. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  5826. if not archive.file_path:
  5827. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  5828. archive_dir = resolve_archive_dir(archive)
  5829. photo_filename = None
  5830. # Prefer the timelapse last-frame source when a timelapse was
  5831. # recording — it captures the moment after the toolhead parks
  5832. # but before the bed drops, which the live-camera grab below
  5833. # would miss (#1397). Skipped for external cameras (those have
  5834. # their own framing and don't see a Bambu timelapse). Only
  5835. # runs when the USER explicitly enabled timelapse for this
  5836. # print — #1721 removed Bambuddy's force-on at dispatch
  5837. # because it caused per-layer nozzle parking on Smooth-mode
  5838. # slicer profiles.
  5839. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  5840. printer.external_camera_enabled and printer.external_camera_url
  5841. )
  5842. timelapse_still_pending = False
  5843. if prefer_timelapse_source:
  5844. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  5845. archive_id=archive_id,
  5846. archive_dir=archive_dir,
  5847. rotation=getattr(printer, "camera_rotation", 0),
  5848. )
  5849. # #1721: replacement framing path — on_finish_photo_moment
  5850. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  5851. # parked, bed not yet dropped) and cached the JPEG bytes in
  5852. # _stage22_finish_frames. Consume them now so the saved photo
  5853. # has the better framing instead of the post-bed-drop angle
  5854. # the live-camera fallback below would give.
  5855. if not photo_filename:
  5856. # #1790: on the FINISH-state fallback path the producer
  5857. # task is dispatched back-to-back with this consumer, so
  5858. # a bare pop would race past with an empty result and
  5859. # the RTSP fallback below would collide with the
  5860. # producer's still-in-flight grab (single-client RTSP
  5861. # on Bambu printers). Wait for the producer to finish
  5862. # or give up before touching the cache.
  5863. #
  5864. # #2547: 20s was enough when the producer only ever grabbed a
  5865. # frame. It now also raises the plate first, which costs the
  5866. # settle window before the grab even starts — so the budget has
  5867. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  5868. # under the notification's own photo wait below.
  5869. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  5870. if in_flight is not None:
  5871. try:
  5872. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  5873. except asyncio.TimeoutError:
  5874. logger.warning(
  5875. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  5876. printer_id,
  5877. )
  5878. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  5879. if cached_frame:
  5880. # Already rotated by the producer (#2708) — rotating again
  5881. # here would undo the fix on the banked-frame path, whose
  5882. # bytes reach the cache having been rotated once already.
  5883. photos_dir = archive_dir / "photos"
  5884. photos_dir.mkdir(parents=True, exist_ok=True)
  5885. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5886. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  5887. photo_path = photos_dir / photo_filename
  5888. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  5889. logger.info(
  5890. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  5891. photo_filename,
  5892. len(cached_frame),
  5893. )
  5894. # #2547: the timelapse path reaches the live grab below whenever the
  5895. # video hasn't landed in time — the documented usual outcome on
  5896. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  5897. # returned early for those prints without raising the plate, so
  5898. # without this the photo that actually ships in the notification is
  5899. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  5900. # asked us to fix. The archive still gets the better video frame
  5901. # later; this is about the image the user is sent.
  5902. #
  5903. # Gated on `timelapse_was_active` precisely because that is the
  5904. # condition under which the producer skipped. On every other path it
  5905. # has already raised and lowered the plate, and repeating that here
  5906. # would be a second pointless round trip.
  5907. if (
  5908. not photo_filename
  5909. and data.get("timelapse_was_active")
  5910. and not print_dispatch_context.end_gcode_injected(printer_id)
  5911. ):
  5912. try:
  5913. async with async_session() as db:
  5914. from backend.app.api.routes.settings import get_setting
  5915. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  5916. if restore_setting is None or restore_setting.lower() == "true":
  5917. max_z = await _max_z_for_current_print(printer_id, data, logger)
  5918. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  5919. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  5920. plate_restored_z = max_z
  5921. except Exception as e:
  5922. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  5923. # Fallback chain: external camera → buffered live frame →
  5924. # fresh RTSP capture. Only runs if the timelapse path above
  5925. # didn't already produce a photo.
  5926. if not photo_filename:
  5927. if printer.external_camera_enabled and printer.external_camera_url:
  5928. logger.info("[PHOTO-BG] Using external camera")
  5929. from backend.app.api.routes.camera import live_frame_for_capture
  5930. from backend.app.services.external_camera import capture_frame
  5931. # #2707: the second half of the finish-photo failure — the
  5932. # pre-capture and this fallback both collided with the live
  5933. # view. None here continues down the fallback chain.
  5934. defer, buffered = live_frame_for_capture(printer_id)
  5935. if defer:
  5936. frame_data = buffered
  5937. else:
  5938. frame_data = await capture_frame(
  5939. printer.external_camera_url,
  5940. printer.external_camera_type or "mjpeg",
  5941. snapshot_url=printer.external_camera_snapshot_url,
  5942. )
  5943. if frame_data:
  5944. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  5945. photos_dir = archive_dir / "photos"
  5946. photos_dir.mkdir(parents=True, exist_ok=True)
  5947. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5948. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  5949. photo_path = photos_dir / photo_filename
  5950. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  5951. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  5952. else:
  5953. # Check if camera stream is active - use buffered frame to avoid freeze
  5954. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  5955. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  5956. active_chamber_for_printer = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  5957. buffered_frame = get_buffered_frame(printer_id)
  5958. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  5959. # Use frame from active stream
  5960. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  5961. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  5962. photos_dir = archive_dir / "photos"
  5963. photos_dir.mkdir(parents=True, exist_ok=True)
  5964. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5965. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  5966. photo_path = photos_dir / photo_filename
  5967. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  5968. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  5969. else:
  5970. # No active stream - capture new frame
  5971. from backend.app.services.camera import capture_finish_photo
  5972. photo_filename = await capture_finish_photo(
  5973. printer_id=printer_id,
  5974. ip_address=printer.ip_address,
  5975. access_code=printer.access_code,
  5976. model=printer.model,
  5977. archive_dir=archive_dir,
  5978. rotation=getattr(printer, "camera_rotation", 0),
  5979. )
  5980. # Write phase: attach the photo in a fresh short-lived session.
  5981. if photo_filename:
  5982. async with async_session() as db:
  5983. from backend.app.models.archive import PrintArchive
  5984. arch = await db.get(PrintArchive, archive_id)
  5985. if arch is not None:
  5986. photos = arch.photos or []
  5987. photos.append(photo_filename)
  5988. arch.photos = photos
  5989. await db.commit()
  5990. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  5991. # The short wait above is bounded so a slow printer can't hold up
  5992. # the print-complete notification, which is what the caller is
  5993. # blocking on. When it ran out with the video still on its way,
  5994. # keep waiting off to the side and add the better frame to the
  5995. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  5996. # users, whose videos routinely take minutes to transfer, never get
  5997. # the pre-bed-drop framing this path exists to provide.
  5998. #
  5999. # Spawned here rather than at the point the wait gave up: both this
  6000. # function and the upgrade do a read-modify-write on `photos`, and
  6001. # the live-camera fallback above can take tens of seconds. Starting
  6002. # the upgrade before that write means the two can interleave and one
  6003. # silently drops the other's entry, leaving a JPEG on disk that the
  6004. # gallery never lists.
  6005. if timelapse_still_pending:
  6006. spawn_background_task(
  6007. _upgrade_finish_photo_from_timelapse(
  6008. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  6009. ),
  6010. name=f"finish-photo-upgrade-{archive_id}",
  6011. )
  6012. return photo_filename
  6013. except Exception as e:
  6014. logger.warning("[PHOTO-BG] Failed: %s", e)
  6015. return None
  6016. finally:
  6017. # #2547: we raised the plate, so we owe the move back down — even if
  6018. # the capture in between threw. Otherwise the user finds the print
  6019. # pinned under the nozzle.
  6020. if plate_restored_z is not None:
  6021. try:
  6022. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  6023. except Exception as e:
  6024. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6025. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  6026. # Photo capture task - result will be used by notifications
  6027. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  6028. log_timing("Background tasks scheduled (energy, photo)")
  6029. # Also run smart plug, notifications, and maintenance as background tasks
  6030. print_status = data.get("status", "completed")
  6031. async def _background_smart_plug():
  6032. """Handle smart plug automation in background."""
  6033. try:
  6034. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  6035. async with async_session() as db:
  6036. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  6037. logger.info("[AUTO-OFF-BG] Completed")
  6038. except Exception as e:
  6039. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  6040. async def _background_notifications(finish_photo_filename: str | None = None):
  6041. """Send print complete notifications in background."""
  6042. try:
  6043. logger.info(
  6044. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  6045. )
  6046. async with async_session() as db:
  6047. from backend.app.models.archive import PrintArchive
  6048. from backend.app.models.printer import Printer
  6049. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6050. printer = result.scalar_one_or_none()
  6051. printer_name = printer.name if printer else f"Printer {printer_id}"
  6052. archive_data = None
  6053. if archive_id:
  6054. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6055. archive = archive_result.scalar_one_or_none()
  6056. if archive:
  6057. # Actual elapsed time from started_at/completed_at when both are
  6058. # populated (every terminal status sets completed_at after #1198).
  6059. # Falls back to None so the notification path can decide whether to
  6060. # render the slicer estimate as a last resort.
  6061. actual_time_seconds = None
  6062. if archive.started_at and archive.completed_at:
  6063. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  6064. if elapsed > 0:
  6065. actual_time_seconds = int(elapsed)
  6066. archive_data = {
  6067. "print_time_seconds": archive.print_time_seconds,
  6068. "actual_time_seconds": actual_time_seconds,
  6069. "actual_filament_grams": archive.filament_used_grams,
  6070. "failure_reason": archive.failure_reason,
  6071. "created_by_id": archive.created_by_id,
  6072. }
  6073. # Scale filament usage for partial prints
  6074. if print_status != "completed" and archive.filament_used_grams:
  6075. progress = data.get("progress") or 0
  6076. scale = _partial_progress_scale(progress)
  6077. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  6078. archive_data["progress"] = progress
  6079. # Pass per-slot data from archive.extra_data
  6080. if archive.extra_data and archive.extra_data.get("filament_slots"):
  6081. slots = archive.extra_data["filament_slots"]
  6082. if print_status != "completed":
  6083. scale = _partial_progress_scale(data.get("progress"))
  6084. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  6085. archive_data["filament_slots"] = slots
  6086. # Scope project-summed totals down to the plate that was
  6087. # actually printed — see _scope_notification_archive_data_to_plate
  6088. # for the why (#1785).
  6089. archive_data = _scope_notification_archive_data_to_plate(
  6090. archive_data,
  6091. archive.file_path,
  6092. notify_plate_id,
  6093. print_status,
  6094. data.get("progress"),
  6095. app_settings.base_dir,
  6096. )
  6097. # Enrich filament_grams from usage_results when archive has no 3MF data
  6098. if not archive_data.get("actual_filament_grams") and usage_results:
  6099. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  6100. if total_from_usage > 0:
  6101. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  6102. # Pass usage tracker results for AMS slot info in notifications
  6103. if usage_results:
  6104. archive_data["usage_results"] = usage_results
  6105. # Add finish photo URL and image bytes if available
  6106. if finish_photo_filename:
  6107. from backend.app.api.routes.settings import get_setting
  6108. external_url = await get_setting(db, "external_url")
  6109. if external_url:
  6110. external_url = external_url.rstrip("/")
  6111. archive_data["finish_photo_url"] = (
  6112. f"{external_url}/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  6113. )
  6114. else:
  6115. # Fallback to relative URL (won't work for external services)
  6116. archive_data["finish_photo_url"] = (
  6117. f"/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  6118. )
  6119. # Read finish photo bytes for image attachment (e.g. Pushover)
  6120. try:
  6121. from backend.app.utils.archive_paths import find_archive_photo
  6122. photo_path = find_archive_photo(archive, finish_photo_filename)
  6123. if photo_path is not None:
  6124. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  6125. if len(photo_bytes) <= 2_500_000:
  6126. archive_data["image_data"] = photo_bytes
  6127. logger.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  6128. else:
  6129. logger.warning(
  6130. f"[NOTIFY-BG] Finish photo too large for attachment: "
  6131. f"{len(photo_bytes)} bytes"
  6132. )
  6133. except Exception as e:
  6134. logger.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  6135. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  6136. await notification_service.on_print_complete(
  6137. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  6138. )
  6139. else:
  6140. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  6141. # Send user-specific email notification
  6142. if archive_data:
  6143. created_by_id = archive_data.get("created_by_id")
  6144. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  6145. await _dispatch_user_print_email(
  6146. print_status,
  6147. created_by_id,
  6148. printer_name,
  6149. raw_filename,
  6150. db,
  6151. )
  6152. logger.info("[NOTIFY-BG] Completed")
  6153. except Exception as e:
  6154. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  6155. async def _background_maintenance_check():
  6156. """Check for maintenance due in background."""
  6157. if print_status != "completed":
  6158. return
  6159. try:
  6160. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  6161. async with async_session() as db:
  6162. from backend.app.models.printer import Printer
  6163. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6164. printer = result.scalar_one_or_none()
  6165. printer_name = printer.name if printer else f"Printer {printer_id}"
  6166. await ensure_default_types(db)
  6167. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  6168. items_needing_attention = [
  6169. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  6170. for item in overview.maintenance_items
  6171. if item.enabled and (item.is_due or item.is_warning)
  6172. ]
  6173. if items_needing_attention:
  6174. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  6175. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  6176. # MQTT relay - publish maintenance alerts
  6177. for item in items_needing_attention:
  6178. try:
  6179. await mqtt_relay.on_maintenance_alert(
  6180. printer_id=printer_id,
  6181. printer_name=printer_name,
  6182. maintenance_type=item["name"],
  6183. current_value=0, # Not easily available here
  6184. threshold=0, # Not easily available here
  6185. )
  6186. except Exception:
  6187. pass # Don't fail if MQTT fails
  6188. else:
  6189. logger.info("[MAINT-BG] Completed (no items need attention)")
  6190. except Exception as e:
  6191. logger.warning("[MAINT-BG] Failed: %s", e)
  6192. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  6193. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  6194. # Notification task waits for photo capture to complete first (with timeout).
  6195. # When a timelapse was recording, photo sourcing polls the per-print
  6196. # timelapse for up to 60s (#1397) — extend the budget so the notification
  6197. # carries the correct bed-up photo instead of falling through to the
  6198. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  6199. #
  6200. # #2547: both budgets now have to cover a plate restore as well.
  6201. #
  6202. # Without timelapse, the wait is on the moment producer, which raises the
  6203. # plate before its grab — so this has to outlast that producer's own budget.
  6204. #
  6205. # With timelapse, the capture polls up to
  6206. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  6207. # falls back to a live grab, which is the case that raises the plate. At the
  6208. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  6209. # restore would have moved the plate for a photo nobody waited for.
  6210. photo_wait_timeout = (
  6211. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  6212. if data.get("timelapse_was_active")
  6213. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  6214. )
  6215. async def _photo_then_notify():
  6216. """Wait for photo capture, then send notification with photo URL."""
  6217. finish_photo = None
  6218. try:
  6219. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  6220. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  6221. except TimeoutError:
  6222. logger.warning(
  6223. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  6224. photo_wait_timeout,
  6225. )
  6226. except Exception as e:
  6227. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  6228. try:
  6229. await _background_notifications(finish_photo)
  6230. except Exception as e:
  6231. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  6232. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  6233. # Stitch external camera layer timelapse if session was active
  6234. print_status = data.get("status", "completed")
  6235. async def _background_layer_timelapse():
  6236. """Stitch layer timelapse and attach to archive."""
  6237. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  6238. try:
  6239. if print_status == "completed":
  6240. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  6241. timelapse_path = await tl_complete(printer_id)
  6242. if timelapse_path and archive_id:
  6243. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  6244. async with async_session() as db:
  6245. service = ArchiveService(db)
  6246. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  6247. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  6248. # Clean up the temp file
  6249. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6250. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  6251. elif timelapse_path:
  6252. # Timelapse created but no archive - just clean up
  6253. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6254. else:
  6255. # Print failed or cancelled - cancel timelapse session
  6256. cancel_session(printer_id)
  6257. logger.info(
  6258. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  6259. )
  6260. except Exception as e:
  6261. logger.warning("[LAYER-TL] Failed: %s", e)
  6262. # Try to cancel session on error
  6263. try:
  6264. cancel_session(printer_id)
  6265. except Exception:
  6266. pass # Best-effort timelapse session cancellation on error
  6267. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  6268. log_timing("All background tasks scheduled")
  6269. # Auto-scan for timelapse if recording was active during the print
  6270. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  6271. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  6272. # Schedule timelapse scan as background task with retries
  6273. # The printer needs time to encode the video after print completion
  6274. baseline = _timelapse_baselines.pop(printer_id, None)
  6275. spawn_background_task(
  6276. _scan_for_timelapse_with_retries(archive_id, baseline),
  6277. name=f"scan-timelapse-{archive_id}",
  6278. )
  6279. log_timing("Timelapse scan scheduled")
  6280. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  6281. # AMS sensor history recording
  6282. _ams_history_task: asyncio.Task | None = None
  6283. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  6284. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  6285. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  6286. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  6287. _ams_alarm_cooldown: dict[str, datetime] = {}
  6288. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  6289. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  6290. # through a cycle and the cool-down after it (#1802). Stored in the settings
  6291. # table rather than alongside _ams_alarm_cooldown above, because a restart
  6292. # partway through a cool-down would otherwise resume alarming about heat the
  6293. # user asked for — the same internal-timestamp-row pattern as
  6294. # support.py's debug_logging_enabled_at.
  6295. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  6296. # Upper bound on that suppression. The latch normally clears as soon as the unit
  6297. # reads at or below the threshold; see utils.ams_drying for why this cap only
  6298. # matters when it never does.
  6299. AMS_DRYING_GRACE_MINUTES = 120
  6300. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  6301. """Read the persisted per-AMS drying latch, dropping entries out of window.
  6302. Anything older than the grace cap would expire on its next visit anyway, so
  6303. discarding it here costs nothing and stops rows for deleted printers from
  6304. accumulating.
  6305. Stamps ahead of now get two defences, because a box whose clock jumps
  6306. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  6307. ones are discarded outright, and the rest are clamped to now. Without the
  6308. clamp the cap would measure from a moment that has not happened yet and hold
  6309. the alarm quiet for the skew on top of the cap. One unnecessary notification
  6310. after a clock jump is a far better failure than an alarm silently disabled
  6311. for hours.
  6312. """
  6313. from backend.app.models.settings import Settings
  6314. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  6315. setting = result.scalar_one_or_none()
  6316. if not setting or not setting.value:
  6317. return {}
  6318. try:
  6319. raw = json.loads(setting.value)
  6320. except (ValueError, TypeError):
  6321. return {} # Corrupted row → no latch, alarms behave as they did before
  6322. if not isinstance(raw, dict):
  6323. return {}
  6324. now = datetime.now(timezone.utc)
  6325. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  6326. latch: dict[str, datetime] = {}
  6327. for key, value in raw.items():
  6328. try:
  6329. stamp = datetime.fromisoformat(str(value))
  6330. except (ValueError, TypeError):
  6331. continue
  6332. if stamp.tzinfo is None:
  6333. stamp = stamp.replace(tzinfo=timezone.utc)
  6334. if not (now - window <= stamp <= now + window):
  6335. continue
  6336. # Nothing may sit in the future: suppression is measured as now minus
  6337. # the stamp, so a stamp ahead of now would extend it by the skew on top
  6338. # of the cap. Clamping the survivors keeps the cap an actual cap.
  6339. latch[str(key)] = min(stamp, now)
  6340. return latch
  6341. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  6342. """Persist the latch, writing only when it actually changed.
  6343. Adds the session change but does not commit — the caller's own commit
  6344. carries it, so the latch lands in the same transaction as the sensor rows
  6345. that produced it.
  6346. """
  6347. from backend.app.models.settings import Settings
  6348. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  6349. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  6350. setting = result.scalar_one_or_none()
  6351. if setting is None:
  6352. # Don't create the row on installs that never dry anything.
  6353. if payload != "{}":
  6354. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  6355. elif setting.value != payload:
  6356. setting.value = payload
  6357. def _ams_has_filament(ams_data: dict) -> bool:
  6358. """True if this AMS unit has at least one tray slot holding filament.
  6359. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  6360. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  6361. still report sensor readings, but those readings are ambient and not
  6362. actionable: no filament to dry, no humidity to push down. #1619 — gate
  6363. humidity/temperature alarms on this check so empty units don't generate
  6364. hourly noise. Sensor history still records regardless so the UI charts
  6365. stay continuous.
  6366. Fallback path inspects the `tray` array's `tray_type` fields for setups
  6367. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  6368. """
  6369. bits = ams_data.get("tray_exist_bits")
  6370. if isinstance(bits, str) and bits.strip():
  6371. try:
  6372. return int(bits, 16) > 0
  6373. except ValueError:
  6374. pass
  6375. trays = ams_data.get("tray")
  6376. if isinstance(trays, list):
  6377. return any(
  6378. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  6379. )
  6380. return False
  6381. async def record_ams_history():
  6382. """Background task to record AMS humidity and temperature data."""
  6383. logger = logging.getLogger(__name__)
  6384. # Wait a short time for MQTT connections to establish on startup
  6385. await asyncio.sleep(10)
  6386. while True:
  6387. try:
  6388. from backend.app.models.ams_history import AMSSensorHistory
  6389. from backend.app.models.printer import Printer
  6390. from backend.app.models.settings import Settings
  6391. async with async_session() as db:
  6392. # Get all active printers
  6393. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  6394. printers = result.scalars().all()
  6395. # Get alarm thresholds from settings
  6396. humidity_threshold = 60.0 # Default: fair threshold
  6397. temp_threshold = 35.0 # Default: fair threshold
  6398. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  6399. setting = result.scalar_one_or_none()
  6400. if setting:
  6401. try:
  6402. humidity_threshold = float(setting.value)
  6403. except (ValueError, TypeError):
  6404. pass # Keep default threshold if stored value is invalid
  6405. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  6406. setting = result.scalar_one_or_none()
  6407. if setting:
  6408. try:
  6409. temp_threshold = float(setting.value)
  6410. except (ValueError, TypeError):
  6411. pass # Keep default threshold if stored value is invalid
  6412. # Per-filament humidity threshold overrides (#1605) — resolved
  6413. # per-AMS below from the loaded tray types. Reuses the same
  6414. # resolver as the auto-drying scheduler so behavior stays in
  6415. # lockstep across both consumers.
  6416. from backend.app.services.print_scheduler import PrintScheduler
  6417. per_type_humidity_thresholds: dict[str, int] = {}
  6418. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  6419. setting = result.scalar_one_or_none()
  6420. if setting and setting.value:
  6421. try:
  6422. raw = json.loads(setting.value)
  6423. if isinstance(raw, dict):
  6424. for k, v in raw.items():
  6425. try:
  6426. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  6427. v
  6428. )
  6429. except (TypeError, ValueError):
  6430. continue
  6431. except (ValueError, TypeError):
  6432. pass # Invalid JSON → no overrides, fall through to global threshold
  6433. # Per-AMS drying latch (#1802), loaded once per pass and written
  6434. # back below only if a unit changed it.
  6435. drying_latch = await _load_ams_drying_latch(db)
  6436. drying_latch_before = dict(drying_latch)
  6437. recorded_count = 0
  6438. for printer in printers:
  6439. # Get current state from printer manager
  6440. state = printer_manager.get_status(printer.id)
  6441. if not state or not state.connected or not state.raw_data:
  6442. continue # Skip disconnected printers - don't use stale data
  6443. raw_data = state.raw_data
  6444. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  6445. continue
  6446. # Record data for each AMS unit
  6447. for ams_data in raw_data["ams"]:
  6448. ams_id = int(ams_data.get("id", 0))
  6449. # Get humidity (prefer humidity_raw)
  6450. humidity_raw = ams_data.get("humidity_raw")
  6451. humidity_idx = ams_data.get("humidity")
  6452. humidity = None
  6453. if humidity_raw is not None:
  6454. try:
  6455. humidity = float(humidity_raw)
  6456. except (ValueError, TypeError):
  6457. pass # Skip unparseable humidity; will try fallback
  6458. if humidity is None and humidity_idx is not None:
  6459. try:
  6460. humidity = float(humidity_idx)
  6461. except (ValueError, TypeError):
  6462. pass # Skip unparseable humidity index value
  6463. # Get temperature
  6464. temperature = None
  6465. temp_str = ams_data.get("temp")
  6466. if temp_str is not None:
  6467. try:
  6468. temperature = float(temp_str)
  6469. except (ValueError, TypeError):
  6470. pass # Skip unparseable temperature value
  6471. # Skip if no data
  6472. if humidity is None and temperature is None:
  6473. continue
  6474. # Record the data point
  6475. history = AMSSensorHistory(
  6476. printer_id=printer.id,
  6477. ams_id=ams_id,
  6478. humidity=humidity,
  6479. humidity_raw=float(humidity_raw) if humidity_raw else None,
  6480. temperature=temperature,
  6481. )
  6482. db.add(history)
  6483. recorded_count += 1
  6484. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  6485. is_ams_ht = ams_id >= 128
  6486. if is_ams_ht:
  6487. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  6488. else:
  6489. ams_label = f"AMS-{chr(65 + ams_id)}"
  6490. # Skip alarm dispatch for empty AMS units — humidity /
  6491. # temperature readings are ambient with no filament to
  6492. # protect, and the hourly notification just becomes
  6493. # noise. Sensor history was already recorded above so
  6494. # the UI charts stay continuous (#1619). Per-AMS check
  6495. # so a multi-AMS setup with one loaded + one empty
  6496. # still alarms on the loaded unit.
  6497. if not _ams_has_filament(ams_data):
  6498. continue
  6499. # Resolve per-filament humidity threshold for this AMS
  6500. # unit (#1605). Falls back to the global ams_humidity_fair
  6501. # when no per-type overrides are configured.
  6502. trays = ams_data.get("tray", []) or []
  6503. effective_humidity_threshold = float(
  6504. PrintScheduler.resolve_humidity_threshold(
  6505. trays, per_type_humidity_thresholds, int(humidity_threshold)
  6506. )
  6507. )
  6508. # Check humidity alarm (only if above threshold)
  6509. if humidity is not None and humidity > effective_humidity_threshold:
  6510. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  6511. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  6512. now = datetime.now(timezone.utc)
  6513. if (
  6514. last_alarm is None
  6515. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  6516. ):
  6517. _ams_alarm_cooldown[cooldown_key] = now
  6518. logger.info(
  6519. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  6520. )
  6521. try:
  6522. # Call different notification method based on AMS type
  6523. if is_ams_ht:
  6524. await notification_service.on_ams_ht_humidity_high(
  6525. printer.id,
  6526. printer.name,
  6527. ams_label,
  6528. humidity,
  6529. effective_humidity_threshold,
  6530. db,
  6531. )
  6532. else:
  6533. await notification_service.on_ams_humidity_high(
  6534. printer.id,
  6535. printer.name,
  6536. ams_label,
  6537. humidity,
  6538. effective_humidity_threshold,
  6539. db,
  6540. )
  6541. except Exception as e:
  6542. logger.warning("Failed to send humidity alarm: %s", e)
  6543. # A drying cycle heats the unit far past ams_temp_fair on
  6544. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  6545. # AMS-HT, against a 35 C default — so the alarm fired
  6546. # once an hour for the whole cycle and kept firing while
  6547. # the unit cooled back down (#1802). Latch on the
  6548. # firmware's own drying state and hold until the reading
  6549. # returns to normal. Humidity is deliberately left alone:
  6550. # it falls during drying, which is the whole point.
  6551. latch_key = f"{printer.id}:{ams_id}"
  6552. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  6553. drying_active=is_drying_active(ams_data),
  6554. temperature=temperature,
  6555. threshold=temp_threshold,
  6556. latched_at=drying_latch.get(latch_key),
  6557. now=datetime.now(timezone.utc),
  6558. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  6559. )
  6560. if new_latch is None:
  6561. drying_latch.pop(latch_key, None)
  6562. else:
  6563. drying_latch[latch_key] = new_latch
  6564. # Check temperature alarm (only if above threshold)
  6565. if temperature is not None and temperature > temp_threshold and not suppress_temp_alarm:
  6566. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  6567. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  6568. now = datetime.now(timezone.utc)
  6569. if (
  6570. last_alarm is None
  6571. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  6572. ):
  6573. _ams_alarm_cooldown[cooldown_key] = now
  6574. logger.info(
  6575. f"Sending temperature alarm for {printer.name} {ams_label}: {temperature}°C > {temp_threshold}°C"
  6576. )
  6577. try:
  6578. # Call different notification method based on AMS type
  6579. if is_ams_ht:
  6580. await notification_service.on_ams_ht_temperature_high(
  6581. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  6582. )
  6583. else:
  6584. await notification_service.on_ams_temperature_high(
  6585. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  6586. )
  6587. except Exception as e:
  6588. logger.warning("Failed to send temperature alarm: %s", e)
  6589. if drying_latch != drying_latch_before:
  6590. await _save_ams_drying_latch(db, drying_latch)
  6591. await db.commit()
  6592. if recorded_count > 0:
  6593. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  6594. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  6595. global _ams_cleanup_counter
  6596. _ams_cleanup_counter += 1
  6597. if _ams_cleanup_counter >= 288:
  6598. _ams_cleanup_counter = 0
  6599. # Get retention days from settings
  6600. from backend.app.models.settings import Settings
  6601. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  6602. setting = result.scalar_one_or_none()
  6603. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  6604. cutoff = utcnow_naive() - timedelta(days=retention_days)
  6605. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  6606. await db.commit()
  6607. if result.rowcount > 0:
  6608. logger.info(
  6609. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  6610. )
  6611. # Wait until next recording interval
  6612. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  6613. except asyncio.CancelledError:
  6614. break
  6615. except Exception as e:
  6616. logger.warning("AMS history recording failed: %s", e)
  6617. await asyncio.sleep(60) # Wait a bit before retrying
  6618. def start_ams_history_recording():
  6619. """Start the AMS history recording background task."""
  6620. global _ams_history_task
  6621. if _ams_history_task is None:
  6622. _ams_history_task = asyncio.create_task(record_ams_history())
  6623. logging.getLogger(__name__).info("AMS history recording started")
  6624. def stop_ams_history_recording():
  6625. """Stop the AMS history recording background task."""
  6626. global _ams_history_task
  6627. if _ams_history_task:
  6628. _ams_history_task.cancel()
  6629. _ams_history_task = None
  6630. logging.getLogger(__name__).info("AMS history recording stopped")
  6631. # Printer sensor history recording (nozzle / bed / chamber)
  6632. _printer_sensor_history_task: asyncio.Task | None = None
  6633. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  6634. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  6635. _printer_sensor_cleanup_counter = 0
  6636. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  6637. # MQTT parser writes, so we don't need to handle per-model field aliases here
  6638. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  6639. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  6640. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  6641. _SENSOR_TARGET_KEYS = {
  6642. "nozzle": "nozzle_target",
  6643. "nozzle_2": "nozzle_2_target",
  6644. "bed": "bed_target",
  6645. "chamber": "chamber_target",
  6646. }
  6647. async def record_printer_sensor_history():
  6648. """Background task to record nozzle / bed / chamber readings.
  6649. Pulls from `state.temperatures` (already normalised across all printer
  6650. models by the MQTT parser) rather than re-parsing raw_data, so we get
  6651. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  6652. """
  6653. logger = logging.getLogger(__name__)
  6654. await asyncio.sleep(10)
  6655. while True:
  6656. try:
  6657. from backend.app.models.printer import Printer
  6658. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  6659. from backend.app.models.settings import Settings
  6660. async with async_session() as db:
  6661. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  6662. printers = result.scalars().all()
  6663. recorded_count = 0
  6664. for printer in printers:
  6665. state = printer_manager.get_status(printer.id)
  6666. if not state or not state.connected:
  6667. continue
  6668. temps = getattr(state, "temperatures", None) or {}
  6669. if not isinstance(temps, dict):
  6670. continue
  6671. for kind in _SENSOR_KINDS:
  6672. if kind not in temps:
  6673. continue
  6674. try:
  6675. value = float(temps[kind])
  6676. except (ValueError, TypeError):
  6677. continue
  6678. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  6679. target_val: float | None = None
  6680. if target_raw is not None:
  6681. try:
  6682. target_val = float(target_raw)
  6683. except (ValueError, TypeError):
  6684. target_val = None
  6685. db.add(
  6686. PrinterSensorHistory(
  6687. printer_id=printer.id,
  6688. sensor_kind=kind,
  6689. value=value,
  6690. target=target_val,
  6691. )
  6692. )
  6693. recorded_count += 1
  6694. await db.commit()
  6695. if recorded_count > 0:
  6696. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  6697. # Periodic cleanup — once every ~24h at this interval.
  6698. global _printer_sensor_cleanup_counter
  6699. _printer_sensor_cleanup_counter += 1
  6700. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  6701. if _printer_sensor_cleanup_counter >= cleanup_every:
  6702. _printer_sensor_cleanup_counter = 0
  6703. result = await db.execute(
  6704. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  6705. )
  6706. setting = result.scalar_one_or_none()
  6707. retention_days = int(setting.value) if setting else PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  6708. cutoff = utcnow_naive() - timedelta(days=retention_days)
  6709. cleanup = await db.execute(
  6710. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  6711. )
  6712. await db.commit()
  6713. if cleanup.rowcount > 0:
  6714. logger.info(
  6715. "Cleaned up %s old printer sensor history entries (older than %s days)",
  6716. cleanup.rowcount,
  6717. retention_days,
  6718. )
  6719. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  6720. except asyncio.CancelledError:
  6721. break
  6722. except Exception as e:
  6723. logger.warning("Printer sensor history recording failed: %s", e)
  6724. await asyncio.sleep(60)
  6725. def start_printer_sensor_history_recording():
  6726. global _printer_sensor_history_task
  6727. if _printer_sensor_history_task is None:
  6728. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  6729. logging.getLogger(__name__).info("Printer sensor history recording started")
  6730. def stop_printer_sensor_history_recording():
  6731. global _printer_sensor_history_task
  6732. if _printer_sensor_history_task:
  6733. _printer_sensor_history_task.cancel()
  6734. _printer_sensor_history_task = None
  6735. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  6736. # Printer runtime tracking
  6737. _runtime_tracking_task: asyncio.Task | None = None
  6738. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  6739. async def track_printer_runtime():
  6740. """Background task to track printer active runtime (RUNNING state only).
  6741. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  6742. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  6743. which track mechanical wear. Pause time has no motion and no wear, so
  6744. counting it inflates maintenance warnings (#1521).
  6745. """
  6746. logger = logging.getLogger(__name__)
  6747. # Wait for MQTT connections to establish on startup
  6748. await asyncio.sleep(15)
  6749. while True:
  6750. try:
  6751. from backend.app.models.printer import Printer
  6752. # Fetch printer IDs in a short-lived read-only session
  6753. async with async_session() as db:
  6754. result = await db.execute(
  6755. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  6756. Printer.is_active.is_(True)
  6757. )
  6758. )
  6759. printer_rows = result.all()
  6760. now = datetime.now(timezone.utc)
  6761. updated_count = 0
  6762. # Update each printer in its own short session to minimise write-lock
  6763. # hold time and avoid blocking critical commits like queue status
  6764. # updates (#897).
  6765. for pid, pname, runtime_secs, last_update in printer_rows:
  6766. state = printer_manager.get_status(pid)
  6767. if not state:
  6768. logger.debug("[%s] Runtime tracking: no state available", pname)
  6769. continue
  6770. if not state.connected:
  6771. logger.debug("[%s] Runtime tracking: not connected", pname)
  6772. continue
  6773. needs_commit = False
  6774. new_runtime = runtime_secs
  6775. new_last_update = last_update
  6776. if state.state == "RUNNING":
  6777. if last_update:
  6778. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  6779. elapsed = (now - lu).total_seconds()
  6780. if elapsed > 0:
  6781. new_runtime = runtime_secs + int(elapsed)
  6782. updated_count += 1
  6783. needs_commit = True
  6784. logger.debug(
  6785. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  6786. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  6787. )
  6788. else:
  6789. needs_commit = True
  6790. logger.debug("[%s] Runtime tracking: first active detection", pname)
  6791. new_last_update = now
  6792. else:
  6793. if last_update is not None:
  6794. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  6795. new_last_update = None
  6796. needs_commit = True
  6797. if needs_commit:
  6798. try:
  6799. async with async_session() as db:
  6800. result = await db.execute(select(Printer).where(Printer.id == pid))
  6801. printer = result.scalar_one_or_none()
  6802. if printer:
  6803. printer.runtime_seconds = new_runtime
  6804. printer.last_runtime_update = new_last_update
  6805. await db.commit()
  6806. except Exception as e:
  6807. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  6808. if updated_count > 0:
  6809. logger.debug("Updated runtime for %s printer(s)", updated_count)
  6810. except asyncio.CancelledError:
  6811. logger.info("Runtime tracking cancelled")
  6812. break
  6813. except Exception as e:
  6814. logger.warning("Runtime tracking failed: %s", e)
  6815. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  6816. def start_runtime_tracking():
  6817. """Start the printer runtime tracking background task."""
  6818. global _runtime_tracking_task
  6819. if _runtime_tracking_task is None:
  6820. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  6821. logging.getLogger(__name__).info("Printer runtime tracking started")
  6822. def stop_runtime_tracking():
  6823. """Stop the printer runtime tracking background task."""
  6824. global _runtime_tracking_task
  6825. if _runtime_tracking_task:
  6826. _runtime_tracking_task.cancel()
  6827. _runtime_tracking_task = None
  6828. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  6829. # SpoolBuddy device watchdog
  6830. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  6831. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  6832. async def _spoolbuddy_watchdog_loop():
  6833. """Periodic check for SpoolBuddy devices that have gone offline."""
  6834. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  6835. while True:
  6836. try:
  6837. await spoolbuddy_watchdog()
  6838. except asyncio.CancelledError:
  6839. break
  6840. except Exception as e:
  6841. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  6842. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  6843. def start_spoolbuddy_watchdog():
  6844. global _spoolbuddy_watchdog_task
  6845. if _spoolbuddy_watchdog_task is None:
  6846. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  6847. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  6848. def stop_spoolbuddy_watchdog():
  6849. global _spoolbuddy_watchdog_task
  6850. if _spoolbuddy_watchdog_task:
  6851. _spoolbuddy_watchdog_task.cancel()
  6852. _spoolbuddy_watchdog_task = None
  6853. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  6854. # Dead-MQTT-session recovery
  6855. #
  6856. # check_staleness() covers the "connected but silent" half-broken session. It
  6857. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  6858. # is the only thing left watching at that point. When paho stops making
  6859. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  6860. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  6861. # offline with the UI open the whole time, recovered only when something
  6862. # happened to nudge it.
  6863. #
  6864. # This loop is that backstop. It only touches printers that had a working
  6865. # session and lost it, and only when the MQTT port still answers — a printer
  6866. # that is simply switched off is left to paho, since rebuilding a client
  6867. # against an unreachable host achieves nothing and would fill the log every
  6868. # night.
  6869. _connection_watchdog_task: asyncio.Task | None = None
  6870. CONNECTION_WATCHDOG_INTERVAL = 60
  6871. # How long a printer must have been silent before we stop trusting paho.
  6872. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  6873. # so a session that is recovering on its own is never interrupted.
  6874. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  6875. # Per-printer floor between rebuild attempts.
  6876. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  6877. _connection_watchdog_last_attempt: dict[int, float] = {}
  6878. async def _recover_dead_printer_sessions() -> int:
  6879. """Rebuild MQTT clients that have been offline too long to still be trying.
  6880. Returns the number of printers a rebuild was attempted for (for tests and
  6881. for the caller's logging). Never raises: one unreachable printer must not
  6882. stop the sweep for the rest of the farm.
  6883. """
  6884. logger = logging.getLogger(__name__)
  6885. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  6886. now = time.monotonic()
  6887. recovered = 0
  6888. for printer_id, client in list(printer_manager._clients.items()):
  6889. try:
  6890. if client.state.connected:
  6891. _connection_watchdog_last_attempt.pop(printer_id, None)
  6892. continue
  6893. # Time since the last inbound message is the age of the last known
  6894. # good session — no extra bookkeeping needed, and it is the same
  6895. # clock is_stale() reads. 0 means this client has never had one:
  6896. # that is the initial-connect path, where paho retrying is the
  6897. # correct and only behaviour, so leave it be.
  6898. last_msg = client._last_message_time
  6899. if not last_msg:
  6900. continue
  6901. offline_for = time.time() - last_msg
  6902. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  6903. continue
  6904. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  6905. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  6906. continue
  6907. if not await check_port(client.ip_address, PORT_MQTT):
  6908. # Switched off, unplugged, or off the network. Paho's retry is
  6909. # the right handler; say so at debug level and move on.
  6910. logger.debug(
  6911. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  6912. "— leaving the reconnect to paho",
  6913. printer_id,
  6914. offline_for,
  6915. )
  6916. _connection_watchdog_last_attempt[printer_id] = now
  6917. continue
  6918. _connection_watchdog_last_attempt[printer_id] = now
  6919. recovered += 1
  6920. logger.warning(
  6921. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  6922. "rebuilding the client with a fresh session (last connect error: %s)",
  6923. printer_id,
  6924. offline_for,
  6925. PORT_MQTT,
  6926. client.last_connect_error or "none recorded",
  6927. )
  6928. # Async context, so this takes the hard-reset path: fresh client_id,
  6929. # paho's QoS 1 queue dropped. That matters — a project_file left
  6930. # unacked on the dead session would otherwise replay into the new
  6931. # one and trip 0500_4003 on the printer (#1136).
  6932. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  6933. except Exception as e:
  6934. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  6935. return recovered
  6936. async def _connection_watchdog_loop():
  6937. logger = logging.getLogger(__name__)
  6938. # Let the initial connects settle before judging anyone offline.
  6939. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  6940. while True:
  6941. try:
  6942. await _recover_dead_printer_sessions()
  6943. except asyncio.CancelledError:
  6944. break
  6945. except Exception as e:
  6946. logger.warning("Connection watchdog sweep failed: %s", e)
  6947. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  6948. def start_connection_watchdog():
  6949. global _connection_watchdog_task
  6950. if _connection_watchdog_task is None:
  6951. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  6952. logging.getLogger(__name__).info("Printer connection watchdog started")
  6953. def stop_connection_watchdog():
  6954. global _connection_watchdog_task
  6955. if _connection_watchdog_task:
  6956. _connection_watchdog_task.cancel()
  6957. _connection_watchdog_task = None
  6958. _connection_watchdog_last_attempt.clear()
  6959. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  6960. # Camera stream orphan cleanup
  6961. _camera_cleanup_task: asyncio.Task | None = None
  6962. CAMERA_CLEANUP_INTERVAL = 60
  6963. async def _camera_cleanup_loop():
  6964. """Periodically clean up orphaned ffmpeg processes."""
  6965. from backend.app.api.routes.camera import cleanup_orphaned_streams
  6966. while True:
  6967. try:
  6968. await cleanup_orphaned_streams()
  6969. except asyncio.CancelledError:
  6970. break
  6971. except Exception as e:
  6972. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  6973. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  6974. def start_camera_cleanup():
  6975. global _camera_cleanup_task
  6976. if _camera_cleanup_task is None:
  6977. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  6978. logging.getLogger(__name__).info("Camera stream cleanup started")
  6979. def stop_camera_cleanup():
  6980. global _camera_cleanup_task
  6981. if _camera_cleanup_task:
  6982. _camera_cleanup_task.cancel()
  6983. _camera_cleanup_task = None
  6984. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  6985. # ---------------------------------------------------------------------------
  6986. # Expected-print TTL eviction
  6987. # ---------------------------------------------------------------------------
  6988. def _evict_stale_expected_prints() -> None:
  6989. """Remove entries from _expected_prints / _expected_print_creators that are
  6990. older than _EXPECTED_PRINT_TTL_SECONDS.
  6991. This prevents unbounded growth when a print is registered (via
  6992. register_expected_print) but on_print_start never fires — e.g. because the
  6993. printer disconnects, the app restarts, or the print is started directly from
  6994. the printer panel without going through the queue.
  6995. """
  6996. # Use monotonic time so the TTL is unaffected by system clock adjustments
  6997. # (e.g. NTP sync, DST changes).
  6998. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  6999. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  7000. if not stale_keys:
  7001. return
  7002. evicted_archive_ids: set[int] = set()
  7003. for key in stale_keys:
  7004. archive_id = _expected_prints.pop(key, None)
  7005. if archive_id is not None:
  7006. evicted_archive_ids.add(archive_id)
  7007. _expected_print_creators.pop(key, None)
  7008. _expected_print_registered_at.pop(key, None)
  7009. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  7010. # that have no remaining live keys in _expected_prints (all variants
  7011. # were just evicted).
  7012. live_archive_ids = set(_expected_prints.values())
  7013. for archive_id in evicted_archive_ids:
  7014. if archive_id not in live_archive_ids:
  7015. _print_ams_mappings.pop(archive_id, None)
  7016. _print_cost_center_ids.pop(archive_id, None)
  7017. _print_plate_ids.pop(archive_id, None)
  7018. logging.getLogger(__name__).info(
  7019. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  7020. )
  7021. async def _expected_prints_cleanup_loop() -> None:
  7022. """Background task: periodically evict stale expected-print entries."""
  7023. while True:
  7024. try:
  7025. _evict_stale_expected_prints()
  7026. except asyncio.CancelledError:
  7027. raise
  7028. except Exception as e:
  7029. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  7030. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  7031. def start_expected_prints_cleanup() -> None:
  7032. global _expected_prints_cleanup_task
  7033. if _expected_prints_cleanup_task is None:
  7034. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  7035. logging.getLogger(__name__).info("Expected prints cleanup started")
  7036. def stop_expected_prints_cleanup() -> None:
  7037. global _expected_prints_cleanup_task
  7038. if _expected_prints_cleanup_task:
  7039. _expected_prints_cleanup_task.cancel()
  7040. _expected_prints_cleanup_task = None
  7041. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  7042. # ---------------------------------------------------------------------------
  7043. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  7044. # ---------------------------------------------------------------------------
  7045. _auth_cleanup_task: asyncio.Task | None = None
  7046. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  7047. async def _run_auth_cleanup() -> None:
  7048. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  7049. from backend.app.core.database import async_session
  7050. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  7051. from backend.app.models.user_totp import UserTOTP
  7052. now = datetime.now(timezone.utc)
  7053. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  7054. try:
  7055. async with async_session() as db:
  7056. stale_cutoff = now - timedelta(hours=1)
  7057. result = await db.execute(
  7058. select(UserTOTP).where(
  7059. UserTOTP.is_enabled.is_(False),
  7060. UserTOTP.created_at < stale_cutoff,
  7061. )
  7062. )
  7063. stale_records = result.scalars().all()
  7064. if stale_records:
  7065. for rec in stale_records:
  7066. await db.delete(rec)
  7067. await db.commit()
  7068. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  7069. except Exception as e:
  7070. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  7071. # Remove expired revoked-JTI entries (they are no longer needed once the
  7072. # original token's exp has passed — the token would be rejected by JWT
  7073. # signature verification regardless).
  7074. try:
  7075. async with async_session() as db:
  7076. await db.execute(
  7077. delete(AuthEphemeralToken).where(
  7078. AuthEphemeralToken.token_type == "revoked_jti",
  7079. AuthEphemeralToken.expires_at < now,
  7080. )
  7081. )
  7082. await db.commit()
  7083. except Exception as e:
  7084. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  7085. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  7086. # Events outside this window can never affect rate-limit decisions — they only
  7087. # consume DB space. Use the same window constant as the rate limiter so the
  7088. # two are always in sync.
  7089. try:
  7090. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  7091. async with async_session() as db:
  7092. await db.execute(
  7093. delete(AuthRateLimitEvent).where(
  7094. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  7095. )
  7096. )
  7097. await db.commit()
  7098. except Exception as e:
  7099. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  7100. async def _auth_cleanup_loop() -> None:
  7101. """Periodic background task: run auth cleanup every hour."""
  7102. while True:
  7103. try:
  7104. await _run_auth_cleanup()
  7105. except asyncio.CancelledError:
  7106. break
  7107. except Exception as e:
  7108. logging.warning("Auth cleanup loop error: %s", e)
  7109. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  7110. def start_auth_cleanup() -> None:
  7111. global _auth_cleanup_task
  7112. if _auth_cleanup_task is None:
  7113. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  7114. logging.getLogger(__name__).info("Auth periodic cleanup started")
  7115. def stop_auth_cleanup() -> None:
  7116. global _auth_cleanup_task
  7117. if _auth_cleanup_task:
  7118. _auth_cleanup_task.cancel()
  7119. _auth_cleanup_task = None
  7120. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  7121. @asynccontextmanager
  7122. async def lifespan(app: FastAPI):
  7123. # Startup
  7124. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  7125. # anything else can spawn tasks that might trip it.
  7126. from backend.app.core.asyncio_handlers import install_proactor_reset_filter
  7127. install_proactor_reset_filter()
  7128. await init_db()
  7129. # After migrations, so the is_env_managed column exists. Never raises --
  7130. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  7131. # startup (see apply_env_oidc_provider).
  7132. from backend.app.core.oidc_env import apply_env_oidc_provider
  7133. async with async_session() as oidc_db:
  7134. await apply_env_oidc_provider(oidc_db)
  7135. # Close out batches that finished before `completed` was a reachable status
  7136. # (#342). Without this the Batches tab opens on every batch created since
  7137. # the feature shipped, all still marked active. Never blocks startup.
  7138. try:
  7139. from backend.app.services.print_batch import backfill_batch_statuses
  7140. async with async_session() as batch_db:
  7141. await backfill_batch_statuses(batch_db)
  7142. except Exception as exc:
  7143. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  7144. # Register an app-scoped httpx client for Bambu Cloud services so
  7145. # per-request BambuCloudService instances reuse the same connection pool
  7146. # (important for routes like /cloud/filament-info that chain many
  7147. # get_setting_detail calls). The shared client stores no region/token
  7148. # state, so the per-request ownership pattern that fixed the region-bleed
  7149. # bug is preserved.
  7150. import httpx as _httpx
  7151. from backend.app.services.bambu_cloud import set_shared_http_client
  7152. from backend.app.services.makerworld import (
  7153. set_shared_http_client as set_shared_makerworld_http_client,
  7154. )
  7155. from backend.app.services.orca_cloud import (
  7156. set_shared_http_client as set_shared_orca_http_client,
  7157. )
  7158. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  7159. set_shared_http_client(_shared_cloud_http_client)
  7160. # Reuse the same connection pool for MakerWorld — different host, same
  7161. # keep-alive pool saves a TLS handshake per request.
  7162. set_shared_makerworld_http_client(_shared_cloud_http_client)
  7163. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  7164. # each spun up (and never closed) its own client, leaking sockets.
  7165. set_shared_orca_http_client(_shared_cloud_http_client)
  7166. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  7167. # This can happen when a print was cancelled mid-print on versions before this fix.
  7168. try:
  7169. async with async_session() as db:
  7170. from backend.app.models.print_queue import PrintQueueItem
  7171. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  7172. aborted_items = result.scalars().all()
  7173. if aborted_items:
  7174. for item in aborted_items:
  7175. item.status = "cancelled"
  7176. await db.commit()
  7177. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  7178. except Exception as e:
  7179. logging.warning("Failed to fix aborted queue items: %s", e)
  7180. # Restore debug logging state from previous session
  7181. await init_debug_logging()
  7182. # Set up printer manager callbacks
  7183. loop = asyncio.get_event_loop()
  7184. printer_manager.set_event_loop(loop)
  7185. printer_manager.set_status_change_callback(on_printer_status_change)
  7186. printer_manager.set_print_start_callback(on_print_start)
  7187. printer_manager.set_print_complete_callback(on_print_complete)
  7188. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  7189. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  7190. printer_manager.set_ams_change_callback(on_ams_change)
  7191. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  7192. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  7193. await printer_manager.load_awaiting_plate_clear_from_db()
  7194. # Layer change callback for external camera timelapse
  7195. async def on_layer_change(printer_id: int, layer_num: int):
  7196. """Capture timelapse frame on layer change + first layer notification."""
  7197. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  7198. await tl_layer_change(printer_id, layer_num)
  7199. # #1867: bank a recent in-print frame so the finish-photo path has a
  7200. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  7201. # #2547 added `on_print_progress` as a second driver — this one alone
  7202. # stops firing once the final layer begins.
  7203. await _maybe_bank_inprint_frame(printer_id, layer_num)
  7204. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  7205. # Gate on actual printing state — Bambu firmware ticks layer_num during
  7206. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  7207. # nozzle clean), so a bare layer_num check can fire minutes before the
  7208. # first real extrusion. We require gcode_state == RUNNING and
  7209. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  7210. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  7211. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  7212. # edge fires later; _first_layer_notified stays clear until we actually send
  7213. # so a deferred re-evaluation can win. See issue #1837.
  7214. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  7215. client = printer_manager.get_client(printer_id)
  7216. state = client.state if client else None
  7217. if not state or state.state != "RUNNING":
  7218. return
  7219. if state.mc_print_sub_stage not in (None, 0):
  7220. return
  7221. _first_layer_notified[printer_id] = True
  7222. try:
  7223. async with async_session() as db:
  7224. from backend.app.models.printer import Printer
  7225. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7226. printer = result.scalar_one_or_none()
  7227. if not printer:
  7228. return
  7229. printer_name = printer.name
  7230. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  7231. total_layers = state.total_layers if state else 0
  7232. image_data = await _capture_snapshot_for_notification(
  7233. printer_id, printer, logging.getLogger(__name__)
  7234. )
  7235. await notification_service.on_first_layer_complete(
  7236. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  7237. )
  7238. except Exception as e:
  7239. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  7240. printer_manager.set_layer_change_callback(on_layer_change)
  7241. async def on_print_progress(printer_id: int, percent: int):
  7242. """#2547: keep the in-print frame bank fresh through the final layer.
  7243. `on_layer_change` stops the moment the last layer starts, which on the
  7244. H2C capture that closed #2547 left the bank stale for the three minutes
  7245. that layer took. Progress is the only field that keeps advancing there,
  7246. and it freezes before the End G-code runs — so banking on it stays
  7247. inside the print and never sees a swapped plate.
  7248. """
  7249. client = printer_manager.get_client(printer_id)
  7250. state = client.state if client else None
  7251. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  7252. printer_manager.set_print_progress_callback(on_print_progress)
  7253. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  7254. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  7255. waiter = _bed_cool_waiters.get(printer_id)
  7256. if not waiter:
  7257. return
  7258. threshold = waiter["threshold"]
  7259. if bed_temp > threshold:
  7260. return
  7261. # Bed is at or below threshold — fire notification and remove waiter
  7262. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  7263. if not waiter_info:
  7264. return # Another callback already handled it
  7265. bed_cool_logger = logging.getLogger(__name__)
  7266. bed_cool_logger.info(
  7267. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  7268. bed_temp,
  7269. printer_id,
  7270. threshold,
  7271. )
  7272. try:
  7273. printer_info = printer_manager.get_printer(printer_id)
  7274. p_name = printer_info.name if printer_info else "Unknown"
  7275. async with async_session() as db:
  7276. await notification_service.on_bed_cooled(
  7277. printer_id=printer_id,
  7278. printer_name=p_name,
  7279. bed_temp=bed_temp,
  7280. threshold=threshold,
  7281. filename=waiter_info["filename"],
  7282. db=db,
  7283. )
  7284. except Exception as e:
  7285. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  7286. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  7287. async def on_drying_complete(printer_id: int, ams_id: int):
  7288. """Smart-plug auto-off-after-drying trigger (#1349).
  7289. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  7290. manager walks all plugs linked to this printer and turns off only
  7291. the ones with ``auto_off_after_drying`` enabled, after their
  7292. per-plug delay. Multiple AMS units finishing close together (e.g. a
  7293. dual-AMS dry that ends within the same MQTT push) call this once
  7294. per unit — the manager's ``_cancel_pending_off`` collapses
  7295. repeated scheduling on the same plug to one timer, so duplicate
  7296. fires are safe.
  7297. """
  7298. try:
  7299. async with async_session() as db:
  7300. await smart_plug_manager.on_drying_complete(printer_id, db)
  7301. except Exception as e:
  7302. logging.getLogger(__name__).warning(
  7303. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  7304. printer_id,
  7305. ams_id,
  7306. e,
  7307. )
  7308. printer_manager.set_drying_complete_callback(on_drying_complete)
  7309. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  7310. """Surface the read-back result of a spool assignment to the UI (#2582).
  7311. The MQTT client confirms (or fails to confirm) that the tray telemetry
  7312. echoed back the filament id we pushed. We relay that as a websocket
  7313. event so the frontend can toast "loaded" / "assignment didn't take"
  7314. instead of the historic silent fire-and-forget, which made the
  7315. AMS→Studio hand-off feel random to users.
  7316. """
  7317. try:
  7318. from backend.app.services.spool_assignment_notifications import (
  7319. _slot_label_from_global_tray,
  7320. )
  7321. if ams_id == 255:
  7322. global_id = 254 + tray_id
  7323. elif ams_id >= 128:
  7324. global_id = ams_id
  7325. else:
  7326. global_id = ams_id * 4 + tray_id
  7327. slot_label = _slot_label_from_global_tray(global_id)
  7328. printer_info = printer_manager.get_printer(printer_id)
  7329. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  7330. await ws_manager.broadcast(
  7331. {
  7332. "type": "spool_assignment_verified",
  7333. "printer_id": printer_id,
  7334. "printer_name": printer_name,
  7335. "ams_id": ams_id,
  7336. "tray_id": tray_id,
  7337. "slot": slot_label,
  7338. "verified": verified,
  7339. # Present on success: False means the filament setting landed
  7340. # but the K-profile (cali_idx) did not — the reporter's exact
  7341. # "loaded but no flow profile" symptom.
  7342. "kprofile_applied": detail.get("kprofile_applied", True),
  7343. # Present on failure: whether any tray telemetry was seen in
  7344. # the window (distinguishes "printer silent" from "printer
  7345. # stored something else").
  7346. "saw_tray": detail.get("saw_tray", False),
  7347. }
  7348. )
  7349. except Exception as e:
  7350. logging.getLogger(__name__).warning(
  7351. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  7352. printer_id,
  7353. ams_id,
  7354. tray_id,
  7355. e,
  7356. )
  7357. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  7358. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  7359. """Persist a mid-print tray change for completion-time attribution.
  7360. AMS filament backup switches trays without telling the slicer, so the
  7361. tray-change log is the only record of which spool fed which layers.
  7362. Keeping it only in memory meant a restart mid-print charged everything
  7363. to the tray that finished the job.
  7364. """
  7365. try:
  7366. from backend.app.services.usage_tracker import record_tray_change
  7367. async with async_session() as db:
  7368. await record_tray_change(db, printer_id, tray_global, layer_num)
  7369. except Exception as e:
  7370. logging.getLogger(__name__).warning(
  7371. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  7372. printer_id,
  7373. tray_global,
  7374. layer_num,
  7375. e,
  7376. )
  7377. printer_manager.set_tray_change_callback(on_tray_change)
  7378. # Initialize MQTT relay from settings
  7379. async with async_session() as db:
  7380. from backend.app.api.routes.settings import get_setting
  7381. mqtt_settings = {
  7382. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  7383. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  7384. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  7385. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  7386. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  7387. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  7388. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  7389. }
  7390. await mqtt_relay.configure(mqtt_settings)
  7391. # Restore MQTT smart plug subscriptions
  7392. if mqtt_settings.get("mqtt_enabled"):
  7393. from backend.app.models.smart_plug import SmartPlug
  7394. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  7395. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  7396. mqtt_plugs = result.scalars().all()
  7397. restored = 0
  7398. for plug in mqtt_plugs:
  7399. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  7400. restored += 1
  7401. if restored:
  7402. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  7403. # Connect to all active printers
  7404. async with async_session() as db:
  7405. await init_printer_connections(db)
  7406. # Auto-connect to Spoolman if enabled
  7407. async with async_session() as db:
  7408. from backend.app.api.routes.settings import get_setting
  7409. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  7410. spoolman_url = await get_setting(db, "spoolman_url")
  7411. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  7412. try:
  7413. client = await init_spoolman_client(spoolman_url)
  7414. if await client.health_check():
  7415. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  7416. # Ensure the 'tag' extra field exists for RFID/UUID storage
  7417. field_ok = await client.ensure_tag_extra_field()
  7418. if not field_ok:
  7419. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  7420. # Register the BambuStudio slicer-preset fields used by the
  7421. # spool-edit / assign flow. Spoolman rejects PATCHes with
  7422. # unknown extra keys, so these must exist before any update
  7423. # that touches them.
  7424. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  7425. if not await client.ensure_extra_field(field_name):
  7426. logging.warning(
  7427. "Spoolman extra field %r registration failed — "
  7428. "spool slicer-preset edits will return 502",
  7429. field_name,
  7430. )
  7431. else:
  7432. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  7433. except Exception as e:
  7434. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  7435. # Start the print scheduler
  7436. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  7437. # Start the smart plug scheduler for time-based on/off
  7438. smart_plug_manager.start_scheduler()
  7439. # Start the Home Assistant sensor poller (#1148)
  7440. ha_sensor_manager.start()
  7441. # Resume any pending auto-offs that were interrupted by restart
  7442. await smart_plug_manager.resume_pending_auto_offs()
  7443. # Start the notification digest scheduler
  7444. notification_service.start_digest_scheduler()
  7445. # Start the GitHub backup scheduler
  7446. await github_backup_service.start_scheduler()
  7447. # Start the local backup scheduler
  7448. await local_backup_service.start_scheduler()
  7449. await obico_detection_service.start()
  7450. # Start the library trash sweeper (#1008)
  7451. await library_trash_service.start_scheduler()
  7452. # Start the archive auto-purge sweeper (#1008 follow-up)
  7453. await archive_purge_service.start_scheduler()
  7454. # Start AMS history recording
  7455. start_ams_history_recording()
  7456. # Start printer sensor (nozzle / bed / chamber) history recording
  7457. start_printer_sensor_history_recording()
  7458. # Start printer runtime tracking
  7459. start_runtime_tracking()
  7460. # Start SpoolBuddy device watchdog
  7461. start_spoolbuddy_watchdog()
  7462. # Start camera stream orphan cleanup
  7463. start_camera_cleanup()
  7464. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  7465. start_connection_watchdog()
  7466. # One-shot sweep for timelapse session directories orphaned by a crash
  7467. # or restart that happened mid-print (in-memory session tracking can't
  7468. # survive that, and nothing else reaps the leftover frames/output file)
  7469. try:
  7470. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  7471. removed = cleanup_orphaned_timelapse_sessions()
  7472. if removed:
  7473. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  7474. except Exception as e:
  7475. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  7476. # Start expected-print TTL eviction (prevents memory leak when prints are
  7477. # registered but on_print_start never fires)
  7478. start_expected_prints_cleanup()
  7479. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  7480. start_auth_cleanup()
  7481. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  7482. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  7483. from backend.app.services.loop_watchdog import start_loop_watchdog
  7484. start_loop_watchdog()
  7485. # Initialize virtual printer manager and sync from DB
  7486. from backend.app.services.virtual_printer import virtual_printer_manager
  7487. virtual_printer_manager.set_session_factory(async_session)
  7488. virtual_printer_manager.set_printer_manager(printer_manager)
  7489. try:
  7490. await virtual_printer_manager.sync_from_db()
  7491. logging.info("Virtual printer manager synced from database")
  7492. except Exception as e:
  7493. logging.warning("Failed to sync virtual printers: %s", e)
  7494. yield
  7495. # Shutdown
  7496. print_scheduler.stop()
  7497. smart_plug_manager.stop_scheduler()
  7498. ha_sensor_manager.stop()
  7499. notification_service.stop_digest_scheduler()
  7500. github_backup_service.stop_scheduler()
  7501. local_backup_service.stop_scheduler()
  7502. library_trash_service.stop_scheduler()
  7503. archive_purge_service.stop_scheduler()
  7504. obico_detection_service.stop()
  7505. stop_ams_history_recording()
  7506. stop_printer_sensor_history_recording()
  7507. stop_runtime_tracking()
  7508. stop_spoolbuddy_watchdog()
  7509. stop_camera_cleanup()
  7510. stop_connection_watchdog()
  7511. from backend.app.services.loop_watchdog import stop_loop_watchdog
  7512. stop_loop_watchdog()
  7513. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  7514. # cleanly rather than waiting on a queue that nothing will ever fill.
  7515. try:
  7516. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  7517. await shutdown_all_broadcasters()
  7518. except Exception as e:
  7519. logging.warning("Failed to shut down camera broadcasters: %s", e)
  7520. stop_expected_prints_cleanup()
  7521. stop_auth_cleanup()
  7522. printer_manager.disconnect_all()
  7523. await close_spoolman_client()
  7524. # Stop all virtual printer services
  7525. await virtual_printer_manager.stop_all()
  7526. await mqtt_smart_plug_service.disconnect(timeout=2)
  7527. await mqtt_relay.disconnect(timeout=2)
  7528. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  7529. set_shared_http_client(None)
  7530. set_shared_makerworld_http_client(None)
  7531. set_shared_orca_http_client(None)
  7532. await _shared_cloud_http_client.aclose()
  7533. # Checkpoint WAL (SQLite only) and close all database connections
  7534. from backend.app.core.db_dialect import is_sqlite
  7535. if is_sqlite():
  7536. try:
  7537. async with engine.begin() as conn:
  7538. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  7539. logging.info("WAL checkpoint completed")
  7540. except Exception as e:
  7541. logging.warning("WAL checkpoint failed: %s", e)
  7542. await engine.dispose()
  7543. app = FastAPI(
  7544. title=app_settings.app_name,
  7545. description="Archive and manage Bambu Lab 3MF files",
  7546. version=APP_VERSION,
  7547. lifespan=lifespan,
  7548. )
  7549. # =============================================================================
  7550. # Authentication Middleware - Secures ALL API routes by default
  7551. # =============================================================================
  7552. # Public routes that don't require authentication even when auth is enabled
  7553. PUBLIC_API_ROUTES = {
  7554. # Auth routes needed before/during login
  7555. "/api/v1/auth/status",
  7556. "/api/v1/auth/login",
  7557. "/api/v1/auth/setup", # Needed for initial setup and recovery
  7558. # Advanced auth status needed for login page
  7559. "/api/v1/auth/advanced-auth/status",
  7560. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  7561. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  7562. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  7563. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  7564. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  7565. # OIDC routes that must be reachable without a JWT
  7566. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  7567. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  7568. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  7569. # Version check for updates (no sensitive data)
  7570. "/api/v1/updates/version",
  7571. # Metrics endpoint handles its own prometheus_token authentication
  7572. "/api/v1/metrics",
  7573. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  7574. # this BEFORE a JWT is available to pick up the firstboot wizard's
  7575. # hostname / timezone / locale and the chrony NTP-gate state. The
  7576. # response contains user-set defaults and a public sync flag — no
  7577. # secrets. Without this entry the global auth middleware returns 401
  7578. # before the route handler runs, regardless of the route's own
  7579. # "no auth required" intent.
  7580. "/api/v1/system/appliance",
  7581. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  7582. # authenticates with a long-lived ``camwall``-scoped token in the query
  7583. # string — exactly like the camera streams two lists below, and for the same
  7584. # reason (no header to put a JWT in). "Public" here only means the middleware
  7585. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  7586. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  7587. # plain ``camera_stream`` token does NOT open this door.
  7588. "/api/v1/camwall/printers",
  7589. }
  7590. # Route prefixes that are public (for routes with dynamic segments)
  7591. PUBLIC_API_PREFIXES = [
  7592. # WebSocket connections handle their own auth
  7593. "/api/v1/ws",
  7594. # OIDC authorize redirects — include provider_id in path
  7595. "/api/v1/auth/oidc/authorize/",
  7596. ]
  7597. # Route patterns that are public (read-only display data)
  7598. # These are checked with "in path" - needed because browsers load images/videos
  7599. # via <img src> and <video src> which don't include Authorization headers
  7600. PUBLIC_API_PATTERNS = [
  7601. # Thumbnails
  7602. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  7603. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  7604. # Images and media
  7605. "/photos/", # /archives/{id}/photos/{filename}
  7606. "/project-image/", # /archives/{id}/project-image/{path}
  7607. "/qrcode", # /archives/{id}/qrcode
  7608. "/timelapse", # /archives/{id}/timelapse (video)
  7609. "/cover", # /printers/{id}/cover
  7610. "/icon", # /external-links/{id}/icon
  7611. # Camera (streams loaded via <img> tag)
  7612. "/camera/stream", # /printers/{id}/camera/stream
  7613. "/camera/snapshot", # /printers/{id}/camera/snapshot
  7614. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  7615. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  7616. # string (same reasoning as the camera streams above — no header to carry a
  7617. # JWT). "Public" only means the middleware steps aside; the route still runs
  7618. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  7619. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  7620. "/overlay-status", # /printers/{id}/overlay-status
  7621. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  7622. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  7623. # download token in the URL path instead.
  7624. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  7625. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  7626. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  7627. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  7628. ]
  7629. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  7630. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  7631. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  7632. Format: comma-separated list of ``scheme://host[:port]`` origins.
  7633. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  7634. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  7635. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  7636. Invalid entries are dropped with a warning rather than failing startup, so
  7637. a typo in one origin doesn't take the whole deployment down.
  7638. """
  7639. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  7640. if not raw:
  7641. return ()
  7642. valid: list[str] = []
  7643. for item in raw.split(","):
  7644. candidate = item.strip()
  7645. if not candidate:
  7646. continue
  7647. try:
  7648. parsed = urlparse(candidate)
  7649. except ValueError as e:
  7650. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  7651. continue
  7652. if parsed.scheme not in ("http", "https"):
  7653. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  7654. continue
  7655. if not parsed.netloc:
  7656. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  7657. continue
  7658. if parsed.path and parsed.path != "/":
  7659. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  7660. continue
  7661. if parsed.query or parsed.fragment:
  7662. _security_headers_logger.warning(
  7663. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  7664. )
  7665. continue
  7666. if "*" in parsed.netloc:
  7667. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  7668. continue
  7669. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  7670. if valid:
  7671. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  7672. return tuple(valid)
  7673. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  7674. def _frame_ancestors(default_value: str) -> str:
  7675. """Compose the ``frame-ancestors`` CSP directive (#1191).
  7676. ``default_value`` is the strict directive used when the operator has not
  7677. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  7678. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  7679. Settings URL builder's preview). When trusted origins
  7680. are configured, ``'self'`` is always included so same-origin embedding never
  7681. breaks even if an operator forgets to add their own origin to the list.
  7682. """
  7683. if _TRUSTED_FRAME_ORIGINS:
  7684. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  7685. return f"frame-ancestors {default_value};"
  7686. @app.middleware("http")
  7687. async def security_headers_middleware(request, call_next):
  7688. """Add standard HTTP security headers to every response."""
  7689. # Per-request nonce stamped into `script-src` (#1460). On its own this
  7690. # changes nothing for Bambuddy's own pages — index.html has no inline
  7691. # scripts since the SW registration moved to /sw-register.js. The reason
  7692. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  7693. # script injected into the HTML on the edge, with a fresh hash on every
  7694. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  7695. # it clones the same nonce onto its injected <script>, and the inline
  7696. # script passes the policy without us needing 'unsafe-inline'. See
  7697. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  7698. csp_nonce = secrets.token_urlsafe(16)
  7699. response = await call_next(request)
  7700. response.headers["X-Content-Type-Options"] = "nosniff"
  7701. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  7702. # browsers honour CSP frame-ancestors instead, and the legacy
  7703. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  7704. # When operators have explicitly allowlisted trusted frame origins (#1191
  7705. # — typically Home Assistant on a different port), drop X-Frame-Options
  7706. # and let the CSP-side frame-ancestors directive govern embedding.
  7707. if not _TRUSTED_FRAME_ORIGINS:
  7708. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  7709. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  7710. # Content-Security-Policy for the React SPA.
  7711. # Notes:
  7712. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  7713. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  7714. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  7715. # - media-src blob:: timelapse video player uses Blob URLs.
  7716. # - font-src data:: some icon fonts are embedded as data URIs.
  7717. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  7718. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  7719. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  7720. # default CSP would render a blank page.
  7721. response.headers["Content-Security-Policy"] = (
  7722. "default-src 'self'; "
  7723. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  7724. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  7725. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  7726. "connect-src 'self'; "
  7727. "font-src 'self' data: https://fonts.gstatic.com; "
  7728. "worker-src 'self' blob:; "
  7729. "object-src 'none'; "
  7730. "base-uri 'self'; " + _frame_ancestors("'none'")
  7731. )
  7732. else:
  7733. # The streaming overlay is embedded same-origin by the URL builder's
  7734. # preview in Settings (#1422), so this branch allows 'self'.
  7735. # Embedding from anywhere else is still refused: 'self'
  7736. # only permits a framer on this origin, which is Bambuddy's own UI, so
  7737. # a clickjacking page on another host is blocked exactly as before.
  7738. # (The overlay draws status over a camera feed and its only interactive
  7739. # element is the logo link, so there is nothing to bait a click into
  7740. # even from a same-origin framer.) Cross-origin embedding of the
  7741. # overlay — Home Assistant on another port — remains what
  7742. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  7743. # allowlist in.
  7744. embeddable_same_origin = request.url.path.startswith("/overlay/")
  7745. response.headers["Content-Security-Policy"] = (
  7746. "default-src 'self'; "
  7747. f"script-src 'self' 'nonce-{csp_nonce}'; "
  7748. "style-src 'self' 'unsafe-inline'; "
  7749. "img-src 'self' data: blob:; "
  7750. "media-src 'self' blob:; "
  7751. "connect-src 'self' ws: wss:; "
  7752. "font-src 'self' data:; "
  7753. "object-src 'none'; "
  7754. "base-uri 'self'; "
  7755. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  7756. )
  7757. if request.url.scheme == "https":
  7758. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  7759. return response
  7760. @app.middleware("http")
  7761. async def auth_middleware(request, call_next):
  7762. """Enforce authentication on all API routes when auth is enabled.
  7763. This middleware provides defense-in-depth by checking auth at the API gateway level,
  7764. regardless of whether individual routes have auth dependencies.
  7765. """
  7766. from starlette.responses import JSONResponse
  7767. path = request.url.path
  7768. # Only apply to API routes
  7769. if not path.startswith("/api/"):
  7770. return await call_next(request)
  7771. # Allow public routes
  7772. if path in PUBLIC_API_ROUTES:
  7773. return await call_next(request)
  7774. # Allow public prefixes
  7775. for prefix in PUBLIC_API_PREFIXES:
  7776. if path.startswith(prefix):
  7777. return await call_next(request)
  7778. # Allow public patterns (read-only display data like thumbnails)
  7779. for pattern in PUBLIC_API_PATTERNS:
  7780. if pattern in path:
  7781. return await call_next(request)
  7782. # Check if auth is enabled. Fail CLOSED on any exception during the
  7783. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  7784. # an attacker who could force a DB exception (e.g. file-descriptor
  7785. # exhaustion via login flood) bypass auth on every protected endpoint.
  7786. try:
  7787. async with async_session() as db:
  7788. from backend.app.core.auth import is_auth_enabled
  7789. auth_enabled = await is_auth_enabled(db)
  7790. if not auth_enabled:
  7791. # Auth disabled, allow all requests
  7792. return await call_next(request)
  7793. except Exception:
  7794. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  7795. return JSONResponse(
  7796. status_code=503,
  7797. content={"detail": "Authentication service temporarily unavailable"},
  7798. )
  7799. # Auth is enabled - require valid token
  7800. auth_header = request.headers.get("Authorization")
  7801. x_api_key = request.headers.get("X-API-Key")
  7802. # Check for API key auth first
  7803. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  7804. # API key authentication - let the request through to be validated by route handler
  7805. # API keys are validated per-route since they have different permission levels
  7806. return await call_next(request)
  7807. # Check for JWT auth
  7808. if not auth_header or not auth_header.startswith("Bearer "):
  7809. return JSONResponse(
  7810. status_code=401,
  7811. content={"detail": "Authentication required"},
  7812. headers={"WWW-Authenticate": "Bearer"},
  7813. )
  7814. # Validate JWT token
  7815. import jwt
  7816. try:
  7817. from backend.app.core.auth import (
  7818. ALGORITHM,
  7819. SECRET_KEY,
  7820. _is_token_fresh,
  7821. get_user_by_username,
  7822. is_jti_revoked,
  7823. )
  7824. token = auth_header.replace("Bearer ", "")
  7825. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  7826. username = payload.get("sub")
  7827. if not username:
  7828. raise ValueError("No username in token")
  7829. jti = payload.get("jti")
  7830. if not jti:
  7831. raise ValueError("No jti in token")
  7832. iat = payload.get("iat")
  7833. # Verify user exists, is active, and token is still fresh (L-R8-A).
  7834. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  7835. # this session so the gateway adds a single pooled checkout, not two (#2572).
  7836. async with async_session() as db:
  7837. if await is_jti_revoked(jti, db):
  7838. return JSONResponse(
  7839. status_code=401,
  7840. content={"detail": "Token has been revoked"},
  7841. headers={"WWW-Authenticate": "Bearer"},
  7842. )
  7843. user = await get_user_by_username(db, username)
  7844. if not user or not user.is_active:
  7845. return JSONResponse(
  7846. status_code=401,
  7847. content={"detail": "User not found or inactive"},
  7848. headers={"WWW-Authenticate": "Bearer"},
  7849. )
  7850. if not _is_token_fresh(iat, user):
  7851. return JSONResponse(
  7852. status_code=401,
  7853. content={"detail": "Token no longer valid"},
  7854. headers={"WWW-Authenticate": "Bearer"},
  7855. )
  7856. except jwt.ExpiredSignatureError:
  7857. return JSONResponse(
  7858. status_code=401,
  7859. content={"detail": "Token has expired"},
  7860. headers={"WWW-Authenticate": "Bearer"},
  7861. )
  7862. except (jwt.InvalidTokenError, ValueError, Exception):
  7863. return JSONResponse(
  7864. status_code=401,
  7865. content={"detail": "Invalid token"},
  7866. headers={"WWW-Authenticate": "Bearer"},
  7867. )
  7868. return await call_next(request)
  7869. @app.middleware("http")
  7870. async def trace_id_middleware(request, call_next):
  7871. """Stamp every HTTP request with a trace ID and echo it back.
  7872. Decorated AFTER auth_middleware on purpose: Starlette stacks
  7873. @app.middleware decorators LIFO, so the last-decorated runs first
  7874. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  7875. which means auth-middleware log lines (and every line emitted on the
  7876. way down to and back from the route handler) all carry the same
  7877. trace ID. If we put it before auth, auth's logs would be stamped
  7878. with the *previous* request's ID — useless for correlation.
  7879. Honours an inbound ``X-Trace-Id`` header so callers running their
  7880. own tracing can correlate their span IDs with our log lines, but
  7881. only if the value passes the whitelist gate in
  7882. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  7883. rejected (too long, contains control chars, etc.) silently triggers
  7884. a freshly minted server-side ID rather than failing the request.
  7885. The minted (or echoed) ID is set on a ContextVar so that every log
  7886. record emitted during the request — application logs *and* uvicorn's
  7887. access log — carries it via TraceIDFilter, and is also written to
  7888. the ``X-Trace-Id`` response header so clients can pin a server-side
  7889. log search to the exact request they made.
  7890. """
  7891. from backend.app.core.trace import (
  7892. generate_trace_id,
  7893. normalise_inbound_trace_id,
  7894. trace_id_var,
  7895. )
  7896. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  7897. trace_id = inbound if inbound is not None else generate_trace_id()
  7898. token = trace_id_var.set(trace_id)
  7899. try:
  7900. response = await call_next(request)
  7901. finally:
  7902. # Reset the ContextVar so a record emitted in a totally
  7903. # unrelated background task that just happens to inherit this
  7904. # context doesn't keep referencing this request's ID forever.
  7905. # In practice ContextVar.reset is best-effort under asyncio
  7906. # task-spawn semantics, but the cost is one attribute write so
  7907. # we may as well do it.
  7908. trace_id_var.reset(token)
  7909. response.headers["X-Trace-Id"] = trace_id
  7910. return response
  7911. # API routes
  7912. app.include_router(auth.router, prefix=app_settings.api_prefix)
  7913. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  7914. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  7915. app.include_router(users.router, prefix=app_settings.api_prefix)
  7916. app.include_router(groups.router, prefix=app_settings.api_prefix)
  7917. app.include_router(printers.router, prefix=app_settings.api_prefix)
  7918. app.include_router(archives.router, prefix=app_settings.api_prefix)
  7919. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  7920. app.include_router(finance.router, prefix=app_settings.api_prefix)
  7921. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  7922. app.include_router(labels.router, prefix=app_settings.api_prefix)
  7923. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  7924. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  7925. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  7926. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  7927. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  7928. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  7929. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  7930. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  7931. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  7932. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  7933. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  7934. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  7935. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  7936. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  7937. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  7938. app.include_router(updates.router, prefix=app_settings.api_prefix)
  7939. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  7940. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  7941. app.include_router(camera.router, prefix=app_settings.api_prefix)
  7942. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  7943. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  7944. app.include_router(projects.router, prefix=app_settings.api_prefix)
  7945. app.include_router(library.router, prefix=app_settings.api_prefix)
  7946. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  7947. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  7948. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  7949. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  7950. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  7951. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  7952. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  7953. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  7954. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  7955. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  7956. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  7957. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  7958. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  7959. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  7960. app.include_router(system.router, prefix=app_settings.api_prefix)
  7961. app.include_router(support.router, prefix=app_settings.api_prefix)
  7962. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  7963. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  7964. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  7965. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  7966. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  7967. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  7968. app.include_router(obico.router, prefix=app_settings.api_prefix)
  7969. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  7970. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  7971. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  7972. # Serve static files (React build)
  7973. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  7974. app.mount(
  7975. "/assets",
  7976. StaticFiles(directory=app_settings.static_dir / "assets"),
  7977. name="assets",
  7978. )
  7979. if (app_settings.static_dir / "img").exists():
  7980. app.mount(
  7981. "/img",
  7982. StaticFiles(directory=app_settings.static_dir / "img"),
  7983. name="img",
  7984. )
  7985. if (app_settings.static_dir / "icons").exists():
  7986. app.mount(
  7987. "/icons",
  7988. StaticFiles(directory=app_settings.static_dir / "icons"),
  7989. name="icons",
  7990. )
  7991. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  7992. # falls through to the SPA catch-all and returns index.html, which the
  7993. # browser's font sanitizer rejects ("downloadable font: rejected by
  7994. # sanitizer").
  7995. if (app_settings.static_dir / "fonts").exists():
  7996. app.mount(
  7997. "/fonts",
  7998. StaticFiles(directory=app_settings.static_dir / "fonts"),
  7999. name="fonts",
  8000. )
  8001. @app.get("/")
  8002. async def serve_frontend():
  8003. """Serve the React frontend."""
  8004. index_file = app_settings.static_dir / "index.html"
  8005. if index_file.exists():
  8006. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  8007. return {
  8008. "message": "Bambuddy API",
  8009. "docs": "/docs",
  8010. "frontend": "Build and place React app in /static directory",
  8011. }
  8012. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  8013. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  8014. # forever, but the HTML wrapping it is the only file that knows which hash
  8015. # is current. Without explicit cache-control headers Chromium decides
  8016. # heuristically (typically 10% of the time since Last-Modified) and on
  8017. # long-running kiosks happily serves stale HTML across browser restarts.
  8018. # That stale HTML references an old bundle hash, the old bundle is also
  8019. # in the disk cache, and the user ends up running pre-update JS forever
  8020. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  8021. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  8022. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  8023. @app.get("/health")
  8024. async def health_check():
  8025. """Health check endpoint."""
  8026. return {"status": "healthy"}
  8027. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  8028. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  8029. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  8030. # in deployment debugging.
  8031. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  8032. async def serve_manifest():
  8033. """Serve PWA manifest."""
  8034. manifest_file = app_settings.static_dir / "manifest.json"
  8035. if manifest_file.exists():
  8036. return FileResponse(manifest_file, media_type="application/manifest+json")
  8037. return {"error": "Manifest not found"}
  8038. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  8039. async def serve_service_worker():
  8040. """Serve service worker."""
  8041. sw_file = app_settings.static_dir / "sw.js"
  8042. if sw_file.exists():
  8043. return FileResponse(
  8044. sw_file,
  8045. media_type="application/javascript",
  8046. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  8047. )
  8048. return {"error": "Service worker not found"}
  8049. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  8050. async def serve_sw_register():
  8051. """Serve the service-worker registration bootstrap script.
  8052. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  8053. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  8054. """
  8055. reg_file = app_settings.static_dir / "sw-register.js"
  8056. if reg_file.exists():
  8057. return FileResponse(reg_file, media_type="application/javascript")
  8058. return {"error": "sw-register.js not found"}
  8059. # ── GCode viewer static files ────────────────────────────────────────────────
  8060. # Catch-all route for React Router (must be last)
  8061. @app.get("/{full_path:path}")
  8062. async def serve_spa(full_path: str):
  8063. """Serve React app for client-side routing."""
  8064. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  8065. if full_path.startswith("api/"):
  8066. from fastapi import HTTPException
  8067. raise HTTPException(status_code=404, detail="Not found")
  8068. index_file = app_settings.static_dir / "index.html"
  8069. if index_file.exists():
  8070. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  8071. return {"error": "Frontend not built"}