main.py 389 KB

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