main.py 386 KB

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