main.py 460 KB

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