main.py 297 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259
  1. import asyncio
  2. import logging
  3. import mimetypes as _mimetypes
  4. import os
  5. import posixpath
  6. import secrets
  7. import time
  8. from contextlib import asynccontextmanager
  9. from datetime import datetime, timedelta, timezone
  10. from logging.handlers import RotatingFileHandler
  11. from pathlib import Path
  12. from urllib.parse import urlparse
  13. from fastapi import FastAPI
  14. from fastapi.responses import FileResponse
  15. from fastapi.staticfiles import StaticFiles
  16. from sqlalchemy import delete, or_, select, text
  17. from backend.app.api.routes import (
  18. ams_history,
  19. api_keys,
  20. archive_purge,
  21. archives,
  22. auth,
  23. background_dispatch as background_dispatch_routes,
  24. bug_report,
  25. camera,
  26. cloud,
  27. discovery,
  28. external_links,
  29. filaments,
  30. firmware,
  31. github_backup,
  32. groups,
  33. inventory,
  34. kprofiles,
  35. labels,
  36. library,
  37. library_trash,
  38. local_backup,
  39. local_presets,
  40. maintenance,
  41. makerworld,
  42. metrics,
  43. mfa,
  44. notification_templates,
  45. notifications,
  46. obico,
  47. orca_cloud,
  48. pending_uploads,
  49. print_log,
  50. print_queue,
  51. printers,
  52. projects,
  53. settings as settings_routes,
  54. slice_jobs,
  55. slicer_presets,
  56. smart_plugs,
  57. spoolbuddy,
  58. spoolman,
  59. spoolman_inventory,
  60. support,
  61. system,
  62. updates,
  63. user_notifications,
  64. users,
  65. virtual_printers,
  66. webhook,
  67. websocket,
  68. )
  69. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  70. from backend.app.api.routes.support import init_debug_logging
  71. from backend.app.core.config import APP_VERSION, settings as app_settings
  72. from backend.app.core.database import async_session, engine, init_db
  73. from backend.app.core.tasks import spawn_background_task
  74. from backend.app.core.websocket import ws_manager
  75. from backend.app.models.smart_plug import SmartPlug
  76. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  77. from backend.app.services.archive_purge import archive_purge_service
  78. from backend.app.services.background_dispatch import background_dispatch
  79. from backend.app.services.bambu_ftp import (
  80. FileNotOnPrinterError,
  81. cache_3mf_download,
  82. clear_3mf_cache,
  83. download_file_async,
  84. get_cached_3mf,
  85. get_ftp_retry_settings,
  86. with_ftp_retry,
  87. )
  88. from backend.app.services.bambu_mqtt import PrinterState
  89. from backend.app.services.github_backup import github_backup_service
  90. from backend.app.services.homeassistant import homeassistant_service
  91. from backend.app.services.library_trash import library_trash_service
  92. from backend.app.services.local_backup import local_backup_service
  93. from backend.app.services.mqtt_relay import mqtt_relay
  94. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  95. from backend.app.services.notification_service import notification_service
  96. from backend.app.services.obico_detection import obico_detection_service
  97. from backend.app.services.print_scheduler import scheduler as print_scheduler
  98. from backend.app.services.printer_manager import (
  99. init_printer_connections,
  100. parse_plate_id,
  101. printer_manager,
  102. printer_state_to_dict,
  103. )
  104. from backend.app.services.smart_plug_manager import smart_plug_manager
  105. from backend.app.services.spool_assignment_notifications import (
  106. notify_missing_spool_assignments_on_print_start,
  107. )
  108. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  109. from backend.app.services.spoolman_tracking import (
  110. cleanup_tracking as _cleanup_spoolman_tracking,
  111. report_usage as _report_spoolman_usage,
  112. store_print_data as _store_spoolman_print_data,
  113. )
  114. from backend.app.services.tasmota import tasmota_service
  115. # =============================================================================
  116. # Dependency Check - runs before other imports to give helpful error messages
  117. # =============================================================================
  118. def _start_error_server(missing_packages: list):
  119. """Start a minimal HTTP server to display dependency errors in browser."""
  120. import os
  121. import signal
  122. from http.server import BaseHTTPRequestHandler, HTTPServer
  123. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  124. html = f"""<!DOCTYPE html>
  125. <html>
  126. <head>
  127. <title>Bambuddy - Setup Required</title>
  128. <style>
  129. body {{
  130. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  131. background: #0f172a; color: #e2e8f0;
  132. display: flex; justify-content: center; align-items: center;
  133. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  134. }}
  135. .container {{
  136. background: #1e293b; border-radius: 12px; padding: 40px;
  137. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  138. }}
  139. h1 {{ color: #f87171; margin-bottom: 10px; }}
  140. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  141. .packages {{
  142. background: #0f172a; border-radius: 8px; padding: 20px;
  143. margin: 20px 0; text-align: left;
  144. }}
  145. .packages ul {{ margin: 0; padding-left: 20px; }}
  146. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  147. .command {{
  148. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  149. margin: 15px 0; font-family: monospace; color: #4ade80;
  150. text-align: left; overflow-x: auto;
  151. }}
  152. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  153. </style>
  154. </head>
  155. <body>
  156. <div class="container">
  157. <h1>Setup Required</h1>
  158. <h2>Missing Python packages</h2>
  159. <div class="packages"><ul>{packages_html}</ul></div>
  160. <p>To fix, run this command on your server:</p>
  161. <div class="command">pip install -r requirements.txt</div>
  162. <p>Or if using a virtual environment:</p>
  163. <div class="command">./venv/bin/pip install -r requirements.txt</div>
  164. <p class="note">After installing, restart Bambuddy:<br>
  165. <code>sudo systemctl restart bambuddy</code></p>
  166. </div>
  167. </body>
  168. </html>"""
  169. class ErrorHandler(BaseHTTPRequestHandler):
  170. def do_GET(self):
  171. self.send_response(503)
  172. self.send_header("Content-type", "text/html")
  173. self.end_headers()
  174. self.wfile.write(html.encode())
  175. def log_message(self, format, *args):
  176. print(f"[Error Server] {args[0]}")
  177. port = int(os.environ.get("PORT", 8000))
  178. print(f"\nStarting error server on http://0.0.0.0:{port}")
  179. print("Visit this URL in your browser to see the error details.\n")
  180. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  181. def shutdown(signum, frame):
  182. print("\nShutting down error server...")
  183. raise SystemExit(0)
  184. signal.signal(signal.SIGTERM, shutdown)
  185. signal.signal(signal.SIGINT, shutdown)
  186. server.serve_forever()
  187. def check_dependencies():
  188. """Check that all required packages are installed."""
  189. missing = []
  190. # Map of import name -> package name (for pip install)
  191. required = {
  192. "jwt": "PyJWT",
  193. "fastapi": "fastapi",
  194. "uvicorn": "uvicorn",
  195. "sqlalchemy": "sqlalchemy",
  196. "aiosqlite": "aiosqlite",
  197. "pydantic": "pydantic",
  198. "paho.mqtt": "paho-mqtt",
  199. }
  200. for module, package in required.items():
  201. try:
  202. __import__(module)
  203. except ImportError:
  204. missing.append(package)
  205. if missing:
  206. print("\n" + "=" * 60)
  207. print("ERROR: Missing required Python packages!")
  208. print("=" * 60)
  209. print(f"\nMissing packages: {', '.join(missing)}")
  210. print("\nTo fix, run:")
  211. print(" pip install -r requirements.txt")
  212. print("\nOr if using a virtual environment:")
  213. print(" ./venv/bin/pip install -r requirements.txt")
  214. print("=" * 60 + "\n")
  215. _start_error_server(missing)
  216. check_dependencies()
  217. # =============================================================================
  218. # Import settings first for logging configuration
  219. # Configure logging based on settings
  220. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  221. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  222. log_level = getattr(logging, log_level_str, logging.INFO)
  223. # Trace ID column ([-] when no request scope is active — startup, MQTT
  224. # callbacks, scheduled tasks not chained from a request — so the column
  225. # stays visually aligned and missing values are obvious in grep). See
  226. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  227. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  228. # Create root logger
  229. root_logger = logging.getLogger()
  230. root_logger.setLevel(log_level)
  231. # Trace-ID injection: this filter populates record.trace_id from the
  232. # per-request ContextVar so the format string above can reference it.
  233. # Attached to each HANDLER (not the root logger) because Python's
  234. # logging semantics only invoke a logger's filters on records that
  235. # *originated* at that logger — records propagated up from child
  236. # loggers (every named logger in the app) never trigger root's filter.
  237. # Putting it on the handlers means every record any handler emits gets
  238. # trace_id injected just before the formatter runs, regardless of which
  239. # logger created the record. Without this, the formatter raises
  240. # KeyError on every child-logger record and the record is silently
  241. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  242. # partially" bug we hit. See backend/app/core/trace.py for the
  243. # ContextVar the filter reads.
  244. from backend.app.core.trace import TraceIDFilter
  245. _trace_id_filter = TraceIDFilter()
  246. # Console handler - always enabled
  247. console_handler = logging.StreamHandler()
  248. console_handler.setLevel(log_level)
  249. console_handler.setFormatter(logging.Formatter(log_format))
  250. console_handler.addFilter(_trace_id_filter)
  251. root_logger.addHandler(console_handler)
  252. # File handler - only in production or if explicitly enabled
  253. if app_settings.log_to_file:
  254. log_file = app_settings.log_dir / "bambuddy.log"
  255. file_handler = RotatingFileHandler(
  256. log_file,
  257. maxBytes=5 * 1024 * 1024, # 5MB
  258. backupCount=3,
  259. encoding="utf-8",
  260. )
  261. file_handler.setLevel(log_level)
  262. file_handler.setFormatter(logging.Formatter(log_format))
  263. file_handler.addFilter(_trace_id_filter)
  264. root_logger.addHandler(file_handler)
  265. logging.info("Logging to file: %s", log_file)
  266. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  267. # access logger with propagate=False by default, so without this attach
  268. # there is no on-disk record of which endpoint triggered a server-state
  269. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  270. # for exactly this reason. Filtered to write methods only
  271. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  272. # frontend don't churn the rotation window faster than it's useful.
  273. from backend.app.core.logging_filters import (
  274. CancelledPoolNoiseFilter,
  275. WriteRequestsOnlyFilter,
  276. )
  277. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  278. uvicorn_access_logger.addHandler(file_handler)
  279. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  280. # Uvicorn's access logger has propagate=False (its own default), so the
  281. # root-attached TraceIDFilter never sees these records. Attach a
  282. # second instance directly so HTTP access lines carry the same trace
  283. # ID column as the application logs they correlate with.
  284. uvicorn_access_logger.addFilter(TraceIDFilter())
  285. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  286. # BaseHTTPMiddleware cancelling the inner task scope on client
  287. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  288. # underlying transaction leak; this filter only suppresses the residual
  289. # log records that pre-existing pools still emit during their cleanup.
  290. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  291. # Reduce noise from third-party libraries in production
  292. if not app_settings.debug:
  293. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  294. logging.getLogger("httpcore").setLevel(logging.WARNING)
  295. logging.getLogger("httpx").setLevel(logging.WARNING)
  296. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  297. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  298. # Track active prints: {(printer_id, filename): archive_id}
  299. _active_prints: dict[tuple[int, str], int] = {}
  300. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  301. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  302. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  303. # the first connected status update for that connection; transitions back
  304. # to False whenever we observe `state.connected = False` so the next
  305. # reconnect re-arms reconciliation. Keyed by printer_id.
  306. _printer_reconciled_since_connect: dict[int, bool] = {}
  307. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  308. # {(printer_id, filename): archive_id}
  309. _expected_prints: dict[tuple[int, str], int] = {}
  310. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  311. # Used by usage tracker to map 3MF slots to physical AMS trays
  312. _print_ams_mappings: dict[int, list[int]] = {}
  313. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  314. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  315. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  316. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  317. # for the queue path. Cleared on print completion or TTL eviction.
  318. _print_plate_ids: dict[int, int] = {}
  319. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  320. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  321. _last_progress_milestone: dict[int, int] = {}
  322. # Track whether first layer complete notification has been sent for current print
  323. _first_layer_notified: dict[int, bool] = {}
  324. # Track HMS errors that have been notified: {printer_id: set of error codes}
  325. # This prevents sending duplicate notifications for the same error
  326. _notified_hms_errors: dict[int, set[str]] = {}
  327. # Track when HMS errors were last seen: {printer_id: timestamp}
  328. # Used to debounce clearing — prevents flapping errors from re-triggering notifications
  329. _hms_last_seen: dict[int, float] = {}
  330. _HMS_CLEAR_GRACE_SECONDS = 30.0
  331. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  332. # Used for snapshot-diff detection at print completion
  333. _timelapse_baselines: dict[int, set[str]] = {}
  334. # Track printers waiting for bed to cool after print completion.
  335. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  336. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  337. _bed_cool_waiters: dict[int, dict] = {}
  338. # Track printers where the user explicitly stopped the print from the queue UI.
  339. # When on_print_complete fires with status "failed" for these printers we treat it
  340. # as "cancelled" (stopped by user) so the correct notification email is sent.
  341. _user_stopped_printers: set[int] = set()
  342. # HMS short-code → human-readable failure reason. Used by _dispatch_archive_update
  343. # when status="failed" to label the print's failure_reason in archives.
  344. #
  345. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  346. # which is wrong on two counts:
  347. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  348. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  349. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  350. # the public wiki) as part of its user-cancel sequence. Matching on the module
  351. # alone caused user-cancellations to be archived as "Layer shift" failures.
  352. # We now match by full short code only — anything not in this map leaves
  353. # failure_reason=None rather than guessing.
  354. _HMS_FAILURE_REASONS: dict[str, str] = {
  355. # Layer shift / step loss
  356. "0300_4057": "Layer shift",
  357. "0300_4068": "Layer shift",
  358. "0300_800C": "Layer shift",
  359. # Filament runout (printer-side & per-AMS-slot)
  360. "0300_8004": "Filament runout",
  361. "0700_8011": "Filament runout",
  362. "0701_8011": "Filament runout",
  363. "0702_8011": "Filament runout",
  364. "0703_8011": "Filament runout",
  365. "0704_8011": "Filament runout",
  366. "0705_8011": "Filament runout",
  367. "0706_8011": "Filament runout",
  368. "0707_8011": "Filament runout",
  369. "07FF_8011": "Filament runout",
  370. # Clogged nozzle / extruder
  371. "0300_4006": "Clogged nozzle",
  372. "0300_8016": "Clogged nozzle",
  373. "0300_801C": "Clogged nozzle",
  374. "0700_8003": "Clogged nozzle",
  375. "0700_8007": "Clogged nozzle",
  376. "0700_8013": "Clogged nozzle",
  377. "0701_8003": "Clogged nozzle",
  378. "0701_8007": "Clogged nozzle",
  379. "0701_8013": "Clogged nozzle",
  380. "0702_8003": "Clogged nozzle",
  381. }
  382. def _hms_short_code(attr: int, code: int | str) -> str:
  383. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  384. if isinstance(code, str):
  385. code_int = int(code.replace("0x", ""), 16) if code else 0
  386. else:
  387. code_int = int(code or 0)
  388. attr_int = int(attr or 0)
  389. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  390. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  391. """Derive a human-readable failure_reason for an archived print.
  392. Returns "User cancelled" for cancelled/aborted prints; for failed prints,
  393. returns the first matching reason from _HMS_FAILURE_REASONS, or None when
  394. no HMS code matches (don't guess — null is honest).
  395. """
  396. if status in ("aborted", "cancelled"):
  397. return "User cancelled"
  398. if status != "failed":
  399. return None
  400. for err in hms_errors or []:
  401. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  402. if short_code in _HMS_FAILURE_REASONS:
  403. return _HMS_FAILURE_REASONS[short_code]
  404. return None
  405. # Track created_by_id for expected prints so the user email can be sent even when
  406. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  407. # {(printer_id, filename): created_by_id}
  408. _expected_print_creators: dict[tuple[int, str], int] = {}
  409. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  410. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  411. # updates for the same printer in quick succession (~30 ms apart, observed in
  412. # the wild on H2D + dual AMS).
  413. #
  414. # Without this serialisation, two concurrent on_ams_change callbacks each read
  415. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  416. # the second commit hits
  417. # IntegrityError: duplicate key value violates unique constraint
  418. # "spool_assignment_printer_id_ams_id_tray_id_key"
  419. # SQLite's WAL serial-write semantics had been silently swallowing the race
  420. # until optional Postgres support landed (asyncpg allows true concurrent
  421. # transactions and surfaces the constraint violation).
  422. #
  423. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  424. # assign) are inside the lock. The Spoolman sync block further down stays
  425. # concurrent because it's network-bound and idempotent.
  426. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  427. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  428. """Return the per-printer assignment lock, creating it on first use."""
  429. lock = _ams_assignment_locks.get(printer_id)
  430. if lock is None:
  431. lock = asyncio.Lock()
  432. _ams_assignment_locks[printer_id] = lock
  433. return lock
  434. # TTL for expected-print entries: evict registrations older than this to prevent
  435. # unbounded growth when a print is registered but never starts (e.g. printer
  436. # disconnect, app restart, print started from the printer panel).
  437. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  438. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  439. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  440. # Cleanup loop interval
  441. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  442. _expected_prints_cleanup_task: asyncio.Task | None = None
  443. async def _get_plug_energy(plug, db) -> dict | None:
  444. """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
  445. For HA plugs, configures the service with current settings from DB.
  446. For MQTT plugs, returns data from the subscription service.
  447. For REST plugs, polls the status URL with JSON path extraction.
  448. """
  449. if plug.plug_type == "homeassistant":
  450. from backend.app.api.routes.settings import get_homeassistant_settings
  451. ha_settings = await get_homeassistant_settings(db)
  452. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  453. return await homeassistant_service.get_energy(plug)
  454. elif plug.plug_type == "mqtt":
  455. # MQTT plugs report "today" energy, not lifetime total
  456. # For per-print tracking, we use "today" as the counter (resets at midnight)
  457. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  458. if mqtt_data:
  459. return {
  460. "power": mqtt_data.power,
  461. "today": mqtt_data.energy,
  462. "total": mqtt_data.energy, # Use today as total for per-print calculations
  463. }
  464. return None
  465. elif plug.plug_type == "rest":
  466. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  467. return await rest_smart_plug_service.get_energy(plug)
  468. else:
  469. return await tasmota_service.get_energy(plug)
  470. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  471. """Capture the smart plug lifetime counter on the archive at print start.
  472. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  473. tracking survives a backend restart mid-print. The print-end handler reads
  474. this value back from the DB and computes the delta against the current
  475. plug counter.
  476. """
  477. _logger = logging.getLogger(__name__)
  478. try:
  479. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  480. plug = plug_result.scalar_one_or_none()
  481. if not plug:
  482. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  483. return False
  484. energy = await _get_plug_energy(plug, db)
  485. if not energy or energy.get("total") is None:
  486. _logger.warning("[ENERGY] No 'total' in energy response for archive %s", archive.id)
  487. return False
  488. archive.energy_start_kwh = float(energy["total"])
  489. await db.commit()
  490. _logger.info(
  491. "[ENERGY] Recorded starting energy%s for archive %s: %s kWh",
  492. f" ({context})" if context else "",
  493. archive.id,
  494. energy["total"],
  495. )
  496. return True
  497. except Exception as e:
  498. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  499. return False
  500. def register_expected_print(
  501. printer_id: int,
  502. filename: str,
  503. archive_id: int,
  504. ams_mapping: list[int] | None = None,
  505. created_by_id: int | None = None,
  506. plate_id: int | None = None,
  507. ):
  508. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  509. # Store with multiple filename variations to catch different naming patterns
  510. _expected_prints[(printer_id, filename)] = archive_id
  511. # Also store without .3mf extension if present
  512. if filename.endswith(".3mf"):
  513. base = filename[:-4]
  514. _expected_prints[(printer_id, base)] = archive_id
  515. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  516. # Store AMS mapping for usage tracking at print completion
  517. if ams_mapping is not None:
  518. _print_ams_mappings[archive_id] = ams_mapping
  519. # Store plate_id for usage tracking when this is a single-plate dispatch from
  520. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  521. # file's filament total to the spool instead of just the printed plate (#1697).
  522. if plate_id is not None:
  523. _print_plate_ids[archive_id] = plate_id
  524. # Store created_by_id so the user start email can be sent even when the archive
  525. # itself has no created_by_id (e.g. library-file-based queue prints)
  526. if created_by_id is not None:
  527. _expected_print_creators[(printer_id, filename)] = created_by_id
  528. if filename.endswith(".3mf"):
  529. base = filename[:-4]
  530. _expected_print_creators[(printer_id, base)] = created_by_id
  531. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  532. # Record registration time for TTL-based eviction
  533. _registered_at = time.monotonic()
  534. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  535. if filename.endswith(".3mf"):
  536. base = filename[:-4]
  537. _expected_print_registered_at[(printer_id, base)] = _registered_at
  538. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  539. logging.getLogger(__name__).info(
  540. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  541. )
  542. def _compute_run_filament_grams(
  543. status: str,
  544. archive_filament_used_grams: float | None,
  545. progress: float | int | None,
  546. usage_results: list[dict] | None,
  547. ) -> float | None:
  548. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  549. Priority for every status:
  550. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  551. weight delta — same source that drives "Total Consumed" on the
  552. Inventory page, so Stats and Inventory totals stay aligned).
  553. 2. For ``completed``: the slicer estimate (no tracker available, fall
  554. back to the canonical "this print used X" value).
  555. 3. For partial statuses: ``estimate * progress%``.
  556. 4. ``None`` if nothing is known.
  557. """
  558. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  559. if tracked_grams > 0:
  560. return round(tracked_grams, 1)
  561. if status == "completed":
  562. return archive_filament_used_grams
  563. if archive_filament_used_grams:
  564. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  565. if scale > 0:
  566. return round(archive_filament_used_grams * scale, 1)
  567. return None
  568. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  569. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  570. stored_ams_mapping = data.get("ams_mapping")
  571. if not stored_ams_mapping and archive_id:
  572. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  573. return stored_ams_mapping
  574. def _get_start_plate_id(archive_id: int | None) -> int | None:
  575. """Resolve plate_id for print start without consuming stored direct-Print state.
  576. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  577. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  578. read it back at print-start without popping (the entry is popped on print
  579. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  580. """
  581. if archive_id is None:
  582. return None
  583. return _print_plate_ids.get(archive_id)
  584. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  585. """Best-effort filament metadata from the MQTT print-start snapshot.
  586. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  587. file during print, see #1533) so the fallback PrintArchive still has
  588. enough filament info to support the inventory views and AMS-expansion
  589. planning the operator opens it for. Returns a dict with optional
  590. ``filament_type`` and ``filament_color`` keys in the same
  591. comma-separated format the 3MF extractor produces, so the rest of the
  592. codebase treats the fallback archive identically to a normal one.
  593. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  594. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  595. entries). When supplied, only the slots actually consumed by this
  596. print contribute. Without it the function falls back to every loaded
  597. AMS slot — less accurate but still useful.
  598. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  599. that the unit tests pass directly, AND the on_print_start callback
  600. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  601. bambu_mqtt service hands to main.py at runtime. The original
  602. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  603. handled the inner shape and silently returned ``{}`` for every real
  604. print start, leaving fallback archives' filament fields NULL — the
  605. exact regression the fix was meant to close. Reported with a log
  606. proving the AMS state was right there at
  607. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  608. """
  609. result: dict[str, str] = {}
  610. # Look at the on_print_start wrapper first, then the inner shape.
  611. raw_data = (data or {}).get("raw_data")
  612. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  613. if not isinstance(ams_root, dict):
  614. ams_root = (data or {}).get("ams") or {}
  615. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  616. if not isinstance(ams_units, list) or not ams_units:
  617. return result
  618. # Map global tray id (unit * 4 + tray) → (type, color).
  619. loaded: dict[int, tuple[str, str]] = {}
  620. for unit in ams_units:
  621. if not isinstance(unit, dict):
  622. continue
  623. try:
  624. unit_id = int(unit.get("id", 0))
  625. except (TypeError, ValueError):
  626. continue
  627. for tray in unit.get("tray") or []:
  628. if not isinstance(tray, dict):
  629. continue
  630. try:
  631. tray_id = int(tray.get("id", 0))
  632. except (TypeError, ValueError):
  633. continue
  634. ttype = (tray.get("tray_type") or "").strip()
  635. tcolor = (tray.get("tray_color") or "").strip().upper()
  636. if not ttype:
  637. continue # Empty / unloaded slot.
  638. loaded[unit_id * 4 + tray_id] = (ttype, tcolor)
  639. if not loaded:
  640. return result
  641. if ams_mapping:
  642. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  643. filaments = [loaded[g] for g in used_ids if g in loaded]
  644. if not filaments:
  645. return result # Mapping points entirely at slots we have no data for.
  646. else:
  647. filaments = [loaded[g] for g in sorted(loaded.keys())]
  648. types_joined = ",".join(f[0] for f in filaments)
  649. colors_joined = ",".join(f[1] for f in filaments if f[1])
  650. # Column limits per backend/app/models/archive.py: filament_type=50,
  651. # filament_color=200.
  652. if types_joined:
  653. result["filament_type"] = types_joined[:50]
  654. if colors_joined:
  655. result["filament_color"] = colors_joined[:200]
  656. return result
  657. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  658. """Start a layer-timelapse session for *archive_id* when the printer has
  659. an external camera configured. Returns True if a session was started.
  660. Three call sites in on_print_start (expected-archive promotion, fallback
  661. archive creation, fresh-archive creation) used to inline this same
  662. if-block; the inline copies kept drifting (#1353 fixed only one of them
  663. on the first pass). Centralising the conditional + call here makes the
  664. contract testable in isolation and keeps the three sites locked in step.
  665. """
  666. if not (printer.external_camera_enabled and printer.external_camera_url):
  667. return False
  668. from backend.app.services.layer_timelapse import start_session
  669. start_session(
  670. printer_id,
  671. archive_id,
  672. printer.external_camera_url,
  673. printer.external_camera_type or "mjpeg",
  674. snapshot_url=printer.external_camera_snapshot_url,
  675. )
  676. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  677. return True
  678. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  679. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  680. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity.
  681. The short code used for the hms_errors.py lookup table is 'MMMM_EEEE' — module
  682. from attr bits 16-31, error from the numeric part of code. Falls back to the raw
  683. short code when no description is on file. Returns None for an empty list so
  684. callers can leave error_message unset.
  685. """
  686. if not hms_errors:
  687. return None
  688. from backend.app.services.hms_errors import get_error_description
  689. parts: list[str] = []
  690. for err in hms_errors:
  691. try:
  692. code_str = str(err.get("code", "")).replace("0x", "")
  693. error_num = int(code_str, 16) if code_str else 0
  694. module_num = (int(err.get("attr", 0)) >> 16) & 0xFFFF
  695. short_code = f"{module_num:04X}_{error_num:04X}"
  696. except (TypeError, ValueError):
  697. continue
  698. description = get_error_description(short_code)
  699. parts.append(f"[{short_code}] {description}" if description else f"[{short_code}]")
  700. return "; ".join(parts) if parts else None
  701. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  702. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  703. print completes successfully. Gated to status=='completed': failed, cancelled
  704. and aborted prints do not count as usage. Caller is responsible for committing
  705. the session. No-op when the queue item has no linked library file (e.g. reprints
  706. from an archive). See #1008."""
  707. if queue_status != "completed" or item.library_file_id is None:
  708. return
  709. from backend.app.models.library import LibraryFile
  710. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  711. if lib_file is None:
  712. return
  713. lib_file.print_count = (lib_file.print_count or 0) + 1
  714. lib_file.last_printed_at = datetime.now(timezone.utc)
  715. def mark_printer_stopped_by_user(printer_id: int) -> None:
  716. """Mark that the active print on this printer was stopped by the user from the queue UI.
  717. When on_print_complete fires with status 'failed' for a printer in this set we
  718. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  719. rather than a 'print failed' notification.
  720. """
  721. _user_stopped_printers.add(printer_id)
  722. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  723. _last_status_broadcast: dict[int, str] = {}
  724. # Track printers where we've updated nozzle_count
  725. _nozzle_count_updated: set[int] = set()
  726. async def on_printer_status_change(printer_id: int, state: PrinterState):
  727. """Handle printer status changes - broadcast via WebSocket."""
  728. # Connected-edge reconciliation (#1542 follow-up). When the printer
  729. # transitions disconnected → connected — which covers both Bambuddy
  730. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  731. # `reconcile_stale_active_prints` exactly once for this connection so
  732. # any archive still in `status="printing"` that can't actually be
  733. # running anymore (printer IDLE / different subtask / empty subtask)
  734. # gets a synthesised PRINT COMPLETE. Without this, a print that
  735. # finished during a disconnect window + a smart-plug power cycle
  736. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  737. # next boot. Reconciliation runs concurrently — it must not block the
  738. # WebSocket dedup / broadcast logic below, and the connected edge is
  739. # marked True BEFORE the await so concurrent status updates inside
  740. # the same connection don't re-trigger reconciliation.
  741. #
  742. # Wait for a real push_status before reconciling (#1679): MQTT
  743. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  744. # the connection, BEFORE `_request_push_all` round-trips. At that
  745. # instant the `PrinterState` is still on construction defaults — most
  746. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  747. # If reconcile spawns here, every in-flight archive falls through to
  748. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  749. # creates a duplicate archive on the real PRINT COMPLETE and
  750. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  751. # keeps the #1542 mechanism intact: once the first real push_status
  752. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  753. # fires again with the flag still False — reconcile then runs against
  754. # actual evidence.
  755. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  756. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  757. _printer_reconciled_since_connect[printer_id] = True
  758. spawn_background_task(
  759. reconcile_stale_active_prints(printer_id),
  760. name=f"reconcile-stale-prints-{printer_id}",
  761. )
  762. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  763. # Re-arm so the next reconnect triggers reconciliation again.
  764. _printer_reconciled_since_connect[printer_id] = False
  765. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  766. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  767. temps = state.temperatures or {}
  768. nozzle_temp = round(temps.get("nozzle", 0))
  769. bed_temp = round(temps.get("bed", 0))
  770. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  771. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  772. # Auto-detect dual-nozzle printers from MQTT temperature data
  773. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  774. _nozzle_count_updated.add(printer_id)
  775. # Update nozzle_count in database
  776. async with async_session() as db:
  777. from backend.app.models.printer import Printer
  778. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  779. printer = result.scalar_one_or_none()
  780. if printer and printer.nozzle_count != 2:
  781. printer.nozzle_count = 2
  782. await db.commit()
  783. logging.getLogger(__name__).info(
  784. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  785. )
  786. # Include target temps for heating phase detection
  787. bed_target = round(temps.get("bed_target", 0))
  788. nozzle_target = round(temps.get("nozzle_target", 0))
  789. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  790. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  791. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts
  792. ams_dry_key = tuple(a.get("dry_time", 0) for a in (state.raw_data.get("ams") or [])) if state.raw_data else ()
  793. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  794. ams_tray_key = (
  795. tuple(
  796. (t.get("id"), t.get("tray_type", ""), t.get("state"))
  797. for a in (state.raw_data.get("ams") or [])
  798. for t in a.get("tray", [])
  799. )
  800. if state.raw_data
  801. else ()
  802. )
  803. status_key = (
  804. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  805. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  806. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  807. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  808. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  809. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}"
  810. )
  811. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  812. try:
  813. printer_info = printer_manager.get_printer(printer_id)
  814. if printer_info:
  815. await mqtt_relay.on_printer_status(printer_id, state, printer_info.name, printer_info.serial_number)
  816. except Exception:
  817. pass # Don't fail status callback if MQTT fails
  818. if _last_status_broadcast.get(printer_id) == status_key:
  819. return # No change, skip WebSocket broadcast
  820. _last_status_broadcast[printer_id] = status_key
  821. # Check for progress milestone notifications (25%, 50%, 75%)
  822. progress = state.progress or 0
  823. is_printing = state.state in ("RUNNING", "PRINTING")
  824. if is_printing and progress > 0:
  825. # Determine which milestone we've reached
  826. current_milestone = 0
  827. if progress >= 75:
  828. current_milestone = 75
  829. elif progress >= 50:
  830. current_milestone = 50
  831. elif progress >= 25:
  832. current_milestone = 25
  833. last_milestone = _last_progress_milestone.get(printer_id, 0)
  834. # If we've crossed a new milestone, send notification
  835. if current_milestone > last_milestone:
  836. _last_progress_milestone[printer_id] = current_milestone
  837. try:
  838. async with async_session() as db:
  839. from backend.app.models.printer import Printer
  840. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  841. printer = result.scalar_one_or_none()
  842. printer_name = printer.name if printer else f"Printer {printer_id}"
  843. filename = state.subtask_name or state.gcode_file or "Unknown"
  844. # remaining_time is in minutes, convert to seconds for notification
  845. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  846. # Capture camera snapshot for notification image attachment
  847. image_data = await _capture_snapshot_for_notification(
  848. printer_id, printer, logging.getLogger(__name__)
  849. )
  850. await notification_service.on_print_progress(
  851. printer_id,
  852. printer_name,
  853. filename,
  854. current_milestone,
  855. db,
  856. remaining_time_seconds,
  857. image_data=image_data,
  858. )
  859. except Exception as e:
  860. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  861. elif progress < 5:
  862. # Reset milestone tracking when print restarts or new print begins
  863. _last_progress_milestone[printer_id] = 0
  864. _first_layer_notified[printer_id] = False
  865. # HMS error codes that should not trigger notifications even though they
  866. # have known descriptions (e.g. user-initiated actions, not real errors).
  867. _HMS_NOTIFICATION_SUPPRESS = {
  868. "0500_400E", # Printing was cancelled (user action, not an error)
  869. }
  870. # Check for new HMS errors and send notifications
  871. current_hms_errors = getattr(state, "hms_errors", []) or []
  872. if current_hms_errors:
  873. # Build set of current error codes (using attr for uniqueness)
  874. current_error_codes = {f"{e.attr:08x}" for e in current_hms_errors}
  875. previously_notified = _notified_hms_errors.get(printer_id, set())
  876. # Find new errors that haven't been notified yet
  877. new_error_codes = current_error_codes - previously_notified
  878. # Update tracking immediately to prevent duplicate notifications from concurrent callbacks
  879. _notified_hms_errors[printer_id] = current_error_codes
  880. _hms_last_seen[printer_id] = time.time()
  881. if new_error_codes:
  882. # Get the actual new errors for the notification
  883. # Filter to severity >= 2 (skip informational/status messages like H2D sends)
  884. new_errors = [e for e in current_hms_errors if f"{e.attr:08x}" in new_error_codes and e.severity >= 2]
  885. try:
  886. async with async_session() as db:
  887. from backend.app.models.printer import Printer
  888. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  889. printer = result.scalar_one_or_none()
  890. printer_name = printer.name if printer else f"Printer {printer_id}"
  891. # Format error details for notification
  892. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  893. module_names = {
  894. 0x03: "Print/Task",
  895. 0x05: "Nozzle/Extruder",
  896. 0x07: "AMS/Filament",
  897. 0x0C: "Motion Controller",
  898. 0x12: "Chamber",
  899. }
  900. from backend.app.services.hms_errors import get_error_description
  901. # Capture camera snapshot once for all error notifications
  902. error_image_data = await _capture_snapshot_for_notification(
  903. printer_id, printer, logging.getLogger(__name__)
  904. )
  905. sent_count = 0
  906. for error in new_errors:
  907. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  908. # Build short code like "0700_8010"
  909. # Mask to 16 bits to handle printers that send larger values
  910. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  911. error_code_masked = error_code_int & 0xFFFF
  912. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  913. # Only notify for errors with known descriptions — printers
  914. # send many undocumented/phantom codes that aren't real errors.
  915. description = get_error_description(short_code)
  916. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  917. continue
  918. error_type = f"{module_name} Error"
  919. error_detail = description
  920. await notification_service.on_printer_error(
  921. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  922. )
  923. sent_count += 1
  924. if sent_count:
  925. logging.getLogger(__name__).info(
  926. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  927. )
  928. # Also publish to MQTT relay
  929. printer_info = printer_manager.get_printer(printer_id)
  930. if printer_info:
  931. errors_data = [
  932. {
  933. "code": e.code,
  934. "attr": e.attr,
  935. "module": e.module,
  936. "severity": e.severity,
  937. }
  938. for e in new_errors
  939. ]
  940. await mqtt_relay.on_printer_error(
  941. printer_id, printer_info.name, printer_info.serial_number, errors_data
  942. )
  943. except Exception as e:
  944. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  945. else:
  946. # No HMS errors — only clear tracking after a grace period to prevent
  947. # flapping errors (brief hms:[] gaps) from re-triggering notifications.
  948. # Some HMS codes (e.g. chamber temp regulation during PETG prints) toggle
  949. # on/off every few seconds as conditions fluctuate around thresholds.
  950. if printer_id in _notified_hms_errors:
  951. last_seen = _hms_last_seen.get(printer_id, 0)
  952. if time.time() - last_seen >= _HMS_CLEAR_GRACE_SECONDS:
  953. _notified_hms_errors.pop(printer_id, None)
  954. _hms_last_seen.pop(printer_id, None)
  955. await ws_manager.send_printer_status(
  956. printer_id,
  957. printer_state_to_dict(state, printer_id, printer_manager.get_model(printer_id)),
  958. )
  959. def _is_bambu_uuid(tray_uuid: str) -> bool:
  960. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  961. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  962. async def on_ams_change(printer_id: int, ams_data: list):
  963. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  964. logger = logging.getLogger(__name__)
  965. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  966. # on_print_complete may pop _active_sessions during our awaits (#880).
  967. from backend.app.services.usage_tracker import _active_sessions
  968. _print_active = printer_id in _active_sessions
  969. # MQTT relay - publish AMS change
  970. try:
  971. printer_info = printer_manager.get_printer(printer_id)
  972. if printer_info:
  973. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  974. except Exception:
  975. pass # Don't fail AMS callback if MQTT fails
  976. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  977. # This ensures frontend gets immediate updates when AMS slots are configured
  978. try:
  979. state = printer_manager.get_status(printer_id)
  980. if state:
  981. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  982. await ws_manager.send_printer_status(
  983. printer_id,
  984. printer_state_to_dict(state, printer_id, printer_manager.get_model(printer_id)),
  985. )
  986. except Exception as e:
  987. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  988. from backend.app.utils.color_utils import colors_similar as _colors_similar
  989. # Auto-unlink spool assignments with stale fingerprints
  990. try:
  991. async with async_session() as db:
  992. from sqlalchemy.orm import selectinload
  993. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  994. from backend.app.models.spool import Spool as _Spool
  995. from backend.app.models.spool_assignment import SpoolAssignment as SA
  996. result = await db.execute(
  997. select(SA)
  998. .where(SA.printer_id == printer_id)
  999. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  1000. )
  1001. stale = []
  1002. for assignment in result.scalars().all():
  1003. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  1004. if assignment.ams_id == 255:
  1005. ps = printer_manager.get_status(printer_id)
  1006. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  1007. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  1008. current_tray = None
  1009. for vt in vt_tray_raw:
  1010. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  1011. current_tray = vt
  1012. break
  1013. if not current_tray:
  1014. # vt_tray data may not have arrived yet — keep assignment
  1015. continue
  1016. else:
  1017. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  1018. if not current_tray:
  1019. logger.info(
  1020. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  1021. assignment.spool_id,
  1022. assignment.ams_id,
  1023. assignment.tray_id,
  1024. )
  1025. stale.append(assignment) # Slot empty
  1026. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  1027. # A Bambu Lab spool is in this slot — check if it's the same spool
  1028. # that's currently assigned. If yes, keep the assignment (avoids
  1029. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  1030. # the printer's filament preset on every startup).
  1031. tray_uuid = current_tray.get("tray_uuid", "")
  1032. tag_uid = current_tray.get("tag_uid", "")
  1033. spool = assignment.spool
  1034. spool_matches = False
  1035. if spool:
  1036. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  1037. spool.tag_uid
  1038. and tag_uid
  1039. and tag_uid != "0000000000000000"
  1040. and spool.tag_uid.upper() == tag_uid.upper()
  1041. ):
  1042. spool_matches = True
  1043. if spool_matches:
  1044. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  1045. cur_color = current_tray.get("tray_color", "")
  1046. cur_type = current_tray.get("tray_type", "")
  1047. fp_color = assignment.fingerprint_color or ""
  1048. fp_type = assignment.fingerprint_type or ""
  1049. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  1050. assignment.fingerprint_color = cur_color
  1051. assignment.fingerprint_type = cur_type
  1052. logger.debug(
  1053. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  1054. assignment.spool_id,
  1055. assignment.ams_id,
  1056. assignment.tray_id,
  1057. )
  1058. continue
  1059. # Different BL spool or unrecognized — unlink so auto-assign can match
  1060. logger.info(
  1061. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  1062. assignment.spool_id,
  1063. assignment.ams_id,
  1064. assignment.tray_id,
  1065. tray_uuid,
  1066. )
  1067. stale.append(assignment)
  1068. else:
  1069. cur_color = current_tray.get("tray_color", "")
  1070. cur_type = current_tray.get("tray_type", "")
  1071. cur_state = current_tray.get("state")
  1072. fp_color = assignment.fingerprint_color or ""
  1073. fp_type = assignment.fingerprint_type or ""
  1074. # SpoolBuddy pre-config replay: fingerprint_type empty means
  1075. # the slot was empty when the user pre-assigned via SpoolBuddy
  1076. # (the firmware drops ams_filament_setting on empty slots, so
  1077. # MQTT was deferred). The moment any filament gets inserted
  1078. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  1079. # reconfigured spool — fire the deferred configuration.
  1080. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  1081. # extruder" code) OR, on firmwares that don't use the state
  1082. # enum meaningfully, a non-empty tray_type when state is
  1083. # NOT one of the firmware's explicit empty signals (9, 10).
  1084. # state-only was wrong for firmwares that never set 11 — A1
  1085. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  1086. # always report state=3 — so the replay never fired for them
  1087. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  1088. # explicit "empty" signals authoritative over any stale
  1089. # tray_type that might survive the relay's auto-clearing.
  1090. loaded = cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  1091. if not fp_type.strip() and loaded and assignment.spool:
  1092. try:
  1093. from backend.app.api.routes.inventory import (
  1094. apply_spool_to_slot_via_mqtt,
  1095. )
  1096. await apply_spool_to_slot_via_mqtt(
  1097. db=db,
  1098. current_user=None,
  1099. spool=assignment.spool,
  1100. printer_id=printer_id,
  1101. ams_id=assignment.ams_id,
  1102. tray_id=assignment.tray_id,
  1103. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  1104. current_tray_type=cur_type,
  1105. )
  1106. logger.info(
  1107. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  1108. assignment.spool_id,
  1109. printer_id,
  1110. assignment.ams_id,
  1111. assignment.tray_id,
  1112. )
  1113. except Exception:
  1114. logger.exception(
  1115. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  1116. assignment.spool_id,
  1117. printer_id,
  1118. assignment.ams_id,
  1119. assignment.tray_id,
  1120. )
  1121. assignment.fingerprint_color = cur_color
  1122. assignment.fingerprint_type = cur_type
  1123. continue
  1124. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  1125. # Fingerprint mismatch — but check if tray now matches the
  1126. # assigned spool (e.g. auto-configure changed the tray).
  1127. spool = assignment.spool
  1128. if spool:
  1129. spool_color = (spool.rgba or "FFFFFFFF").upper()
  1130. spool_type = (spool.material or "").upper()
  1131. if _colors_similar(cur_color, spool_color) and cur_type.upper() == spool_type:
  1132. logger.info(
  1133. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  1134. assignment.spool_id,
  1135. assignment.ams_id,
  1136. assignment.tray_id,
  1137. )
  1138. assignment.fingerprint_color = cur_color
  1139. assignment.fingerprint_type = cur_type
  1140. continue
  1141. logger.info(
  1142. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  1143. assignment.spool_id,
  1144. assignment.ams_id,
  1145. assignment.tray_id,
  1146. cur_color,
  1147. cur_type,
  1148. fp_color,
  1149. fp_type,
  1150. spool.rgba if spool else "?",
  1151. spool.material if spool else "?",
  1152. )
  1153. stale.append(assignment) # Spool changed
  1154. for a in stale:
  1155. await db.delete(a)
  1156. if stale:
  1157. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  1158. # Commit any changes (stale deletions and/or fingerprint updates)
  1159. await db.commit()
  1160. except Exception as e:
  1161. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  1162. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  1163. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  1164. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  1165. # "no existing assignment" for the same (printer, ams, tray) and race to
  1166. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  1167. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  1168. # bug stayed latent there. See _ams_assignment_locks comment for details.
  1169. try:
  1170. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  1171. from backend.app.api.routes.settings import get_setting
  1172. from backend.app.models.spool import Spool
  1173. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1174. from backend.app.services.spool_tag_matcher import (
  1175. auto_assign_spool,
  1176. create_spool_from_tray,
  1177. find_matching_untagged_spool,
  1178. get_spool_by_tag,
  1179. is_bambu_tag,
  1180. is_valid_tag,
  1181. link_tag_to_inventory_spool,
  1182. )
  1183. _spoolman_on = await get_setting(db, "spoolman_enabled")
  1184. if not _spoolman_on or _spoolman_on.lower() != "true":
  1185. for ams_unit in ams_data:
  1186. if not isinstance(ams_unit, dict):
  1187. continue
  1188. ams_id = int(ams_unit.get("id", 0))
  1189. for tray in ams_unit.get("tray", []):
  1190. if not isinstance(tray, dict):
  1191. continue
  1192. tray_id = int(tray.get("id", 0))
  1193. tag_uid = tray.get("tag_uid", "")
  1194. tray_uuid = tray.get("tray_uuid", "")
  1195. tray_info_idx = tray.get("tray_info_idx", "")
  1196. if not tray.get("tray_type"):
  1197. continue # Empty slot
  1198. # Check if assignment already exists for this slot
  1199. existing = await db.execute(
  1200. select(SA)
  1201. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  1202. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  1203. )
  1204. existing_assignment = existing.scalar_one_or_none()
  1205. if existing_assignment:
  1206. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  1207. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  1208. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  1209. # Skip during active prints: the usage tracker handles deduction
  1210. # precisely via 3MF data on print completion. Without this guard the
  1211. # AMS remain% SET and the usage tracker ADD both fire from the same
  1212. # MQTT message, doubling the deduction (#880).
  1213. if _print_active:
  1214. continue
  1215. remain_raw = tray.get("remain")
  1216. if (
  1217. remain_raw is not None
  1218. and existing_assignment.spool
  1219. and not existing_assignment.spool.weight_locked
  1220. ):
  1221. try:
  1222. remain_val = int(remain_raw)
  1223. except (TypeError, ValueError):
  1224. remain_val = -1
  1225. if 1 <= remain_val <= 100:
  1226. lw = existing_assignment.spool.label_weight or 1000
  1227. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  1228. current_used = existing_assignment.spool.weight_used or 0
  1229. if new_used > current_used + 1:
  1230. logger.info(
  1231. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  1232. existing_assignment.spool_id,
  1233. current_used,
  1234. new_used,
  1235. remain_val,
  1236. )
  1237. existing_assignment.spool.weight_used = new_used
  1238. await db.commit()
  1239. # Re-apply stored K-profile when the live tray's
  1240. # cali_idx drifted from the spool's stored profile.
  1241. # This catches "reset slot → re-read" and any other
  1242. # path where the firmware loses the user's K-profile
  1243. # selection while the SpoolAssignment row persists.
  1244. # Per the maintainer's rule: any time a spool tag is
  1245. # identified and matches inventory, the slot must be
  1246. # configured with the spool's stored settings. Without
  1247. # this block the existing-assignment branch only ran
  1248. # weight-sync and let the firmware-default cali_idx win.
  1249. try:
  1250. spool = existing_assignment.spool
  1251. if (
  1252. spool is not None
  1253. and is_bambu_tag(tag_uid, tray_uuid, tray_info_idx)
  1254. and spool.k_profiles
  1255. ):
  1256. state = printer_manager.get_status(printer_id)
  1257. nozzle_diameter = "0.4"
  1258. if state and state.nozzles:
  1259. nd = state.nozzles[0].nozzle_diameter
  1260. if nd:
  1261. nozzle_diameter = nd
  1262. slot_extruder: int | None = None
  1263. if state and state.ams_extruder_map:
  1264. if ams_id == 255:
  1265. slot_extruder = 1 - tray_id
  1266. else:
  1267. slot_extruder = state.ams_extruder_map.get(str(ams_id))
  1268. # Prefer exact extruder match, fall back to
  1269. # extruder-agnostic kp for the same printer +
  1270. # nozzle. Avoids hard-skipping when the AMS is
  1271. # mapped differently than at calibration time.
  1272. matching_kp = None
  1273. fallback_kp = None
  1274. for kp in spool.k_profiles:
  1275. if (
  1276. kp.printer_id != printer_id
  1277. or kp.nozzle_diameter != nozzle_diameter
  1278. or kp.cali_idx is None
  1279. ):
  1280. continue
  1281. if (
  1282. slot_extruder is not None
  1283. and kp.extruder is not None
  1284. and kp.extruder == slot_extruder
  1285. ):
  1286. matching_kp = kp
  1287. break
  1288. if fallback_kp is None:
  1289. fallback_kp = kp
  1290. chosen_kp = matching_kp or fallback_kp
  1291. if chosen_kp is not None:
  1292. live_cali_idx = tray.get("cali_idx")
  1293. # Only fire MQTT when the printer's live
  1294. # cali_idx differs from the stored value.
  1295. # Avoids spamming the broker on every
  1296. # MQTT push during steady-state operation.
  1297. if live_cali_idx != chosen_kp.cali_idx:
  1298. client = printer_manager.get_client(printer_id)
  1299. if client:
  1300. cali_filament_id = spool.slicer_filament or tray_info_idx or ""
  1301. client.extrusion_cali_sel(
  1302. ams_id=ams_id,
  1303. tray_id=tray_id,
  1304. cali_idx=chosen_kp.cali_idx,
  1305. filament_id=cali_filament_id,
  1306. nozzle_diameter=nozzle_diameter,
  1307. )
  1308. logger.info(
  1309. "Re-applied K-profile cali_idx=%d for spool %d "
  1310. "on printer %d AMS%d-T%d (live=%s drift detected)",
  1311. chosen_kp.cali_idx,
  1312. spool.id,
  1313. printer_id,
  1314. ams_id,
  1315. tray_id,
  1316. live_cali_idx,
  1317. )
  1318. except Exception:
  1319. logger.exception(
  1320. "K-profile re-apply failed for printer %d AMS%d-T%d",
  1321. printer_id,
  1322. ams_id,
  1323. tray_id,
  1324. )
  1325. continue
  1326. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  1327. # BL spool with RFID tag: auto-match → inventory match → auto-create
  1328. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  1329. if not spool:
  1330. # Try matching an untagged inventory spool (same material/color)
  1331. spool = await find_matching_untagged_spool(db, tray)
  1332. if spool:
  1333. await link_tag_to_inventory_spool(db, spool, tray)
  1334. else:
  1335. spool = await create_spool_from_tray(db, tray)
  1336. await auto_assign_spool(
  1337. printer_id,
  1338. ams_id,
  1339. tray_id,
  1340. spool,
  1341. printer_manager,
  1342. db,
  1343. tray_info_idx=tray_info_idx,
  1344. )
  1345. await db.commit()
  1346. await ws_manager.broadcast(
  1347. {
  1348. "type": "spool_auto_assigned",
  1349. "printer_id": printer_id,
  1350. "ams_id": ams_id,
  1351. "tray_id": tray_id,
  1352. "spool_id": spool.id,
  1353. }
  1354. )
  1355. logger.info(
  1356. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  1357. spool.id,
  1358. printer_id,
  1359. ams_id,
  1360. tray_id,
  1361. )
  1362. elif is_valid_tag(tag_uid, tray_uuid):
  1363. # Non-BL spool with some tag — let user choose
  1364. await ws_manager.broadcast(
  1365. {
  1366. "type": "unknown_tag",
  1367. "printer_id": printer_id,
  1368. "ams_id": ams_id,
  1369. "tray_id": tray_id,
  1370. "tag_uid": tag_uid,
  1371. "tray_uuid": tray_uuid,
  1372. }
  1373. )
  1374. else:
  1375. # No tag at all — let user choose from inventory
  1376. await ws_manager.broadcast(
  1377. {
  1378. "type": "unknown_tag",
  1379. "printer_id": printer_id,
  1380. "ams_id": ams_id,
  1381. "tray_id": tray_id,
  1382. "tag_uid": "",
  1383. "tray_uuid": "",
  1384. }
  1385. )
  1386. except Exception as e:
  1387. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  1388. try:
  1389. async with async_session() as db:
  1390. from backend.app.api.routes.settings import get_setting
  1391. from backend.app.models.printer import Printer
  1392. # Check if Spoolman is enabled
  1393. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  1394. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  1395. return
  1396. # Check sync mode
  1397. sync_mode = await get_setting(db, "spoolman_sync_mode")
  1398. if sync_mode and sync_mode != "auto":
  1399. return # Only sync on auto mode
  1400. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  1401. # always owned by per-print tracking, never by AMS auto-sync. The
  1402. # setting is still read by the settings UI for backwards compat but
  1403. # has no effect on the sync path here.
  1404. # Get Spoolman URL
  1405. spoolman_url = await get_setting(db, "spoolman_url")
  1406. if not spoolman_url:
  1407. return
  1408. # Get or create Spoolman client
  1409. client = await get_spoolman_client()
  1410. if not client:
  1411. try:
  1412. client = await init_spoolman_client(spoolman_url)
  1413. except ValueError as exc:
  1414. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  1415. return
  1416. # Check if Spoolman is reachable
  1417. if not await client.health_check():
  1418. logger.warning("Spoolman not reachable at %s", spoolman_url)
  1419. return
  1420. # Get printer name for location
  1421. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1422. printer = result.scalar_one_or_none()
  1423. printer_name = printer.name if printer else f"Printer {printer_id}"
  1424. # OPTIMIZATION: Fetch all spools once before processing trays
  1425. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  1426. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  1427. try:
  1428. cached_spools = await client.get_spools()
  1429. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  1430. except Exception as e:
  1431. logger.error(
  1432. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  1433. printer_id,
  1434. e,
  1435. )
  1436. return
  1437. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  1438. from sqlalchemy.orm import selectinload
  1439. from backend.app.models.spool_assignment import SpoolAssignment
  1440. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  1441. inventory_weights: dict[tuple[int, int], float] = {}
  1442. try:
  1443. assign_result = await db.execute(
  1444. select(SpoolAssignment)
  1445. .options(selectinload(SpoolAssignment.spool))
  1446. .where(SpoolAssignment.printer_id == printer_id)
  1447. )
  1448. for assignment in assign_result.scalars().all():
  1449. spool = assignment.spool
  1450. if spool and spool.label_weight > 0:
  1451. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  1452. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  1453. except Exception as e:
  1454. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  1455. # Load existing Spoolman slot assignments for the no-RFID fallback path
  1456. spoolman_slot_map: dict[tuple[int, int], int] = {}
  1457. try:
  1458. slot_result = await db.execute(
  1459. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  1460. )
  1461. for slot in slot_result.scalars().all():
  1462. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  1463. except Exception as e:
  1464. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  1465. # Sync each AMS tray and collect slot changes for DB persistence
  1466. synced = 0
  1467. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  1468. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  1469. for ams_unit in ams_data:
  1470. if not isinstance(ams_unit, dict):
  1471. continue
  1472. ams_id = int(ams_unit.get("id", 0))
  1473. trays = ams_unit.get("tray", [])
  1474. for tray_data in trays:
  1475. if not isinstance(tray_data, dict):
  1476. continue
  1477. tray_id_raw = int(tray_data.get("id", 0))
  1478. tray = client.parse_ams_tray(ams_id, tray_data)
  1479. if not tray:
  1480. # Empty tray slot — record for local assignment cleanup
  1481. empty_slots.append((ams_id, tray_id_raw))
  1482. continue
  1483. spool_tag = (
  1484. tray.tray_uuid
  1485. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  1486. else tray.tag_uid
  1487. )
  1488. # Provide the hint only when no RFID is available
  1489. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  1490. try:
  1491. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  1492. result = await client.sync_ams_tray(
  1493. tray,
  1494. printer_name,
  1495. # Per-print tracking is the only weight writer (#1119).
  1496. # AMS auto-sync still maintains spool metadata / slot
  1497. # assignments but no longer touches remaining_weight.
  1498. disable_weight_sync=True,
  1499. cached_spools=cached_spools,
  1500. inventory_remaining=inv_remaining,
  1501. spoolman_spool_id_hint=hint,
  1502. )
  1503. if result:
  1504. synced += 1
  1505. if result.get("id"):
  1506. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  1507. # If a new spool was created, add it to the cache
  1508. # so subsequent trays can find it if they reference the same tag
  1509. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  1510. if not spool_exists:
  1511. cached_spools.append(result)
  1512. logger.debug(
  1513. "[Printer %s] Added newly created spool %s to cache",
  1514. printer_id,
  1515. result["id"],
  1516. )
  1517. except Exception as e:
  1518. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  1519. if synced > 0:
  1520. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  1521. # Persist slot assignment changes to the local table
  1522. if slot_changes or empty_slots:
  1523. try:
  1524. for ams_id, tray_id, spool_id in slot_changes:
  1525. await db.execute(
  1526. text(
  1527. "INSERT INTO spoolman_slot_assignments"
  1528. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  1529. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  1530. " ON CONFLICT(printer_id, ams_id, tray_id)"
  1531. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  1532. ),
  1533. {
  1534. "printer_id": printer_id,
  1535. "ams_id": ams_id,
  1536. "tray_id": tray_id,
  1537. "spool_id": spool_id,
  1538. },
  1539. )
  1540. for ams_id, tray_id in empty_slots:
  1541. await db.execute(
  1542. delete(SpoolmanSlotAssignment).where(
  1543. SpoolmanSlotAssignment.printer_id == printer_id,
  1544. SpoolmanSlotAssignment.ams_id == ams_id,
  1545. SpoolmanSlotAssignment.tray_id == tray_id,
  1546. )
  1547. )
  1548. await db.commit()
  1549. except Exception as e:
  1550. await db.rollback()
  1551. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  1552. except Exception as e:
  1553. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  1554. async def _capture_snapshot_for_notification(printer_id: int, printer, logger) -> bytes | None:
  1555. """Capture a camera snapshot for notification image attachment.
  1556. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  1557. Uses: external camera > buffered frame > fresh capture.
  1558. """
  1559. if not printer:
  1560. return None
  1561. try:
  1562. from backend.app.api.routes.settings import get_setting
  1563. async with async_session() as db:
  1564. capture_enabled = await get_setting(db, "capture_finish_photo")
  1565. if capture_enabled is not None and capture_enabled.lower() != "true":
  1566. return None
  1567. # Try external camera first
  1568. if printer.external_camera_enabled and printer.external_camera_url:
  1569. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  1570. from backend.app.services.external_camera import capture_frame
  1571. frame_data = await capture_frame(
  1572. printer.external_camera_url,
  1573. printer.external_camera_type or "mjpeg",
  1574. snapshot_url=printer.external_camera_snapshot_url,
  1575. )
  1576. if frame_data and len(frame_data) <= 2_500_000:
  1577. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  1578. return _apply_camera_rotation(frame_data, printer, logger)
  1579. # Try buffered frame from active stream
  1580. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  1581. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  1582. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  1583. buffered_frame = get_buffered_frame(printer_id)
  1584. if (active_for_printer or active_chamber) and buffered_frame:
  1585. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  1586. if len(buffered_frame) <= 2_500_000:
  1587. return _apply_camera_rotation(buffered_frame, printer, logger)
  1588. # Fresh capture from printer camera
  1589. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  1590. from backend.app.services.camera import capture_camera_frame_bytes
  1591. frame_data = await capture_camera_frame_bytes(
  1592. printer.ip_address, printer.access_code, printer.model, timeout=15
  1593. )
  1594. if frame_data and len(frame_data) <= 2_500_000:
  1595. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  1596. return _apply_camera_rotation(frame_data, printer, logger)
  1597. except Exception as e:
  1598. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  1599. return None
  1600. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  1601. """Apply camera rotation to snapshot image if configured."""
  1602. rotation = getattr(printer, "camera_rotation", 0)
  1603. if not rotation or rotation == 0:
  1604. return image_data
  1605. try:
  1606. from io import BytesIO
  1607. from PIL import Image
  1608. img = Image.open(BytesIO(image_data))
  1609. # PIL rotate is counter-clockwise, so negate for clockwise rotation
  1610. img = img.rotate(-rotation, expand=True)
  1611. buf = BytesIO()
  1612. img.save(buf, format="JPEG", quality=90)
  1613. rotated = buf.getvalue()
  1614. logger.info("[SNAPSHOT] Applied %d° rotation: %s → %s bytes", rotation, len(image_data), len(rotated))
  1615. return rotated
  1616. except Exception as e:
  1617. logger.warning("[SNAPSHOT] Failed to apply rotation: %s", e)
  1618. return image_data
  1619. async def _send_print_start_notification(
  1620. printer_id: int,
  1621. data: dict,
  1622. archive_data: dict | None = None,
  1623. logger=None,
  1624. ):
  1625. """Helper to send print start notification with optional archive data."""
  1626. if logger is None:
  1627. logger = logging.getLogger(__name__)
  1628. try:
  1629. async with async_session() as db:
  1630. from backend.app.models.printer import Printer
  1631. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1632. printer = result.scalar_one_or_none()
  1633. printer_name = printer.name if printer else f"Printer {printer_id}"
  1634. # Capture camera snapshot for notification image attachment
  1635. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  1636. if image_data:
  1637. if archive_data is None:
  1638. archive_data = {}
  1639. archive_data["image_data"] = image_data
  1640. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  1641. # Send user-specific email notification for print start
  1642. if archive_data and archive_data.get("created_by_id"):
  1643. await notification_service.send_user_print_email(
  1644. event_type="user_print_start",
  1645. created_by_id=archive_data["created_by_id"],
  1646. printer_name=printer_name,
  1647. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  1648. db=db,
  1649. )
  1650. except Exception as e:
  1651. logger.warning("Notification on_print_start failed: %s", e)
  1652. async def _dispatch_user_print_email(
  1653. status: str,
  1654. created_by_id: int | None,
  1655. printer_name: str,
  1656. filename: str,
  1657. db,
  1658. ) -> None:
  1659. """Send a user-specific print-completion email based on print status.
  1660. Maps the normalised print status to the correct event type and delegates
  1661. to :meth:`NotificationService.send_user_print_email`. A single helper
  1662. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  1663. "stopped"`` dispatch block at every call site.
  1664. Does nothing if *created_by_id* is ``None``.
  1665. """
  1666. if created_by_id is None:
  1667. return
  1668. if status == "completed":
  1669. event_type = "user_print_complete"
  1670. elif status == "failed":
  1671. event_type = "user_print_failed"
  1672. elif status in ("stopped", "aborted", "cancelled"):
  1673. event_type = "user_print_stopped"
  1674. else:
  1675. return
  1676. await notification_service.send_user_print_email(
  1677. event_type=event_type,
  1678. created_by_id=created_by_id,
  1679. printer_name=printer_name,
  1680. filename=filename,
  1681. db=db,
  1682. )
  1683. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  1684. """Extract printable objects from an archive's 3MF file and store in printer state."""
  1685. try:
  1686. from backend.app.services.archive import extract_printable_objects_from_3mf
  1687. file_path = app_settings.base_dir / archive.file_path
  1688. if file_path.is_file() and str(file_path).endswith(".3mf"):
  1689. with open(file_path, "rb") as f:
  1690. threemf_data = f.read()
  1691. # Extract with positions for UI overlay
  1692. printable_objects, bbox_all = extract_printable_objects_from_3mf(threemf_data, include_positions=True)
  1693. if printable_objects:
  1694. client = printer_manager.get_client(printer_id)
  1695. if client:
  1696. client.state.printable_objects = printable_objects
  1697. client.state.printable_objects_bbox_all = bbox_all
  1698. client.state.skipped_objects = []
  1699. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  1700. except Exception as e:
  1701. logger.debug("Failed to extract printable objects from archive: %s", e)
  1702. async def on_print_start(printer_id: int, data: dict):
  1703. """Handle print start - archive the 3MF file immediately."""
  1704. logger = logging.getLogger(__name__)
  1705. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  1706. # Clear any stale user-stopped flag from previous print cycles
  1707. _user_stopped_printers.discard(printer_id)
  1708. # Cancel any active bed cooldown waiter for this printer
  1709. if _bed_cool_waiters.pop(printer_id, None):
  1710. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  1711. # Clear cached cover images so the new print's thumbnail is fetched fresh
  1712. from backend.app.api.routes.printers import clear_cover_cache
  1713. clear_cover_cache(printer_id)
  1714. await ws_manager.send_print_start(printer_id, data)
  1715. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  1716. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  1717. # MQTT relay - publish print start
  1718. try:
  1719. printer_info = printer_manager.get_printer(printer_id)
  1720. if printer_info:
  1721. await mqtt_relay.on_print_start(
  1722. printer_id,
  1723. printer_info.name,
  1724. printer_info.serial_number,
  1725. data.get("filename", ""),
  1726. data.get("subtask_name", ""),
  1727. )
  1728. except Exception:
  1729. pass # Don't fail print start callback if MQTT fails
  1730. # Capture AMS tray remain% for filament consumption tracking (skip if Spoolman handles usage)
  1731. try:
  1732. async with async_session() as db:
  1733. from backend.app.api.routes.settings import get_setting
  1734. _spoolman_on = await get_setting(db, "spoolman_enabled")
  1735. if not _spoolman_on or _spoolman_on.lower() != "true":
  1736. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  1737. await usage_on_print_start(printer_id, data, printer_manager, db=db)
  1738. except Exception as e:
  1739. logger.warning("Usage tracker on_print_start failed: %s", e)
  1740. # Track if notification was sent (to avoid sending twice)
  1741. notification_sent = False
  1742. # Smart plug automation: turn on plug when print starts
  1743. try:
  1744. async with async_session() as db:
  1745. await smart_plug_manager.on_print_start(printer_id, db)
  1746. except Exception as e:
  1747. logger.warning("Smart plug on_print_start failed: %s", e)
  1748. async with async_session() as db:
  1749. from backend.app.models.printer import Printer
  1750. from backend.app.services.bambu_ftp import list_files_async
  1751. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1752. printer = result.scalar_one_or_none()
  1753. # Plate detection check - pause if objects detected on build plate
  1754. logger.info(
  1755. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  1756. )
  1757. if printer and printer.plate_detection_enabled:
  1758. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  1759. try:
  1760. from backend.app.services.plate_detection import check_plate_empty
  1761. # Build ROI tuple from printer settings if available
  1762. roi = None
  1763. if all(
  1764. [
  1765. printer.plate_detection_roi_x is not None,
  1766. printer.plate_detection_roi_y is not None,
  1767. printer.plate_detection_roi_w is not None,
  1768. printer.plate_detection_roi_h is not None,
  1769. ]
  1770. ):
  1771. roi = (
  1772. printer.plate_detection_roi_x,
  1773. printer.plate_detection_roi_y,
  1774. printer.plate_detection_roi_w,
  1775. printer.plate_detection_roi_h,
  1776. )
  1777. # Auto-turn on chamber light if it's off for better detection
  1778. light_was_off = False
  1779. client = printer_manager.get_client(printer_id)
  1780. if client and client.state:
  1781. light_was_off = not client.state.chamber_light
  1782. if light_was_off:
  1783. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  1784. client.set_chamber_light(True)
  1785. # Wait for light to physically turn on and camera to adjust exposure
  1786. await asyncio.sleep(2.5)
  1787. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  1788. plate_result = await check_plate_empty(
  1789. printer_id=printer_id,
  1790. ip_address=printer.ip_address,
  1791. access_code=printer.access_code,
  1792. model=printer.model,
  1793. include_debug_image=False,
  1794. external_camera_url=printer.external_camera_url,
  1795. external_camera_type=printer.external_camera_type,
  1796. use_external=printer.external_camera_enabled,
  1797. roi=roi,
  1798. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  1799. )
  1800. # Restore chamber light to original state
  1801. if light_was_off and client:
  1802. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  1803. client.set_chamber_light(False)
  1804. if not plate_result.needs_calibration and not plate_result.is_empty:
  1805. # Objects detected - pause the print!
  1806. logger.warning(
  1807. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  1808. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  1809. )
  1810. client = printer_manager.get_client(printer_id)
  1811. if client:
  1812. client.pause_print()
  1813. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  1814. # Send notification about plate not empty
  1815. await ws_manager.broadcast(
  1816. {
  1817. "type": "plate_not_empty",
  1818. "printer_id": printer_id,
  1819. "printer_name": printer.name,
  1820. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  1821. }
  1822. )
  1823. # Also send push notification
  1824. try:
  1825. await notification_service.on_plate_not_empty(
  1826. printer_id=printer_id,
  1827. printer_name=printer.name,
  1828. db=db,
  1829. difference_percent=plate_result.difference_percent,
  1830. )
  1831. except Exception as notif_err:
  1832. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  1833. else:
  1834. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  1835. except Exception as plate_err:
  1836. # Don't block print on plate detection errors
  1837. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  1838. if not printer:
  1839. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  1840. if not notification_sent:
  1841. await _send_print_start_notification(printer_id, data, logger=logger)
  1842. return
  1843. if not printer.auto_archive:
  1844. # auto-archive disabled — check if there's an expected print (dispatched
  1845. # by BamBuddy via queue/reprint) that already has an archive to promote.
  1846. # If so, fall through to the expected-print handling below so the archive
  1847. # is tracked in _active_prints and usage tracking works at completion.
  1848. _fn = data.get("filename", "")
  1849. _sn = data.get("subtask_name", "")
  1850. _check_keys: list[tuple[int, str]] = []
  1851. if _sn:
  1852. _check_keys += [
  1853. (printer_id, _sn),
  1854. (printer_id, f"{_sn}.3mf"),
  1855. (printer_id, f"{_sn}.gcode.3mf"),
  1856. ]
  1857. if _fn:
  1858. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  1859. _check_keys.append((printer_id, _base_fn))
  1860. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  1861. _check_keys += [
  1862. (printer_id, _no_archive_base),
  1863. (printer_id, f"{_no_archive_base}.3mf"),
  1864. ]
  1865. _has_expected = any(k in _expected_prints for k in _check_keys)
  1866. if not _has_expected:
  1867. # No expected print — truly external print (started from slicer/touchscreen)
  1868. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  1869. if not notification_sent:
  1870. _no_archive_creator: int | None = None
  1871. for _key in _check_keys:
  1872. _expected_prints.pop(_key, None)
  1873. _expected_print_registered_at.pop(_key, None)
  1874. popped_creator = _expected_print_creators.pop(_key, None)
  1875. if _no_archive_creator is None:
  1876. _no_archive_creator = popped_creator
  1877. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  1878. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  1879. return
  1880. else:
  1881. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  1882. # Get the filename and subtask_name
  1883. filename = data.get("filename", "")
  1884. subtask_name = data.get("subtask_name", "")
  1885. # MQTT subtask_id uniquely identifies a print job on the printer. When
  1886. # present, it lets us match an archive across a backend restart (#972):
  1887. # same id → same print → resume the existing row instead of cancelling
  1888. # it and recreating from scratch (which loses started_at). Treat "0"
  1889. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  1890. raw_mqtt = data.get("raw_data") or {}
  1891. subtask_id = raw_mqtt.get("subtask_id")
  1892. if subtask_id is not None:
  1893. subtask_id = str(subtask_id).strip()
  1894. if subtask_id in ("", "0"):
  1895. subtask_id = None
  1896. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  1897. # Skip calibration prints — internal printer files should not be archived
  1898. # Bambu calibration gcode lives under /usr/ (e.g. /usr/etc/print/auto_cali_for_user.gcode)
  1899. if filename and filename.startswith("/usr/"):
  1900. logger.info("[CALLBACK] Skipping archive — internal printer file detected: %s", filename)
  1901. if not notification_sent:
  1902. await _send_print_start_notification(printer_id, data, logger=logger)
  1903. return
  1904. if not filename and not subtask_name:
  1905. # Send notification without archive data (no filename)
  1906. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  1907. if not notification_sent:
  1908. await _send_print_start_notification(printer_id, data, logger=logger)
  1909. return
  1910. # Check if this is an expected print from reprint/scheduled
  1911. # Build list of possible keys to check
  1912. expected_keys = []
  1913. if subtask_name:
  1914. expected_keys.append((printer_id, subtask_name))
  1915. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  1916. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  1917. if filename:
  1918. fname = filename.split("/")[-1] if "/" in filename else filename
  1919. expected_keys.append((printer_id, fname))
  1920. # Strip extensions to match
  1921. base = fname.replace(".gcode", "").replace(".3mf", "")
  1922. expected_keys.append((printer_id, base))
  1923. expected_keys.append((printer_id, f"{base}.3mf"))
  1924. expected_archive_id = None
  1925. for key in expected_keys:
  1926. expected_archive_id = _expected_prints.pop(key, None)
  1927. _expected_print_registered_at.pop(key, None)
  1928. if expected_archive_id:
  1929. # Clean up other possible keys for this print
  1930. for other_key in expected_keys:
  1931. _expected_prints.pop(other_key, None)
  1932. _expected_print_registered_at.pop(other_key, None)
  1933. break
  1934. if expected_archive_id:
  1935. # This is a reprint/scheduled print - use existing archive, don't create new one
  1936. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  1937. from backend.app.models.archive import PrintArchive
  1938. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  1939. archive = result.scalar_one_or_none()
  1940. if archive:
  1941. # Update archive status to printing
  1942. archive.status = "printing"
  1943. archive.started_at = datetime.now(timezone.utc)
  1944. # Persist a restart-stable id so a later restart resumes this
  1945. # archive by subtask_id instead of name-matching + duplicating
  1946. # it (#1485). The printer often hasn't echoed subtask_id back
  1947. # this soon after dispatch, so fall back to the id Bambuddy
  1948. # minted when it sent the print command. Scoped to this
  1949. # expected-print branch on purpose: an expected match means
  1950. # Bambuddy dispatched this exact print in this process, so the
  1951. # client's last-dispatch id genuinely belongs to it — using it
  1952. # for an externally-started print could mis-tag the archive.
  1953. effective_subtask_id = subtask_id
  1954. if not effective_subtask_id:
  1955. _client = printer_manager.get_client(printer_id)
  1956. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  1957. if _dispatched:
  1958. effective_subtask_id = str(_dispatched).strip() or None
  1959. if effective_subtask_id and not archive.subtask_id:
  1960. archive.subtask_id = effective_subtask_id
  1961. # #1403 follow-up: VP-queue archives are created with
  1962. # printer_id=None at queue-add time (we don't know which
  1963. # printer will run the job yet). When the print actually
  1964. # starts on a specific printer the expected-archive lookup
  1965. # used to skip this assignment, leaving printer_id=None
  1966. # forever — which then disables the "Scan for timelapse"
  1967. # button in ArchivesPage (gated on !archive.printer_id).
  1968. if archive.printer_id != printer_id:
  1969. archive.printer_id = printer_id
  1970. await db.commit()
  1971. # Track as active print
  1972. _active_prints[(printer_id, archive.filename)] = archive.id
  1973. if subtask_name:
  1974. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  1975. # Start timelapse session if external camera is enabled (#1353).
  1976. # Queue / VP-dispatched prints land here in the expected-archive
  1977. # branch and used to skip start_session entirely — frames were
  1978. # never captured and the post-print stitch silently returned None.
  1979. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  1980. # Inject ams_mapping into usage tracker session — the session was created
  1981. # before expected-print promotion, so it may have ams_mapping=None when
  1982. # the MQTT request topic subscription failed (common on P1S/A1).
  1983. _stored_map = _print_ams_mappings.get(expected_archive_id)
  1984. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  1985. if _stored_map or _stored_plate_id is not None:
  1986. try:
  1987. from backend.app.services.usage_tracker import _active_sessions
  1988. _ut_session = _active_sessions.get(printer_id)
  1989. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  1990. _ut_session.ams_mapping = _stored_map
  1991. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  1992. # plate_id injection covers direct-Print of plate N of a multi-plate
  1993. # 3MF — queue prints already capture it via the on_print_start queue
  1994. # lookup, but direct-Print never goes through the queue (#1697).
  1995. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  1996. _ut_session.plate_id = _stored_plate_id
  1997. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  1998. except Exception:
  1999. pass
  2000. # Set up energy tracking (#941: persist start on archive row)
  2001. await _record_energy_start(archive, printer_id, db, context="expected-print")
  2002. await ws_manager.send_archive_updated(
  2003. {
  2004. "id": archive.id,
  2005. "status": "printing",
  2006. }
  2007. )
  2008. # Send notification with archive data (reprint/scheduled)
  2009. if not notification_sent:
  2010. # Use archive's created_by_id; fall back to the creator registered via
  2011. # register_expected_print (handles library-file-based queue items where
  2012. # the freshly-created archive has no created_by_id yet).
  2013. # Pop ALL matching keys so no stale entries remain in the dict.
  2014. fallback_creator = None
  2015. for key in expected_keys:
  2016. popped = _expected_print_creators.pop(key, None)
  2017. if fallback_creator is None:
  2018. fallback_creator = popped
  2019. archive_data = {
  2020. "print_time_seconds": archive.print_time_seconds,
  2021. "created_by_id": archive.created_by_id or fallback_creator,
  2022. }
  2023. await _send_print_start_notification(printer_id, data, archive_data, logger)
  2024. # Extract printable objects from the archived 3MF file
  2025. _load_objects_from_archive(archive, printer_id, logger)
  2026. # Store Spoolman tracking data for per-filament usage reporting
  2027. try:
  2028. await _store_spoolman_print_data(
  2029. printer_id,
  2030. archive.id,
  2031. archive.file_path,
  2032. db,
  2033. printer_manager,
  2034. ams_mapping=_get_start_ams_mapping(data, archive.id),
  2035. plate_id=_get_start_plate_id(archive.id),
  2036. )
  2037. except Exception as e:
  2038. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  2039. # Capture timelapse file baseline for snapshot-diff on completion
  2040. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  2041. # hit this branch — without the baseline the completion-time scan
  2042. # falls into its "take baseline now" fallback, which snapshots
  2043. # AFTER the new MP4 already exists and never matches a diff
  2044. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  2045. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  2046. return # Skip creating a new archive
  2047. # Check if there's already a "printing" archive for this printer/file
  2048. # This prevents duplicates when backend restarts during an active print
  2049. from backend.app.models.archive import PrintArchive
  2050. existing_archive: PrintArchive | None = None
  2051. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  2052. # across a backend restart for the same print, so this is the most
  2053. # reliable way to reattach. We also accept a previously stale-cancelled
  2054. # archive here so users upgrading mid-print get revived when the row
  2055. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  2056. if subtask_id:
  2057. by_id = await db.execute(
  2058. select(PrintArchive)
  2059. .where(PrintArchive.printer_id == printer_id)
  2060. .where(PrintArchive.subtask_id == subtask_id)
  2061. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  2062. .order_by(PrintArchive.created_at.desc())
  2063. .limit(1)
  2064. )
  2065. candidate = by_id.scalar_one_or_none()
  2066. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  2067. existing_archive = candidate
  2068. # Fallback match: name-based lookup. Kept as-is for prints whose
  2069. # subtask_id is missing ("0" / local / non-cloud prints).
  2070. if existing_archive is None:
  2071. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  2072. existing = await db.execute(
  2073. select(PrintArchive)
  2074. .where(PrintArchive.printer_id == printer_id)
  2075. .where(PrintArchive.status == "printing")
  2076. .where(
  2077. or_(
  2078. PrintArchive.print_name == check_name,
  2079. PrintArchive.filename.in_(
  2080. [
  2081. f"{check_name}.3mf",
  2082. f"{check_name}.gcode.3mf",
  2083. ]
  2084. ),
  2085. )
  2086. )
  2087. .order_by(PrintArchive.created_at.desc())
  2088. .limit(1)
  2089. )
  2090. existing_archive = existing.scalar_one_or_none()
  2091. if existing_archive:
  2092. # subtask_id match → always resume, regardless of age. Same print,
  2093. # just a backend restart. Revive if it was previously stale-cancelled.
  2094. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  2095. if subtask_match:
  2096. if existing_archive.status == "cancelled":
  2097. logger.warning(
  2098. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  2099. existing_archive.id,
  2100. subtask_id,
  2101. )
  2102. existing_archive.status = "printing"
  2103. existing_archive.failure_reason = None
  2104. await db.commit()
  2105. else:
  2106. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  2107. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  2108. if existing_archive.energy_start_kwh is None:
  2109. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  2110. if not notification_sent:
  2111. archive_data = {
  2112. "print_time_seconds": existing_archive.print_time_seconds,
  2113. "created_by_id": existing_archive.created_by_id,
  2114. }
  2115. await _send_print_start_notification(printer_id, data, archive_data, logger)
  2116. _load_objects_from_archive(existing_archive, printer_id, logger)
  2117. return
  2118. # Name-match only (no subtask_id to anchor on): decide resume vs.
  2119. # stale from the printer's *current* progress, not wall-clock age.
  2120. # A genuinely long print used to trip a blind 4h cutoff and have its
  2121. # live archive cancelled + duplicated on every backend restart
  2122. # (#1485). If the printer reports real progress, this name-matched
  2123. # 'printing' archive IS that ongoing print — resume it whatever its
  2124. # age. Only treat it as a stale leftover when the printer clearly
  2125. # shows a different, freshly-started print: near-0% progress on an
  2126. # archive far too old to still be at 0%. Unknown progress (printer
  2127. # not connected) never cancels — resuming is the safe default.
  2128. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  2129. live_status = printer_manager.get_status(printer_id)
  2130. live_progress = getattr(live_status, "progress", None) if live_status else None
  2131. looks_stale = (
  2132. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  2133. )
  2134. if looks_stale:
  2135. logger.warning(
  2136. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}, "
  2137. f"printer progress {live_progress:.0f}%) — marking cancelled and creating new archive"
  2138. )
  2139. existing_archive.status = "cancelled"
  2140. existing_archive.failure_reason = "Stale - print likely cancelled or failed without status update"
  2141. await db.commit()
  2142. # Fall through to create new archive (don't return)
  2143. else:
  2144. logger.info(
  2145. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  2146. )
  2147. # Track this as the active print
  2148. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  2149. # Attach subtask_id retroactively so future restarts can resume
  2150. if subtask_id and not existing_archive.subtask_id:
  2151. existing_archive.subtask_id = subtask_id
  2152. await db.commit()
  2153. # Also set up energy tracking if not already tracked (#941: persisted column)
  2154. if existing_archive.energy_start_kwh is None:
  2155. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  2156. # Send notification with archive data (existing archive)
  2157. if not notification_sent:
  2158. archive_data = {
  2159. "print_time_seconds": existing_archive.print_time_seconds,
  2160. "created_by_id": existing_archive.created_by_id,
  2161. }
  2162. await _send_print_start_notification(printer_id, data, archive_data, logger)
  2163. # Extract printable objects from the archived 3MF file
  2164. _load_objects_from_archive(existing_archive, printer_id, logger)
  2165. return
  2166. # Build list of possible 3MF filenames to try
  2167. possible_names = []
  2168. # Bambu printers typically store files as "Name.gcode.3mf"
  2169. # The subtask_name is usually the best source for the filename
  2170. if subtask_name:
  2171. # Try common Bambu naming patterns
  2172. possible_names.append(f"{subtask_name}.gcode.3mf")
  2173. possible_names.append(f"{subtask_name}.3mf")
  2174. # Try original filename with .3mf extension
  2175. if filename:
  2176. # Extract just the filename part, not the full path
  2177. fname = filename.split("/")[-1] if "/" in filename else filename
  2178. if fname.endswith(".3mf"):
  2179. possible_names.append(fname)
  2180. elif fname.endswith(".gcode"):
  2181. base = fname.rsplit(".", 1)[0]
  2182. possible_names.append(f"{base}.gcode.3mf")
  2183. possible_names.append(f"{base}.3mf")
  2184. else:
  2185. possible_names.append(f"{fname}.gcode.3mf")
  2186. possible_names.append(f"{fname}.3mf")
  2187. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  2188. space_variants = []
  2189. for name in possible_names:
  2190. if " " in name:
  2191. space_variants.append(name.replace(" ", "_"))
  2192. possible_names.extend(space_variants)
  2193. # Remove duplicates while preserving order
  2194. seen = set()
  2195. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  2196. logger.info("Trying filenames: %s", possible_names)
  2197. # Try to find and download the 3MF file
  2198. temp_path = None
  2199. downloaded_filename = None
  2200. # Cache check: cover endpoint may have already pulled this 3MF during
  2201. # the print (frontend opens the card and shows the thumbnail) — reuse
  2202. # that file instead of re-downloading 36MB over the same FTP link that
  2203. # just served it (#972). The cache keys on a normalized filename so
  2204. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  2205. for try_filename in possible_names:
  2206. if not try_filename.endswith(".3mf"):
  2207. continue
  2208. cached = get_cached_3mf(printer_id, try_filename)
  2209. if cached:
  2210. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  2211. temp_path = cached
  2212. downloaded_filename = try_filename
  2213. break
  2214. # Get FTP retry settings
  2215. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  2216. for try_filename in possible_names if not downloaded_filename else []:
  2217. if not try_filename.endswith(".3mf"):
  2218. continue
  2219. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  2220. # printers, so try it first — deferring it to last cost #972's reporter
  2221. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  2222. # landing on the path that actually had the file.
  2223. remote_paths = [
  2224. f"/{try_filename}",
  2225. f"/cache/{try_filename}",
  2226. f"/model/{try_filename}",
  2227. f"/data/{try_filename}",
  2228. f"/data/Metadata/{try_filename}",
  2229. ]
  2230. temp_path = app_settings.archive_dir / "temp" / try_filename
  2231. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2232. for remote_path in remote_paths:
  2233. logger.debug("Trying FTP download: %s", remote_path)
  2234. try:
  2235. if ftp_retry_enabled:
  2236. downloaded = await with_ftp_retry(
  2237. download_file_async,
  2238. printer.ip_address,
  2239. printer.access_code,
  2240. remote_path,
  2241. temp_path,
  2242. timeout=ftp_timeout,
  2243. socket_timeout=ftp_timeout,
  2244. printer_model=printer.model,
  2245. max_retries=ftp_retry_count,
  2246. retry_delay=ftp_retry_delay,
  2247. operation_name=f"Download 3MF from {remote_path}",
  2248. non_retry_exceptions=(FileNotOnPrinterError,),
  2249. )
  2250. else:
  2251. downloaded = await download_file_async(
  2252. printer.ip_address,
  2253. printer.access_code,
  2254. remote_path,
  2255. temp_path,
  2256. timeout=ftp_timeout,
  2257. socket_timeout=ftp_timeout,
  2258. printer_model=printer.model,
  2259. )
  2260. if downloaded:
  2261. downloaded_filename = try_filename
  2262. logger.info("Downloaded: %s", remote_path)
  2263. # Populate shared cache so the cover endpoint (if it
  2264. # runs next) doesn't refetch the same 36MB over FTP.
  2265. cache_3mf_download(printer_id, try_filename, temp_path)
  2266. break
  2267. except FileNotOnPrinterError:
  2268. # 550 — file isn't at this path. Advance to next candidate
  2269. # without burning the retry budget.
  2270. logger.debug("3MF not at %s (550), trying next path", remote_path)
  2271. except Exception as e:
  2272. logger.debug("FTP download failed for %s: %s", remote_path, e)
  2273. if downloaded_filename:
  2274. break
  2275. # If still not found, try listing directories to find matching file
  2276. # Different printer models use different directory structures
  2277. if not downloaded_filename and (filename or subtask_name):
  2278. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  2279. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  2280. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  2281. for search_dir in search_dirs:
  2282. if downloaded_filename:
  2283. break
  2284. try:
  2285. dir_files = await list_files_async(
  2286. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  2287. )
  2288. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  2289. if threemf_files:
  2290. logger.info(
  2291. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  2292. )
  2293. for f in dir_files:
  2294. if f.get("is_directory"):
  2295. continue
  2296. fname = f.get("name", "")
  2297. # Normalize both for comparison (spaces and underscores are equivalent)
  2298. fname_normalized = fname.lower().replace(" ", "_")
  2299. search_normalized = search_term.replace(" ", "_")
  2300. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  2301. logger.info("Found matching file in %s: %s", search_dir, fname)
  2302. temp_path = app_settings.archive_dir / "temp" / fname
  2303. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2304. remote_full_path = posixpath.join(search_dir, fname)
  2305. if ftp_retry_enabled:
  2306. downloaded = await with_ftp_retry(
  2307. download_file_async,
  2308. printer.ip_address,
  2309. printer.access_code,
  2310. remote_full_path,
  2311. temp_path,
  2312. timeout=ftp_timeout,
  2313. socket_timeout=ftp_timeout,
  2314. printer_model=printer.model,
  2315. max_retries=ftp_retry_count,
  2316. retry_delay=ftp_retry_delay,
  2317. operation_name=f"Download 3MF from {remote_full_path}",
  2318. )
  2319. else:
  2320. downloaded = await download_file_async(
  2321. printer.ip_address,
  2322. printer.access_code,
  2323. remote_full_path,
  2324. temp_path,
  2325. timeout=ftp_timeout,
  2326. socket_timeout=ftp_timeout,
  2327. printer_model=printer.model,
  2328. )
  2329. if downloaded:
  2330. downloaded_filename = fname
  2331. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  2332. cache_3mf_download(printer_id, fname, temp_path)
  2333. break
  2334. except Exception as e:
  2335. logger.debug("Failed to list %s: %s", search_dir, e)
  2336. # Validate the downloaded 3MF actually matches the plate that's running
  2337. # (#1204): subtask_name lags across consecutive plates of the same model,
  2338. # so the first FTP candidate (built from subtask_name) can land on the
  2339. # previous plate's still-resident upload. Cross-check the slice_info
  2340. # plate index against the plate parsed from gcode_file (always fresh —
  2341. # it's the field whose change triggered this callback).
  2342. if downloaded_filename and temp_path:
  2343. expected_plate = parse_plate_id(filename)
  2344. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  2345. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  2346. logger.warning(
  2347. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  2348. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  2349. downloaded_filename,
  2350. actual_plate,
  2351. expected_plate,
  2352. subtask_name,
  2353. )
  2354. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  2355. retry_succeeded = False
  2356. if corrected_subtask and corrected_subtask != subtask_name:
  2357. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  2358. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  2359. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  2360. for remote_path in (
  2361. f"/{try_filename}",
  2362. f"/cache/{try_filename}",
  2363. f"/model/{try_filename}",
  2364. f"/data/{try_filename}",
  2365. f"/data/Metadata/{try_filename}",
  2366. ):
  2367. try:
  2368. if ftp_retry_enabled:
  2369. downloaded = await with_ftp_retry(
  2370. download_file_async,
  2371. printer.ip_address,
  2372. printer.access_code,
  2373. remote_path,
  2374. retry_temp_path,
  2375. timeout=ftp_timeout,
  2376. socket_timeout=ftp_timeout,
  2377. printer_model=printer.model,
  2378. max_retries=ftp_retry_count,
  2379. retry_delay=ftp_retry_delay,
  2380. operation_name=f"Re-download 3MF from {remote_path}",
  2381. non_retry_exceptions=(FileNotOnPrinterError,),
  2382. )
  2383. else:
  2384. downloaded = await download_file_async(
  2385. printer.ip_address,
  2386. printer.access_code,
  2387. remote_path,
  2388. retry_temp_path,
  2389. timeout=ftp_timeout,
  2390. socket_timeout=ftp_timeout,
  2391. printer_model=printer.model,
  2392. )
  2393. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  2394. logger.info(
  2395. "[CALLBACK] Re-download succeeded with corrected name %s "
  2396. "(plate %s) — replacing wrong file",
  2397. try_filename,
  2398. expected_plate,
  2399. )
  2400. try:
  2401. temp_path.unlink(missing_ok=True)
  2402. except OSError:
  2403. pass
  2404. temp_path = retry_temp_path
  2405. downloaded_filename = try_filename
  2406. subtask_name = corrected_subtask
  2407. cache_3mf_download(printer_id, try_filename, temp_path)
  2408. retry_succeeded = True
  2409. break
  2410. elif downloaded:
  2411. # Wrong plate again — discard and keep trying
  2412. try:
  2413. retry_temp_path.unlink(missing_ok=True)
  2414. except OSError:
  2415. pass
  2416. except FileNotOnPrinterError:
  2417. continue
  2418. except Exception as e:
  2419. logger.debug("Re-download failed for %s: %s", remote_path, e)
  2420. if retry_succeeded:
  2421. break
  2422. # If the retry didn't find a matching file, drop the wrong 3MF
  2423. # so the no-3MF fallback below creates an archive whose name
  2424. # at least reflects the right plate.
  2425. if not retry_succeeded:
  2426. logger.warning(
  2427. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  2428. expected_plate,
  2429. )
  2430. try:
  2431. temp_path.unlink(missing_ok=True)
  2432. except OSError:
  2433. pass
  2434. temp_path = None
  2435. downloaded_filename = None
  2436. # Override the stale subtask_name so the fallback archive's
  2437. # print_name reflects the correct plate. Prefer the swapped
  2438. # name when we have one; otherwise let filename win.
  2439. if corrected_subtask:
  2440. subtask_name = corrected_subtask
  2441. else:
  2442. subtask_name = ""
  2443. if not downloaded_filename or not temp_path:
  2444. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  2445. # Create a fallback archive without 3MF data so the print is still tracked
  2446. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  2447. try:
  2448. from backend.app.models.archive import PrintArchive
  2449. # Derive print name from subtask_name or filename
  2450. print_name = subtask_name or filename
  2451. if print_name:
  2452. # Clean up the name (remove extensions, path parts)
  2453. print_name = print_name.split("/")[-1]
  2454. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  2455. else:
  2456. print_name = "Unknown Print"
  2457. # Recover estimated print time from MQTT (best-effort for notifications)
  2458. fallback_print_time = None
  2459. mqtt_remaining = data.get("remaining_time")
  2460. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  2461. fallback_print_time = int(mqtt_remaining)
  2462. if fallback_print_time is None:
  2463. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  2464. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  2465. fallback_print_time = int(mc_remaining * 60)
  2466. # Best-effort filament metadata from MQTT — see
  2467. # _extract_filament_data_from_mqtt. Without this the fallback
  2468. # archive's filament fields stayed NULL even though the AMS
  2469. # state at print start was sitting right there in `data`.
  2470. # The slicer's ams_mapping (when present) narrows the result
  2471. # to slots actually used by the print (#1533).
  2472. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  2473. # Create minimal archive entry
  2474. fallback_archive = PrintArchive(
  2475. printer_id=printer_id,
  2476. filename=filename or f"{print_name}.3mf",
  2477. file_path="", # Empty - no 3MF file available
  2478. file_size=0,
  2479. print_name=print_name,
  2480. print_time_seconds=fallback_print_time,
  2481. status="printing",
  2482. started_at=datetime.now(timezone.utc),
  2483. subtask_id=subtask_id,
  2484. filament_type=mqtt_filament_meta.get("filament_type"),
  2485. filament_color=mqtt_filament_meta.get("filament_color"),
  2486. extra_data={"no_3mf_available": True, "original_subtask": subtask_name, "_print_data": data},
  2487. )
  2488. db.add(fallback_archive)
  2489. await db.commit()
  2490. await db.refresh(fallback_archive)
  2491. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  2492. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  2493. # Track as active print
  2494. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  2495. if filename:
  2496. _active_prints[(printer_id, filename)] = fallback_archive.id
  2497. if subtask_name:
  2498. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  2499. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  2500. # Record starting energy if smart plug available (#941: persisted column)
  2501. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  2502. # Send WebSocket notification
  2503. await ws_manager.send_archive_created(
  2504. {
  2505. "id": fallback_archive.id,
  2506. "printer_id": fallback_archive.printer_id,
  2507. "filename": fallback_archive.filename,
  2508. "print_name": fallback_archive.print_name,
  2509. "status": fallback_archive.status,
  2510. }
  2511. )
  2512. # MQTT relay - publish archive created
  2513. try:
  2514. await mqtt_relay.on_archive_created(
  2515. archive_id=fallback_archive.id,
  2516. print_name=fallback_archive.print_name,
  2517. printer_name=printer.name,
  2518. status=fallback_archive.status,
  2519. )
  2520. except Exception:
  2521. pass # Don't fail if MQTT fails
  2522. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  2523. try:
  2524. await _store_spoolman_print_data(
  2525. printer_id,
  2526. fallback_archive.id,
  2527. fallback_archive.file_path,
  2528. db,
  2529. printer_manager,
  2530. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  2531. plate_id=_get_start_plate_id(fallback_archive.id),
  2532. )
  2533. except Exception as e:
  2534. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  2535. # Send notification without archive data (file not found)
  2536. if not notification_sent:
  2537. await _send_print_start_notification(printer_id, data, logger=logger)
  2538. return
  2539. except Exception as e:
  2540. logger.error("Failed to create fallback archive: %s", e)
  2541. # Send notification without archive data (file not found)
  2542. if not notification_sent:
  2543. await _send_print_start_notification(printer_id, data, logger=logger)
  2544. return
  2545. try:
  2546. # Archive the file with status "printing"
  2547. service = ArchiveService(db)
  2548. archive = await service.archive_print(
  2549. printer_id=printer_id,
  2550. source_file=temp_path,
  2551. print_data={**data, "status": "printing"},
  2552. subtask_id=subtask_id,
  2553. )
  2554. if archive:
  2555. # Track this active print (use both original filename and downloaded filename)
  2556. _active_prints[(printer_id, downloaded_filename)] = archive.id
  2557. if filename and filename != downloaded_filename:
  2558. _active_prints[(printer_id, filename)] = archive.id
  2559. if subtask_name:
  2560. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  2561. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  2562. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  2563. # Record starting energy from smart plug if available (#941: persisted column)
  2564. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  2565. await ws_manager.send_archive_created(
  2566. {
  2567. "id": archive.id,
  2568. "printer_id": archive.printer_id,
  2569. "filename": archive.filename,
  2570. "print_name": archive.print_name,
  2571. "status": archive.status,
  2572. }
  2573. )
  2574. # MQTT relay - publish archive created
  2575. try:
  2576. await mqtt_relay.on_archive_created(
  2577. archive_id=archive.id,
  2578. print_name=archive.print_name,
  2579. printer_name=printer.name,
  2580. status=archive.status,
  2581. )
  2582. except Exception:
  2583. pass # Don't fail if MQTT fails
  2584. # Send notification with archive data (new archive created)
  2585. if not notification_sent:
  2586. archive_data = {
  2587. "print_time_seconds": archive.print_time_seconds,
  2588. "created_by_id": archive.created_by_id,
  2589. }
  2590. await _send_print_start_notification(printer_id, data, archive_data, logger)
  2591. # Extract printable objects for skip object functionality
  2592. try:
  2593. from backend.app.services.archive import extract_printable_objects_from_3mf
  2594. with open(temp_path, "rb") as f:
  2595. threemf_data = f.read()
  2596. # Extract with positions for UI overlay
  2597. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  2598. threemf_data, include_positions=True
  2599. )
  2600. if printable_objects:
  2601. # Store objects in printer state
  2602. client = printer_manager.get_client(printer_id)
  2603. if client:
  2604. client.state.printable_objects = printable_objects
  2605. client.state.printable_objects_bbox_all = bbox_all
  2606. client.state.skipped_objects = [] # Reset skipped objects for new print
  2607. logger.info(
  2608. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  2609. )
  2610. except Exception as e:
  2611. logger.debug("Failed to extract printable objects: %s", e)
  2612. # Store Spoolman tracking data for per-filament usage reporting
  2613. try:
  2614. await _store_spoolman_print_data(
  2615. printer_id,
  2616. archive.id,
  2617. archive.file_path,
  2618. db,
  2619. printer_manager,
  2620. ams_mapping=_get_start_ams_mapping(data, archive.id),
  2621. plate_id=_get_start_plate_id(archive.id),
  2622. )
  2623. except Exception as e:
  2624. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  2625. # Capture timelapse file baseline for snapshot-diff on completion
  2626. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  2627. finally:
  2628. # Keep temp_path around until print completes so the cover endpoint
  2629. # can reuse it (#972). Cache eviction in on_print_complete deletes
  2630. # the file. If the cache entry was evicted early (file vanished),
  2631. # clean up any stragglers here to avoid leaking disk on retries.
  2632. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  2633. if temp_path and temp_path.exists() and cached_now != temp_path:
  2634. temp_path.unlink()
  2635. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  2636. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  2637. """List video files from printer's timelapse directory.
  2638. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  2639. Returns (video_files, found_path) where video_files is a list of file dicts
  2640. and found_path is the directory where they were found, or ([], None).
  2641. """
  2642. from backend.app.services.bambu_ftp import list_files_async
  2643. logger = logging.getLogger(__name__)
  2644. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  2645. try:
  2646. found_files = await list_files_async(
  2647. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  2648. )
  2649. if found_files:
  2650. video_files = [
  2651. f
  2652. for f in found_files
  2653. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  2654. ]
  2655. if video_files:
  2656. return video_files, timelapse_path
  2657. except Exception as e:
  2658. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  2659. continue
  2660. return [], None
  2661. async def _capture_timelapse_baseline_at_start(printer, printer_id: int, logger: logging.Logger) -> None:
  2662. """Snapshot the printer's timelapse directory at print start so the
  2663. completion-time scan can pick the new file by set-difference.
  2664. Must be called from every on_print_start path that proceeds to a real
  2665. print — both the new-archive branch and the expected-archive branch (which
  2666. queue / VP-dispatched prints take). Without a baseline,
  2667. _scan_for_timelapse_with_retries falls into its "take baseline now"
  2668. fallback that runs AFTER the new MP4 has already landed on the SD card,
  2669. so the new file ends up in the "baseline" set and no diff ever matches.
  2670. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  2671. unreliable — the snapshot-diff approach sidesteps that entirely.
  2672. """
  2673. try:
  2674. baseline_files, _ = await _list_timelapse_videos(printer)
  2675. _timelapse_baselines[printer_id] = {f.get("name", "") for f in baseline_files}
  2676. logger.info(
  2677. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  2678. len(_timelapse_baselines[printer_id]),
  2679. printer_id,
  2680. )
  2681. except Exception as e:
  2682. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  2683. async def _scan_for_timelapse_with_retries(archive_id: int, baseline_names: set[str] | None = None):
  2684. """
  2685. Scan for timelapse with retries using a snapshot-diff approach.
  2686. Instead of picking the "most recent by mtime" (unreliable when the printer
  2687. clock is wrong in LAN-only mode), we snapshot existing MP4 filenames BEFORE
  2688. waiting, then look for any NEW filename that appears after each delay.
  2689. If baseline_names is provided (captured at print start), it is used directly.
  2690. Otherwise falls back to taking a baseline at completion time (best-effort
  2691. for prints started before app restart).
  2692. Falls back to name-matching (print name contained in MP4 filename) if no
  2693. new file appears after all retries.
  2694. """
  2695. from pathlib import Path
  2696. logger = logging.getLogger(__name__)
  2697. # --- Phase 1: Take baseline snapshot of existing timelapse files ---
  2698. try:
  2699. async with async_session() as db:
  2700. from backend.app.models.printer import Printer
  2701. service = ArchiveService(db)
  2702. archive = await service.get_archive(archive_id)
  2703. if not archive:
  2704. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  2705. return
  2706. if archive.timelapse_path:
  2707. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  2708. return
  2709. if not archive.printer_id:
  2710. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  2711. return
  2712. if baseline_names is not None:
  2713. # Use pre-captured baseline from print start (no race condition)
  2714. logger.info(
  2715. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  2716. len(baseline_names),
  2717. archive_id,
  2718. )
  2719. else:
  2720. # Fallback: take baseline now (e.g. app restarted mid-print)
  2721. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  2722. printer = result.scalar_one_or_none()
  2723. if not printer:
  2724. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  2725. return
  2726. baseline_files, _ = await _list_timelapse_videos(printer)
  2727. baseline_names = {f.get("name", "") for f in baseline_files}
  2728. logger.info(
  2729. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  2730. len(baseline_names),
  2731. archive_id,
  2732. )
  2733. # Derive base_name for name-matching fallback
  2734. base_name = Path(archive.filename).stem if archive.filename else ""
  2735. if base_name.endswith(".gcode"):
  2736. base_name = base_name[:-6]
  2737. except Exception as e:
  2738. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  2739. return
  2740. # --- Phase 2: Retry loop — look for NEW files that weren't in baseline ---
  2741. retry_delays = [5, 10, 20, 30]
  2742. for attempt, delay in enumerate(retry_delays, 1):
  2743. logger.info(
  2744. "[TIMELAPSE] Attempt %s/%s: waiting %ss before scanning for archive %s",
  2745. attempt,
  2746. len(retry_delays),
  2747. delay,
  2748. archive_id,
  2749. )
  2750. await asyncio.sleep(delay)
  2751. try:
  2752. async with async_session() as db:
  2753. from backend.app.models.printer import Printer
  2754. from backend.app.services.bambu_ftp import download_file_bytes_async
  2755. service = ArchiveService(db)
  2756. archive = await service.get_archive(archive_id)
  2757. if not archive:
  2758. logger.warning("[TIMELAPSE] Archive %s not found, stopping retries", archive_id)
  2759. return
  2760. if archive.timelapse_path:
  2761. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping retries", archive_id)
  2762. return
  2763. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  2764. printer = result.scalar_one_or_none()
  2765. if not printer:
  2766. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping retries", archive_id)
  2767. return
  2768. video_files, found_path = await _list_timelapse_videos(printer)
  2769. if not video_files:
  2770. logger.info("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  2771. continue
  2772. logger.info("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  2773. for f in video_files[:5]:
  2774. logger.info("[TIMELAPSE] - %s", f.get("name"))
  2775. # Find files that are NEW (not in baseline snapshot)
  2776. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  2777. if new_files:
  2778. # Pick the first new file (there should typically be exactly one)
  2779. target = new_files[0]
  2780. file_name = target.get("name")
  2781. remote_path = target.get("path") or f"/timelapse/{file_name}"
  2782. logger.info(
  2783. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  2784. attempt,
  2785. file_name,
  2786. archive_id,
  2787. )
  2788. timelapse_data = await download_file_bytes_async(
  2789. printer.ip_address, printer.access_code, remote_path, printer_model=printer.model
  2790. )
  2791. if timelapse_data:
  2792. success = await service.attach_timelapse(archive_id, timelapse_data, file_name)
  2793. if success:
  2794. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  2795. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  2796. return
  2797. else:
  2798. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  2799. else:
  2800. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  2801. else:
  2802. logger.info("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  2803. except Exception as e:
  2804. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  2805. # --- Phase 3: Fallback — try name matching against all files ---
  2806. if base_name:
  2807. logger.info("[TIMELAPSE] Retries exhausted, trying name-match fallback for '%s'", base_name)
  2808. try:
  2809. async with async_session() as db:
  2810. from backend.app.models.printer import Printer
  2811. from backend.app.services.bambu_ftp import download_file_bytes_async
  2812. service = ArchiveService(db)
  2813. archive = await service.get_archive(archive_id)
  2814. if not archive or archive.timelapse_path:
  2815. return
  2816. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  2817. printer = result.scalar_one_or_none()
  2818. if not printer:
  2819. return
  2820. video_files, found_path = await _list_timelapse_videos(printer)
  2821. for f in video_files:
  2822. fname = f.get("name", "")
  2823. if base_name.lower() in fname.lower():
  2824. remote_path = f.get("path") or f"/timelapse/{fname}"
  2825. logger.info("[TIMELAPSE] Name-match fallback: '%s' matches '%s'", base_name, fname)
  2826. timelapse_data = await download_file_bytes_async(
  2827. printer.ip_address, printer.access_code, remote_path, printer_model=printer.model
  2828. )
  2829. if timelapse_data:
  2830. success = await service.attach_timelapse(archive_id, timelapse_data, fname)
  2831. if success:
  2832. logger.info(
  2833. "[TIMELAPSE] Name-match fallback attached timelapse to archive %s", archive_id
  2834. )
  2835. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  2836. return
  2837. break # Only try the first name match
  2838. except Exception as e:
  2839. logger.warning("[TIMELAPSE] Name-match fallback failed: %s", e)
  2840. logger.warning("[TIMELAPSE] All attempts exhausted for archive %s, giving up", archive_id)
  2841. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  2842. # module-level so tests can monkeypatch them down to ~0 without timing out.
  2843. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  2844. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  2845. async def _capture_finish_photo_from_timelapse(
  2846. archive_id: int,
  2847. archive_dir: Path,
  2848. ) -> str | None:
  2849. """Wait for the per-print timelapse to land on the archive and extract its
  2850. last frame as the finish photo (#1397).
  2851. Bambu firmware stops timelapse recording after the toolhead parks but
  2852. before the bed-drop end-gcode runs, so the last frame frames the finished
  2853. print correctly. A live camera grab at gcode_state=FINISH captures the
  2854. bed already lowered.
  2855. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  2856. ``archive.timelapse_path`` when the file lands. This function polls for
  2857. that field. Returns the saved photo filename on success, or None if the
  2858. timelapse never arrives within the timeout / extraction fails / no
  2859. timelapse path was set — in which case the caller falls back to the
  2860. existing live-camera capture chain.
  2861. """
  2862. import uuid
  2863. from backend.app.models.archive import PrintArchive
  2864. from backend.app.services.camera import extract_video_last_frame
  2865. logger = logging.getLogger(__name__)
  2866. deadline = asyncio.get_event_loop().time() + _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS
  2867. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  2868. while True:
  2869. async with async_session() as db:
  2870. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2871. archive = result.scalar_one_or_none()
  2872. timelapse_relpath = archive.timelapse_path if archive else None
  2873. if timelapse_relpath:
  2874. video_path = app_settings.base_dir / timelapse_relpath
  2875. if video_path.exists() and video_path.stat().st_size > 0:
  2876. photos_dir = archive_dir / "photos"
  2877. photos_dir.mkdir(parents=True, exist_ok=True)
  2878. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  2879. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  2880. output_path = photos_dir / filename
  2881. if await extract_video_last_frame(video_path, output_path):
  2882. logger.info(
  2883. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  2884. video_path.name,
  2885. archive_id,
  2886. )
  2887. return filename
  2888. logger.warning(
  2889. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  2890. video_path.name,
  2891. archive_id,
  2892. )
  2893. return None
  2894. if asyncio.get_event_loop().time() >= deadline:
  2895. logger.info(
  2896. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  2897. archive_id,
  2898. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS,
  2899. )
  2900. return None
  2901. await asyncio.sleep(poll_interval)
  2902. async def _cleanup_forced_timelapse(archive_id: int, printer_id: int) -> None:
  2903. """Delete the timelapse Bambuddy forced on for #1397's finish-photo path.
  2904. Called from the finish-photo background task after the extractor has had
  2905. its turn (regardless of whether extraction succeeded — the user never
  2906. asked for a video and we shouldn't leave one behind even if ffmpeg
  2907. failed). Cleanup is best-effort and never raises: a printer that's
  2908. offline at cleanup time means a single orphaned file on the SD card,
  2909. not a broken Bambuddy flow.
  2910. Cleans both:
  2911. - the locally-attached file (clears archive.timelapse_path)
  2912. - the printer-side file via FTP DELE
  2913. """
  2914. from backend.app.models.archive import PrintArchive
  2915. from backend.app.models.printer import Printer
  2916. from backend.app.services.bambu_ftp import delete_file_async
  2917. logger = logging.getLogger(__name__)
  2918. local_relpath: str | None = None
  2919. printer = None
  2920. async with async_session() as db:
  2921. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2922. archive = archive_result.scalar_one_or_none()
  2923. if not archive or not archive.bambuddy_forced_timelapse:
  2924. return
  2925. local_relpath = archive.timelapse_path
  2926. if local_relpath:
  2927. local_abspath = app_settings.base_dir / local_relpath
  2928. try:
  2929. if local_abspath.exists():
  2930. local_abspath.unlink()
  2931. logger.info(
  2932. "[FORCED-TIMELAPSE] Deleted local timelapse %s for archive %s",
  2933. local_relpath,
  2934. archive_id,
  2935. )
  2936. except OSError as e:
  2937. logger.warning("[FORCED-TIMELAPSE] Could not delete local timelapse %s: %s", local_relpath, e)
  2938. archive.timelapse_path = None
  2939. await db.commit()
  2940. printer_result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2941. printer = printer_result.scalar_one_or_none()
  2942. if printer is None or not local_relpath:
  2943. return
  2944. # _scan_for_timelapse_with_retries used the original filename when it
  2945. # attached, so the basename of timelapse_path matches the printer-side
  2946. # filename. Try the directories the scanner walks (#1397).
  2947. filename = Path(local_relpath).name
  2948. for remote_dir in ("/timelapse", "/timelapse/video", "/record", "/recording"):
  2949. remote_path = f"{remote_dir}/{filename}"
  2950. try:
  2951. ok = await delete_file_async(
  2952. printer.ip_address,
  2953. printer.access_code,
  2954. remote_path,
  2955. printer_model=printer.model,
  2956. )
  2957. except Exception as e:
  2958. logger.debug("[FORCED-TIMELAPSE] FTP delete attempt failed for %s: %s", remote_path, e)
  2959. continue
  2960. if ok:
  2961. logger.info("[FORCED-TIMELAPSE] Deleted printer-side timelapse %s", remote_path)
  2962. return
  2963. logger.warning(
  2964. "[FORCED-TIMELAPSE] Could not delete printer-side timelapse %s for archive %s (file may already be gone)",
  2965. filename,
  2966. archive_id,
  2967. )
  2968. async def on_print_running_observed(printer_id: int, data: dict):
  2969. """Restart-recovery: capture a fresh timelapse baseline for a print that
  2970. started before Bambuddy came up.
  2971. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  2972. after Bambuddy startup (#1304 guard, prevents duplicate archive
  2973. creation). Without that path, ``_capture_timelapse_baseline_at_start``
  2974. never runs and ``_scan_for_timelapse_with_retries`` falls into its
  2975. "take baseline now" fallback at completion time — but by then the
  2976. printer has already uploaded the in-flight MP4, so the baseline
  2977. includes it and no diff ever matches (#1485 follow-up).
  2978. Fires once per session, in lieu of on_print_start when restart-recovery
  2979. kicks in. The printer doesn't upload the timelapse until after PRINT
  2980. COMPLETE, so a baseline captured any time during the print is still
  2981. pre-upload.
  2982. """
  2983. logger = logging.getLogger(__name__)
  2984. # Avoid double-capture: on_print_start may have run earlier in this
  2985. # Bambuddy process if the print started AFTER startup and we crashed
  2986. # later in the same session. (Realistically this can't happen — the
  2987. # MQTT client object would have been recreated — but the cheap guard
  2988. # is correct regardless.)
  2989. if printer_id in _timelapse_baselines:
  2990. logger.debug(
  2991. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  2992. printer_id,
  2993. )
  2994. return
  2995. async with async_session() as db:
  2996. from backend.app.models.printer import Printer
  2997. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2998. printer = result.scalar_one_or_none()
  2999. if not printer:
  3000. logger.warning(
  3001. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  3002. printer_id,
  3003. )
  3004. return
  3005. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  3006. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  3007. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  3008. against the printer's current MQTT state.
  3009. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  3010. COMPLETE events, typically a print finishing during an MQTT disconnect
  3011. window followed by a smart-plug power cycle):
  3012. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  3013. provably not running anymore — only branch that should fire under
  3014. normal disconnect-then-reconnect timing.
  3015. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  3016. firmware mints a fresh ``subtask_id`` for each print, including the
  3017. ghost replay it runs after a power cycle from a leftover SD file —
  3018. so a mismatch unambiguously means the in-DB archive is no longer
  3019. the print on the printer.
  3020. 3. Printer is running but ``subtask_name`` is empty. The printer
  3021. doesn't know what it's running; the archive's reference to it is
  3022. already broken.
  3023. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  3024. with matching subtask_id+subtask_name is left alone. The cost of a false
  3025. positive is a duplicate archive on the next real PRINT COMPLETE — the
  3026. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  3027. clears on synthesis, so the real completion creates a fresh row instead
  3028. of overwriting the synthesised one (#1679). The cost of a false negative
  3029. is the ghost-print loop in #1542.
  3030. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  3031. MQTT has connected but the first ``push_status`` response hasn't been
  3032. applied yet — ``PrinterState`` is sitting on its construction defaults.
  3033. The reconcile caller in ``on_printer_status_change`` is already gated
  3034. on a real ``state.state``, so in normal operation this branch is
  3035. unreachable; it's kept as belt-and-braces for future callers and for
  3036. the narrow window where a partial state update could arrive
  3037. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  3038. ``not stale`` on degenerate input is strictly conservative: a real
  3039. stale archive will still be caught by the next push_status arriving
  3040. with terminal state.
  3041. """
  3042. current_state = (state.state or "").upper()
  3043. if current_state in ("", "UNKNOWN"):
  3044. # No real push_status yet — PrinterState defaults are not evidence.
  3045. return False, ""
  3046. if current_state in ("IDLE", "FINISH", "FAILED"):
  3047. return True, f"printer state {current_state}"
  3048. # Below here the printer is in a running / pre-running state (RUNNING /
  3049. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  3050. current_subtask_id = (state.subtask_id or "").strip()
  3051. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  3052. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  3053. current_subtask_name = (state.subtask_name or "").strip()
  3054. if not current_subtask_name:
  3055. return True, "printer subtask_name empty"
  3056. return False, ""
  3057. async def reconcile_stale_active_prints(printer_id: int) -> int:
  3058. """Synthesise ``on_print_complete`` for archives whose print can't be
  3059. running on the printer anymore.
  3060. Called once per MQTT (re)connection (from on_printer_status_change when
  3061. the connected edge flips False → True) and at Bambuddy startup (from
  3062. the FastAPI lifespan). Without this, a print that completes during a
  3063. disconnect window — followed by a smart-plug-driven power cycle — leaves
  3064. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  3065. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  3066. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  3067. power cycle until the operator notices (#1542 follow-up). Reconciliation
  3068. closes the loop by faking the missed PRINT COMPLETE — the existing
  3069. cleanup chain handles SD-file deletion, status updates, usage tracking,
  3070. and notifications.
  3071. Synthesised ``status="aborted"`` is the conservative label: we have no
  3072. proof the print finished successfully (and no progress evidence to
  3073. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  3074. fires later, overwrites the status with the correct value.
  3075. Returns the number of archives reconciled.
  3076. """
  3077. state = printer_manager.get_status(printer_id)
  3078. if not state:
  3079. return 0
  3080. # Don't reconcile while disconnected — we'd be making a decision against
  3081. # stale cached state. The connected → reconcile edge handles this.
  3082. if not state.connected:
  3083. return 0
  3084. from backend.app.models.archive import PrintArchive
  3085. reconciled = 0
  3086. async with async_session() as db:
  3087. result = await db.execute(
  3088. select(PrintArchive).where(
  3089. PrintArchive.printer_id == printer_id,
  3090. PrintArchive.status == "printing",
  3091. )
  3092. )
  3093. active = list(result.scalars().all())
  3094. if not active:
  3095. return 0
  3096. logger = logging.getLogger(__name__)
  3097. for archive in active:
  3098. is_stale, reason = _is_active_archive_stale(archive, state)
  3099. if not is_stale:
  3100. continue
  3101. logger.info(
  3102. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  3103. printer_id,
  3104. archive.id,
  3105. archive.filename,
  3106. reason,
  3107. )
  3108. # Synthesised payload: minimal fields the on_print_complete chain
  3109. # needs. `_reconciled` marker lets downstream code distinguish this
  3110. # from a real MQTT-driven completion if it ever needs to (e.g. for
  3111. # metrics / debug logging). raw_data is the live printer state so
  3112. # the usage tracker can compare end-of-print remain% against the
  3113. # captured start values.
  3114. try:
  3115. await on_print_complete(
  3116. printer_id,
  3117. {
  3118. "status": "aborted",
  3119. "filename": archive.filename,
  3120. "subtask_name": archive.print_name or "",
  3121. "subtask_id": archive.subtask_id or "",
  3122. "raw_data": state.raw_data or {},
  3123. "_reconciled": True,
  3124. },
  3125. )
  3126. reconciled += 1
  3127. except Exception as e:
  3128. # Catch-all: a reconciliation failure must not block the
  3129. # printer's normal status flow. The archive stays in
  3130. # ``status="printing"`` and the next reconnect retries.
  3131. logger.warning(
  3132. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  3133. archive.id,
  3134. e,
  3135. )
  3136. return reconciled
  3137. async def on_print_complete(printer_id: int, data: dict):
  3138. """Handle print completion - update the archive status."""
  3139. import time
  3140. logger = logging.getLogger(__name__)
  3141. start_time = time.time()
  3142. def log_timing(section: str):
  3143. elapsed = time.time() - start_time
  3144. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  3145. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  3146. # Drop the 3MF download cache for this printer (#972). The print is over,
  3147. # nothing else legitimately needs the bytes; keeping them would only risk
  3148. # handing a stale file to the next print if it reuses the same name.
  3149. clear_3mf_cache(printer_id)
  3150. try:
  3151. ws_data = {
  3152. "status": data.get("status"),
  3153. "filename": data.get("filename"),
  3154. "subtask_name": data.get("subtask_name"),
  3155. "timelapse_was_active": data.get("timelapse_was_active"),
  3156. }
  3157. await ws_manager.send_print_complete(printer_id, ws_data)
  3158. log_timing("WebSocket send_print_complete")
  3159. except Exception as e:
  3160. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  3161. # Capture user info before clearing (needed for print log entry)
  3162. _print_user_info = printer_manager.get_current_print_user(printer_id)
  3163. # Clear current print user tracking (Issue #206)
  3164. printer_manager.clear_current_print_user(printer_id)
  3165. # If the user explicitly stopped this print from the queue UI the printer will
  3166. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  3167. # correct "print stopped" notification/email is sent instead of a failure alert.
  3168. _raw_status = data.get("status", "completed")
  3169. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  3170. logger.info(
  3171. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  3172. _raw_status,
  3173. printer_id,
  3174. )
  3175. data = {**data, "status": "cancelled"}
  3176. _user_stopped_printers.discard(printer_id)
  3177. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  3178. # may have left material on the bed: a user can cancel ten hours into a
  3179. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  3180. # touchscreen-stop reports `aborted` rather than `cancelled` because
  3181. # `_user_stopped_printers` is only populated when the user stops via the
  3182. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  3183. # which auto-dispatched the next queued print onto a fouled bed two seconds
  3184. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  3185. # Auto Off power cycles and Bambuddy restarts.
  3186. _final_status = data.get("status", "completed")
  3187. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  3188. printer_manager.set_awaiting_plate_clear(printer_id, True)
  3189. # MQTT relay - publish print complete
  3190. try:
  3191. printer_info = printer_manager.get_printer(printer_id)
  3192. if printer_info:
  3193. await mqtt_relay.on_print_complete(
  3194. printer_id,
  3195. printer_info.name,
  3196. printer_info.serial_number,
  3197. data.get("filename", ""),
  3198. data.get("subtask_name", ""),
  3199. data.get("status", "completed"),
  3200. )
  3201. except Exception:
  3202. pass # Don't fail print complete callback if MQTT fails
  3203. filename = data.get("filename", "")
  3204. subtask_name = data.get("subtask_name", "")
  3205. if not filename and not subtask_name:
  3206. logger.warning("Print complete without filename or subtask_name")
  3207. return
  3208. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  3209. # Build list of possible keys to try (matching how they were registered in on_print_start)
  3210. possible_keys = []
  3211. # Try subtask_name variations first (most reliable for matching)
  3212. if subtask_name:
  3213. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  3214. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  3215. possible_keys.append((printer_id, subtask_name))
  3216. # Try filename variations
  3217. if filename:
  3218. # Extract just the filename if it's a path
  3219. fname = filename.split("/")[-1] if "/" in filename else filename
  3220. if fname.endswith(".3mf"):
  3221. possible_keys.append((printer_id, fname))
  3222. elif fname.endswith(".gcode"):
  3223. base_name = fname.rsplit(".", 1)[0]
  3224. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  3225. possible_keys.append((printer_id, f"{base_name}.3mf"))
  3226. possible_keys.append((printer_id, fname))
  3227. else:
  3228. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  3229. possible_keys.append((printer_id, f"{fname}.3mf"))
  3230. possible_keys.append((printer_id, fname))
  3231. # Also try full path versions
  3232. if filename.endswith(".3mf"):
  3233. possible_keys.append((printer_id, filename))
  3234. elif filename.endswith(".gcode"):
  3235. base_name = filename.rsplit(".", 1)[0]
  3236. possible_keys.append((printer_id, f"{base_name}.3mf"))
  3237. possible_keys.append((printer_id, filename))
  3238. else:
  3239. possible_keys.append((printer_id, f"{filename}.3mf"))
  3240. possible_keys.append((printer_id, filename))
  3241. # Find the archive for this print
  3242. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  3243. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  3244. archive_id = None
  3245. for key in possible_keys:
  3246. archive_id = _active_prints.pop(key, None)
  3247. if archive_id:
  3248. logger.info("Found archive %s with key %s", archive_id, key)
  3249. # Also clean up any other keys pointing to this archive
  3250. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  3251. for k in keys_to_remove:
  3252. _active_prints.pop(k, None)
  3253. break
  3254. if not archive_id:
  3255. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  3256. async with async_session() as db:
  3257. from backend.app.models.archive import PrintArchive
  3258. # Try matching by subtask_name (stored as print_name) first
  3259. if subtask_name:
  3260. result = await db.execute(
  3261. select(PrintArchive)
  3262. .where(PrintArchive.printer_id == printer_id)
  3263. .where(PrintArchive.status == "printing")
  3264. .where(
  3265. or_(
  3266. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  3267. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  3268. )
  3269. )
  3270. .order_by(PrintArchive.created_at.desc())
  3271. .limit(1)
  3272. )
  3273. archive = result.scalar_one_or_none()
  3274. if archive:
  3275. archive_id = archive.id
  3276. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  3277. # Also try by filename
  3278. if not archive_id and filename:
  3279. result = await db.execute(
  3280. select(PrintArchive)
  3281. .where(PrintArchive.printer_id == printer_id)
  3282. .where(PrintArchive.filename == filename)
  3283. .where(PrintArchive.status == "printing")
  3284. .order_by(PrintArchive.created_at.desc())
  3285. .limit(1)
  3286. )
  3287. archive = result.scalar_one_or_none()
  3288. if archive:
  3289. archive_id = archive.id
  3290. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  3291. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  3292. # auto-start files found in root on power cycle, causing ghost prints.
  3293. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  3294. try:
  3295. if subtask_name:
  3296. archive_filename: str | None = None
  3297. async with async_session() as db:
  3298. from backend.app.models.archive import PrintArchive
  3299. from backend.app.models.printer import Printer
  3300. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3301. printer = result.scalar_one_or_none()
  3302. if archive_id:
  3303. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  3304. archive_filename = archive_row.scalar_one_or_none()
  3305. if printer:
  3306. from backend.app.services.bambu_ftp import delete_file_async
  3307. from backend.app.utils.filename import derive_remote_filename
  3308. # Primary candidate: the exact path the dispatcher uploaded to
  3309. # (derived from archive.filename via the same rule as upload).
  3310. # Without it, a library row that ended up with a doubled
  3311. # .gcode.3mf (#1542) leaves the real file behind because the
  3312. # subtask_name + ext fallbacks below don't match what's on the
  3313. # SD card. Fallbacks remain for archive-less prints (subtask
  3314. # never resolved to an archive) and for older naming variants.
  3315. candidate_paths: list[str] = []
  3316. if archive_filename:
  3317. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  3318. for ext in (".3mf", ".gcode"):
  3319. fallback = f"/{subtask_name}{ext}"
  3320. if fallback not in candidate_paths:
  3321. candidate_paths.append(fallback)
  3322. for remote_path in candidate_paths:
  3323. # Retry up to 3 times — the printer may still lock the filesystem briefly after a print ends
  3324. for attempt in range(1, 4):
  3325. try:
  3326. delete_result = await delete_file_async(
  3327. printer.ip_address,
  3328. printer.access_code,
  3329. remote_path,
  3330. printer_model=printer.model,
  3331. )
  3332. if delete_result:
  3333. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  3334. break
  3335. except Exception as e:
  3336. delete_result = False
  3337. logger.warning(
  3338. "SD card cleanup attempt %d/3 raised for %s: %s",
  3339. attempt,
  3340. remote_path,
  3341. e,
  3342. )
  3343. if not delete_result and attempt < 3:
  3344. await asyncio.sleep(2)
  3345. elif not delete_result:
  3346. logger.warning(
  3347. "SD card cleanup failed after 3 attempts for %s (file may linger on SD card)",
  3348. remote_path,
  3349. )
  3350. except Exception as e:
  3351. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  3352. log_timing("SD card cleanup")
  3353. # Update queue item status early — must run before the archive_id early-return
  3354. # so queue items don't get stuck in "printing" when archive lookup fails.
  3355. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  3356. queue_item_id = None
  3357. queue_status = None
  3358. queue_auto_off = False
  3359. try:
  3360. from backend.app.core.database import run_with_retry
  3361. from backend.app.models.print_queue import PrintQueueItem
  3362. async def _update_queue_status(db):
  3363. nonlocal queue_item_id, queue_status, queue_auto_off
  3364. result = await db.execute(
  3365. select(PrintQueueItem)
  3366. .where(PrintQueueItem.printer_id == printer_id)
  3367. .where(PrintQueueItem.status == "printing")
  3368. )
  3369. printing_items = list(result.scalars().all())
  3370. if len(printing_items) > 1:
  3371. logger.warning(
  3372. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  3373. printer_id,
  3374. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  3375. )
  3376. item = printing_items[0] if printing_items else None
  3377. if item:
  3378. queue_status = data.get("status", "completed")
  3379. # MQTT sends "aborted" for cancelled prints; normalise to
  3380. # "cancelled" so it matches the queue schema Literal.
  3381. if queue_status == "aborted":
  3382. queue_status = "cancelled"
  3383. item.status = queue_status
  3384. item.completed_at = datetime.now(timezone.utc)
  3385. if queue_status == "failed" and not item.error_message:
  3386. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  3387. # Bump usage counters on the source library file so admins can
  3388. # sort by "last printed" and (eventually) auto-purge stale
  3389. # files — #1008.
  3390. await _bump_library_file_usage_if_completed(db, item, queue_status)
  3391. await db.commit()
  3392. queue_item_id = item.id
  3393. queue_auto_off = item.auto_off_after
  3394. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  3395. await run_with_retry(_update_queue_status, label="queue status update")
  3396. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  3397. # their own sessions and have their own error handling — no retry needed.
  3398. if queue_item_id is not None:
  3399. # MQTT relay - publish queue job completed
  3400. try:
  3401. printer_info = printer_manager.get_printer(printer_id)
  3402. await mqtt_relay.on_queue_job_completed(
  3403. job_id=queue_item_id,
  3404. filename=filename or subtask_name,
  3405. printer_id=printer_id,
  3406. printer_name=printer_info.name if printer_info else "Unknown",
  3407. status=queue_status,
  3408. )
  3409. except Exception:
  3410. pass # Don't fail if MQTT fails
  3411. # Check if queue is now empty and send notification
  3412. try:
  3413. from sqlalchemy import func as sa_func
  3414. async with async_session() as db:
  3415. count_result = await db.execute(
  3416. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  3417. )
  3418. pending_count = count_result.scalar() or 0
  3419. if pending_count == 0:
  3420. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  3421. completed_result = await db.execute(
  3422. select(sa_func.count(PrintQueueItem.id)).where(
  3423. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  3424. PrintQueueItem.completed_at >= today_start,
  3425. )
  3426. )
  3427. completed_count = completed_result.scalar() or 1
  3428. await notification_service.on_queue_completed(
  3429. completed_count=completed_count,
  3430. db=db,
  3431. )
  3432. except Exception:
  3433. pass # Don't fail if notification fails
  3434. # Handle auto_off_after - power off printer if requested (after cooldown)
  3435. if queue_auto_off:
  3436. async with async_session() as db:
  3437. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  3438. plugs = list(result.scalars().all())
  3439. enabled_plugs = [p for p in plugs if p.enabled]
  3440. if enabled_plugs:
  3441. logger.info("Auto-off requested for printer %s, waiting for cooldown...", printer_id)
  3442. async def cooldown_and_poweroff(pid: int, plug_ids: list[int]):
  3443. # Wait for nozzle to cool down
  3444. await printer_manager.wait_for_cooldown(pid, target_temp=50.0, timeout=600)
  3445. # Re-fetch plugs in new session and turn off each one
  3446. async with async_session() as new_db:
  3447. for plug_id in plug_ids:
  3448. try:
  3449. result = await new_db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  3450. p = result.scalar_one_or_none()
  3451. if p and p.enabled:
  3452. service = await smart_plug_manager.get_service_for_plug(p, new_db)
  3453. success = await service.turn_off(p)
  3454. if success:
  3455. logger.info("Powered off printer %s via smart plug '%s'", pid, p.name)
  3456. else:
  3457. logger.warning("Failed to power off plug '%s' for printer %s", p.name, pid)
  3458. except Exception as e:
  3459. logger.warning("Failed to power off plug %s for printer %s: %s", plug_id, pid, e)
  3460. spawn_background_task(
  3461. cooldown_and_poweroff(printer_id, [p.id for p in enabled_plugs]),
  3462. name=f"cooldown-poweroff-{printer_id}",
  3463. )
  3464. except Exception as e:
  3465. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  3466. log_timing("Queue item update")
  3467. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  3468. # Must run before archive_id early-return so it fires for all prints (including
  3469. # prints started from BambuStudio/touchscreen that have no archive).
  3470. if data.get("status") == "completed":
  3471. try:
  3472. from backend.app.api.routes.settings import get_setting
  3473. async with async_session() as db:
  3474. threshold_str = await get_setting(db, "bed_cooled_threshold")
  3475. threshold = float(threshold_str) if threshold_str else 35.0
  3476. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  3477. async with async_session() as db:
  3478. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  3479. if providers:
  3480. _bed_cool_waiters[printer_id] = {
  3481. "threshold": threshold,
  3482. "filename": filename or subtask_name or "",
  3483. "registered_at": time.time(),
  3484. }
  3485. logger.info(
  3486. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  3487. printer_id,
  3488. threshold,
  3489. )
  3490. else:
  3491. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  3492. except Exception as e:
  3493. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  3494. # --- Track filament consumption (must run before archive_id early-return so usage
  3495. # is recorded even when auto-archive is disabled) ---
  3496. usage_results: list[dict] = []
  3497. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  3498. stored_ams_mapping = data.get("ams_mapping")
  3499. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  3500. if not stored_ams_mapping and archive_id:
  3501. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  3502. # Always drain the plate_id register on completion — the session already
  3503. # consumed it at print-start injection; leaving it would leak into the next
  3504. # print on the same archive_id (rare but possible with reprints) (#1697).
  3505. if archive_id:
  3506. _print_plate_ids.pop(archive_id, None)
  3507. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  3508. try:
  3509. async with async_session() as db:
  3510. from backend.app.api.routes.settings import get_setting
  3511. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3512. if not _spoolman_on or _spoolman_on.lower() != "true":
  3513. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  3514. async with async_session() as db:
  3515. usage_results = await usage_on_print_complete(
  3516. printer_id,
  3517. data,
  3518. printer_manager,
  3519. db,
  3520. archive_id=archive_id,
  3521. ams_mapping=stored_ams_mapping,
  3522. )
  3523. if usage_results:
  3524. await ws_manager.broadcast(
  3525. {
  3526. "type": "spool_usage_logged",
  3527. "printer_id": printer_id,
  3528. "usage": usage_results,
  3529. }
  3530. )
  3531. log_timing("Usage tracker")
  3532. except Exception as e:
  3533. logger.warning("Usage tracker on_print_complete failed: %s", e)
  3534. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  3535. if archive_id:
  3536. if data.get("status") == "completed":
  3537. try:
  3538. await _report_spoolman_usage(printer_id, archive_id)
  3539. log_timing("Spoolman usage report")
  3540. except Exception as e:
  3541. logger.warning("Spoolman usage reporting failed: %s", e)
  3542. else:
  3543. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  3544. try:
  3545. async with async_session() as db:
  3546. await _cleanup_spoolman_tracking(
  3547. printer_id,
  3548. archive_id,
  3549. db,
  3550. last_layer_num=data.get("last_layer_num"),
  3551. last_progress=data.get("last_progress"),
  3552. )
  3553. except Exception as e:
  3554. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  3555. log_timing("Filament usage tracking")
  3556. if not archive_id:
  3557. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  3558. # Still send print-complete/failed/stopped notifications even without an archive.
  3559. # Try to enrich with queue/library-file data so user-specific emails work too.
  3560. async def _notify_no_archive():
  3561. try:
  3562. async with async_session() as db:
  3563. from backend.app.models.library import LibraryFile
  3564. from backend.app.models.print_queue import PrintQueueItem
  3565. from backend.app.models.printer import Printer
  3566. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3567. printer_obj = result.scalar_one_or_none()
  3568. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  3569. # Try to find the most-recent queue item for this printer so we can
  3570. # recover created_by_id and estimated print time.
  3571. # NOTE: By the time this task runs the queue item status has already
  3572. # been updated to a terminal state (completed/failed/cancelled), so
  3573. # we look for recently-completed items (within the last 5 minutes).
  3574. no_archive_data: dict | None = None
  3575. try:
  3576. cutoff = datetime.now(timezone.utc) - timedelta(minutes=5)
  3577. q_result = await db.execute(
  3578. select(PrintQueueItem)
  3579. .where(PrintQueueItem.printer_id == printer_id)
  3580. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled"]))
  3581. .where(PrintQueueItem.completed_at >= cutoff)
  3582. .order_by(PrintQueueItem.completed_at.desc())
  3583. .limit(1)
  3584. )
  3585. queue_item = q_result.scalar_one_or_none()
  3586. if queue_item:
  3587. no_archive_data = {"created_by_id": queue_item.created_by_id}
  3588. # Pull estimated time from library file when available
  3589. if queue_item.library_file_id:
  3590. lib_result = await db.execute(
  3591. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  3592. )
  3593. lib_file = lib_result.scalar_one_or_none()
  3594. if lib_file and lib_file.print_time_seconds:
  3595. no_archive_data["print_time_seconds"] = lib_file.print_time_seconds
  3596. except Exception as lookup_err:
  3597. logger.debug(
  3598. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  3599. )
  3600. # Enrich with usage tracker results (captured in enclosing scope)
  3601. if usage_results:
  3602. if no_archive_data is None:
  3603. no_archive_data = {}
  3604. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  3605. if total_from_usage > 0:
  3606. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  3607. no_archive_data["usage_results"] = usage_results
  3608. # Try MQTT remaining_time for print duration when no queue/library data
  3609. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  3610. mqtt_remaining = data.get("remaining_time")
  3611. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  3612. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  3613. ps = data.get("status", "completed")
  3614. logger.info(
  3615. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  3616. )
  3617. await notification_service.on_print_complete(
  3618. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  3619. )
  3620. # Send user-specific email if we have a created_by_id
  3621. if no_archive_data and no_archive_data.get("created_by_id"):
  3622. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  3623. await _dispatch_user_print_email(
  3624. ps,
  3625. no_archive_data["created_by_id"],
  3626. p_name,
  3627. raw_filename,
  3628. db,
  3629. )
  3630. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  3631. except Exception as e:
  3632. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  3633. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  3634. return
  3635. log_timing("Archive lookup")
  3636. # Update archive status
  3637. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  3638. try:
  3639. async with async_session() as db:
  3640. service = ArchiveService(db)
  3641. status = data.get("status", "completed")
  3642. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  3643. if hms_errors:
  3644. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  3645. failure_reason = derive_failure_reason(status, hms_errors)
  3646. if failure_reason:
  3647. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  3648. elif status == "failed" and hms_errors:
  3649. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  3650. await service.update_archive_status(
  3651. archive_id,
  3652. status=status,
  3653. completed_at=(
  3654. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  3655. ),
  3656. failure_reason=failure_reason,
  3657. )
  3658. logger.info(
  3659. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  3660. )
  3661. await ws_manager.send_archive_updated(
  3662. {
  3663. "id": archive_id,
  3664. "status": status,
  3665. }
  3666. )
  3667. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  3668. # MQTT relay - publish archive updated
  3669. try:
  3670. await mqtt_relay.on_archive_updated(
  3671. archive_id=archive_id,
  3672. print_name=filename or subtask_name,
  3673. status=status,
  3674. )
  3675. except Exception:
  3676. pass # Don't fail if MQTT fails
  3677. except Exception as e:
  3678. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  3679. # Continue with other operations even if archive update fails
  3680. log_timing("Archive status update")
  3681. # Write independent print log entry (separate table, never touches archives)
  3682. try:
  3683. async with async_session() as db:
  3684. from backend.app.models.archive import PrintArchive
  3685. from backend.app.services.print_log import write_log_entry
  3686. archive = await db.get(PrintArchive, archive_id)
  3687. if archive:
  3688. # Back-fill created_by_id on reprint (#730): reprint reuses the
  3689. # source archive row rather than creating a new one, so an
  3690. # archive that was auto-created from a printer-initiated
  3691. # print (created_by_id=NULL) would otherwise stay unattributed
  3692. # forever. When we have a print-session user AND the archive
  3693. # has no attribution yet, credit the current user. Never
  3694. # overwrite an existing attribution — the original uploader
  3695. # keeps ownership.
  3696. _print_user_id = _print_user_info.get("user_id") if _print_user_info else None
  3697. if archive.created_by_id is None and _print_user_id is not None:
  3698. archive.created_by_id = _print_user_id
  3699. p_info = printer_manager.get_printer(printer_id)
  3700. # Per-run actuals — written to PrintLogEntry so stats reflect
  3701. # what THIS print actually used, not the source archive's
  3702. # first-run values (#1378). Helper handles the partial-print
  3703. # math (failed / cancelled / stopped get scaled to progress
  3704. # or to tracked spool deltas).
  3705. _run_status = data.get("status", "completed")
  3706. _run_grams = _compute_run_filament_grams(
  3707. _run_status,
  3708. archive.filament_used_grams,
  3709. data.get("progress"),
  3710. usage_results,
  3711. )
  3712. # Per-run cost — prefer usage_results sum. For partial prints
  3713. # we deliberately skip the topup-to-estimate logic in
  3714. # usage_tracker (which assumes the print completed); the raw
  3715. # tracked-spool sum is closer to what THIS run actually cost.
  3716. _run_cost: float | None = None
  3717. if usage_results:
  3718. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  3719. if _run_cost is None and _run_status == "completed":
  3720. _run_cost = archive.cost
  3721. await write_log_entry(
  3722. db,
  3723. archive_id=archive.id,
  3724. status=_run_status,
  3725. print_name=archive.print_name,
  3726. printer_name=p_info.name if p_info else None,
  3727. printer_id=printer_id,
  3728. started_at=archive.started_at,
  3729. completed_at=archive.completed_at,
  3730. filament_type=archive.filament_type,
  3731. filament_color=archive.filament_color,
  3732. filament_used_grams=_run_grams,
  3733. cost=_run_cost,
  3734. failure_reason=archive.failure_reason,
  3735. thumbnail_path=archive.thumbnail_path,
  3736. created_by_id=archive.created_by_id,
  3737. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  3738. )
  3739. await db.commit()
  3740. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  3741. except Exception as e:
  3742. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  3743. log_timing("Print log entry")
  3744. # Run slow operations as background tasks to avoid blocking the event loop
  3745. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  3746. async def _background_energy_calculation():
  3747. """Calculate and save energy usage in background.
  3748. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  3749. backend restart no longer loses per-print energy data).
  3750. """
  3751. try:
  3752. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  3753. async with async_session() as db:
  3754. from backend.app.models.archive import PrintArchive
  3755. archive = await db.get(PrintArchive, archive_id)
  3756. if archive is None:
  3757. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  3758. return
  3759. starting_kwh = archive.energy_start_kwh
  3760. if starting_kwh is None:
  3761. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  3762. return
  3763. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  3764. plug = plug_result.scalar_one_or_none()
  3765. if plug is None:
  3766. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  3767. return
  3768. energy = await _get_plug_energy(plug, db)
  3769. logger.info("[ENERGY-BG] Energy response: %s", energy)
  3770. if not energy or energy.get("total") is None:
  3771. logger.warning("[ENERGY-BG] No 'total' in energy response")
  3772. return
  3773. energy_used = round(energy["total"] - starting_kwh, 4)
  3774. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  3775. if energy_used < 0:
  3776. logger.warning(
  3777. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  3778. archive_id,
  3779. starting_kwh,
  3780. energy["total"],
  3781. )
  3782. return
  3783. from backend.app.api.routes.settings import get_setting
  3784. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  3785. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  3786. energy_cost_value = round(energy_used * cost_per_kwh, 3)
  3787. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  3788. # reprint doesn't visually clobber the source archive's energy data
  3789. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  3790. from sqlalchemy import func
  3791. from backend.app.models.print_log import PrintLogEntry
  3792. existing_runs = await db.scalar(
  3793. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  3794. )
  3795. if (existing_runs or 0) <= 1:
  3796. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  3797. # we just wrote for THIS print. Either way it's the first run.
  3798. archive.energy_kwh = energy_used
  3799. archive.energy_cost = energy_cost_value
  3800. # Backfill the latest PrintLogEntry for this archive with energy
  3801. # (write_log_entry above ran before this background task completed,
  3802. # so energy fields are still NULL on that row).
  3803. latest_run = await db.execute(
  3804. select(PrintLogEntry)
  3805. .where(PrintLogEntry.archive_id == archive_id)
  3806. .order_by(PrintLogEntry.id.desc())
  3807. .limit(1)
  3808. )
  3809. run_row = latest_run.scalar_one_or_none()
  3810. if run_row is not None:
  3811. run_row.energy_kwh = energy_used
  3812. run_row.energy_cost = energy_cost_value
  3813. await db.commit()
  3814. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  3815. except Exception as e:
  3816. logger.warning("[ENERGY-BG] Failed: %s", e)
  3817. async def _background_finish_photo() -> str | None:
  3818. """Capture finish photo in background. Returns photo filename if captured."""
  3819. try:
  3820. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  3821. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3822. async with async_session() as db:
  3823. from backend.app.api.routes.settings import get_setting
  3824. capture_enabled = await get_setting(db, "capture_finish_photo")
  3825. if capture_enabled is None or capture_enabled.lower() == "true":
  3826. from backend.app.models.printer import Printer
  3827. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3828. printer = result.scalar_one_or_none()
  3829. if printer and archive_id:
  3830. from backend.app.models.archive import PrintArchive
  3831. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3832. archive = result.scalar_one_or_none()
  3833. if archive:
  3834. import uuid
  3835. from datetime import datetime
  3836. from pathlib import Path
  3837. if archive.file_path:
  3838. archive_dir = app_settings.base_dir / Path(archive.file_path).parent
  3839. else:
  3840. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  3841. archive_dir = app_settings.archive_dir / str(archive.id)
  3842. photo_filename = None
  3843. # Prefer the timelapse last-frame source when a timelapse was
  3844. # recording — it captures the moment after the toolhead parks
  3845. # but before the bed drops, which the live-camera grab below
  3846. # would miss (#1397). Skipped for external cameras (those have
  3847. # their own framing and don't see a Bambu timelapse).
  3848. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  3849. printer.external_camera_enabled and printer.external_camera_url
  3850. )
  3851. if prefer_timelapse_source:
  3852. photo_filename = await _capture_finish_photo_from_timelapse(
  3853. archive_id=archive_id,
  3854. archive_dir=archive_dir,
  3855. )
  3856. # Fallback chain: external camera → buffered live frame →
  3857. # fresh RTSP capture. Only runs if the timelapse path above
  3858. # didn't already produce a photo.
  3859. if not photo_filename:
  3860. if printer.external_camera_enabled and printer.external_camera_url:
  3861. logger.info("[PHOTO-BG] Using external camera")
  3862. from backend.app.services.external_camera import capture_frame
  3863. frame_data = await capture_frame(
  3864. printer.external_camera_url,
  3865. printer.external_camera_type or "mjpeg",
  3866. snapshot_url=printer.external_camera_snapshot_url,
  3867. )
  3868. if frame_data:
  3869. photos_dir = archive_dir / "photos"
  3870. photos_dir.mkdir(parents=True, exist_ok=True)
  3871. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  3872. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  3873. photo_path = photos_dir / photo_filename
  3874. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  3875. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  3876. else:
  3877. # Check if camera stream is active - use buffered frame to avoid freeze
  3878. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  3879. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3880. active_chamber_for_printer = [
  3881. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  3882. ]
  3883. buffered_frame = get_buffered_frame(printer_id)
  3884. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  3885. # Use frame from active stream
  3886. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  3887. photos_dir = archive_dir / "photos"
  3888. photos_dir.mkdir(parents=True, exist_ok=True)
  3889. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  3890. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  3891. photo_path = photos_dir / photo_filename
  3892. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  3893. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  3894. else:
  3895. # No active stream - capture new frame
  3896. from backend.app.services.camera import capture_finish_photo
  3897. photo_filename = await capture_finish_photo(
  3898. printer_id=printer_id,
  3899. ip_address=printer.ip_address,
  3900. access_code=printer.access_code,
  3901. model=printer.model,
  3902. archive_dir=archive_dir,
  3903. )
  3904. if photo_filename:
  3905. photos = archive.photos or []
  3906. photos.append(photo_filename)
  3907. archive.photos = photos
  3908. await db.commit()
  3909. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  3910. # When Bambuddy forced timelapse on for this print, delete
  3911. # the timelapse afterward (#1397). The user didn't ask for
  3912. # a video to keep — only the finish photo. Runs even when
  3913. # photo extraction failed, so we don't leave debris.
  3914. if archive.bambuddy_forced_timelapse:
  3915. await _cleanup_forced_timelapse(
  3916. archive_id=archive_id,
  3917. printer_id=printer_id,
  3918. )
  3919. if photo_filename:
  3920. return photo_filename
  3921. return None
  3922. except Exception as e:
  3923. logger.warning("[PHOTO-BG] Failed: %s", e)
  3924. return None
  3925. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  3926. # Photo capture task - result will be used by notifications
  3927. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  3928. log_timing("Background tasks scheduled (energy, photo)")
  3929. # Also run smart plug, notifications, and maintenance as background tasks
  3930. print_status = data.get("status", "completed")
  3931. async def _background_smart_plug():
  3932. """Handle smart plug automation in background."""
  3933. try:
  3934. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  3935. async with async_session() as db:
  3936. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  3937. logger.info("[AUTO-OFF-BG] Completed")
  3938. except Exception as e:
  3939. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  3940. async def _background_notifications(finish_photo_filename: str | None = None):
  3941. """Send print complete notifications in background."""
  3942. try:
  3943. logger.info(
  3944. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  3945. )
  3946. async with async_session() as db:
  3947. from backend.app.models.archive import PrintArchive
  3948. from backend.app.models.printer import Printer
  3949. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3950. printer = result.scalar_one_or_none()
  3951. printer_name = printer.name if printer else f"Printer {printer_id}"
  3952. archive_data = None
  3953. if archive_id:
  3954. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3955. archive = archive_result.scalar_one_or_none()
  3956. if archive:
  3957. # Actual elapsed time from started_at/completed_at when both are
  3958. # populated (every terminal status sets completed_at after #1198).
  3959. # Falls back to None so the notification path can decide whether to
  3960. # render the slicer estimate as a last resort.
  3961. actual_time_seconds = None
  3962. if archive.started_at and archive.completed_at:
  3963. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  3964. if elapsed > 0:
  3965. actual_time_seconds = int(elapsed)
  3966. archive_data = {
  3967. "print_time_seconds": archive.print_time_seconds,
  3968. "actual_time_seconds": actual_time_seconds,
  3969. "actual_filament_grams": archive.filament_used_grams,
  3970. "failure_reason": archive.failure_reason,
  3971. "created_by_id": archive.created_by_id,
  3972. }
  3973. # Scale filament usage for partial prints
  3974. if print_status != "completed" and archive.filament_used_grams:
  3975. progress = data.get("progress") or 0
  3976. scale = max(0.0, min(progress / 100.0, 1.0))
  3977. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  3978. archive_data["progress"] = progress
  3979. # Pass per-slot data from archive.extra_data
  3980. if archive.extra_data and archive.extra_data.get("filament_slots"):
  3981. slots = archive.extra_data["filament_slots"]
  3982. if print_status != "completed":
  3983. scale = max(0.0, min((data.get("progress") or 0) / 100.0, 1.0))
  3984. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  3985. archive_data["filament_slots"] = slots
  3986. # Enrich filament_grams from usage_results when archive has no 3MF data
  3987. if not archive_data.get("actual_filament_grams") and usage_results:
  3988. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  3989. if total_from_usage > 0:
  3990. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  3991. # Pass usage tracker results for AMS slot info in notifications
  3992. if usage_results:
  3993. archive_data["usage_results"] = usage_results
  3994. # Add finish photo URL and image bytes if available
  3995. if finish_photo_filename:
  3996. from backend.app.api.routes.settings import get_setting
  3997. external_url = await get_setting(db, "external_url")
  3998. if external_url:
  3999. external_url = external_url.rstrip("/")
  4000. archive_data["finish_photo_url"] = (
  4001. f"{external_url}/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  4002. )
  4003. else:
  4004. # Fallback to relative URL (won't work for external services)
  4005. archive_data["finish_photo_url"] = (
  4006. f"/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  4007. )
  4008. # Read finish photo bytes for image attachment (e.g. Pushover)
  4009. try:
  4010. from pathlib import Path
  4011. photo_path = (
  4012. app_settings.base_dir
  4013. / Path(archive.file_path).parent
  4014. / "photos"
  4015. / finish_photo_filename
  4016. )
  4017. if photo_path.exists():
  4018. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  4019. if len(photo_bytes) <= 2_500_000:
  4020. archive_data["image_data"] = photo_bytes
  4021. logger.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  4022. else:
  4023. logger.warning(
  4024. f"[NOTIFY-BG] Finish photo too large for attachment: "
  4025. f"{len(photo_bytes)} bytes"
  4026. )
  4027. except Exception as e:
  4028. logger.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  4029. await notification_service.on_print_complete(
  4030. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  4031. )
  4032. # Send user-specific email notification
  4033. if archive_data:
  4034. created_by_id = archive_data.get("created_by_id")
  4035. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  4036. await _dispatch_user_print_email(
  4037. print_status,
  4038. created_by_id,
  4039. printer_name,
  4040. raw_filename,
  4041. db,
  4042. )
  4043. logger.info("[NOTIFY-BG] Completed")
  4044. except Exception as e:
  4045. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  4046. async def _background_maintenance_check():
  4047. """Check for maintenance due in background."""
  4048. if print_status != "completed":
  4049. return
  4050. try:
  4051. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  4052. async with async_session() as db:
  4053. from backend.app.models.printer import Printer
  4054. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4055. printer = result.scalar_one_or_none()
  4056. printer_name = printer.name if printer else f"Printer {printer_id}"
  4057. await ensure_default_types(db)
  4058. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  4059. items_needing_attention = [
  4060. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  4061. for item in overview.maintenance_items
  4062. if item.enabled and (item.is_due or item.is_warning)
  4063. ]
  4064. if items_needing_attention:
  4065. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  4066. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  4067. # MQTT relay - publish maintenance alerts
  4068. for item in items_needing_attention:
  4069. try:
  4070. await mqtt_relay.on_maintenance_alert(
  4071. printer_id=printer_id,
  4072. printer_name=printer_name,
  4073. maintenance_type=item["name"],
  4074. current_value=0, # Not easily available here
  4075. threshold=0, # Not easily available here
  4076. )
  4077. except Exception:
  4078. pass # Don't fail if MQTT fails
  4079. else:
  4080. logger.info("[MAINT-BG] Completed (no items need attention)")
  4081. except Exception as e:
  4082. logger.warning("[MAINT-BG] Failed: %s", e)
  4083. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  4084. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  4085. # Notification task waits for photo capture to complete first (with timeout).
  4086. # When a timelapse was recording, photo sourcing polls the per-print
  4087. # timelapse for up to 60s (#1397) — extend the budget so the notification
  4088. # carries the correct bed-up photo instead of falling through to the
  4089. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  4090. photo_wait_timeout = 75 if data.get("timelapse_was_active") else 45
  4091. async def _photo_then_notify():
  4092. """Wait for photo capture, then send notification with photo URL."""
  4093. finish_photo = None
  4094. try:
  4095. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  4096. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  4097. except TimeoutError:
  4098. logger.warning(
  4099. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  4100. photo_wait_timeout,
  4101. )
  4102. except Exception as e:
  4103. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  4104. try:
  4105. await _background_notifications(finish_photo)
  4106. except Exception as e:
  4107. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  4108. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  4109. # Stitch external camera layer timelapse if session was active
  4110. print_status = data.get("status", "completed")
  4111. async def _background_layer_timelapse():
  4112. """Stitch layer timelapse and attach to archive."""
  4113. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  4114. try:
  4115. if print_status == "completed":
  4116. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  4117. timelapse_path = await tl_complete(printer_id)
  4118. if timelapse_path and archive_id:
  4119. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  4120. async with async_session() as db:
  4121. service = ArchiveService(db)
  4122. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  4123. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  4124. # Clean up the temp file
  4125. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  4126. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  4127. elif timelapse_path:
  4128. # Timelapse created but no archive - just clean up
  4129. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  4130. else:
  4131. # Print failed or cancelled - cancel timelapse session
  4132. cancel_session(printer_id)
  4133. logger.info(
  4134. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  4135. )
  4136. except Exception as e:
  4137. logger.warning("[LAYER-TL] Failed: %s", e)
  4138. # Try to cancel session on error
  4139. try:
  4140. cancel_session(printer_id)
  4141. except Exception:
  4142. pass # Best-effort timelapse session cancellation on error
  4143. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  4144. log_timing("All background tasks scheduled")
  4145. # Auto-scan for timelapse if recording was active during the print
  4146. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  4147. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  4148. # Schedule timelapse scan as background task with retries
  4149. # The printer needs time to encode the video after print completion
  4150. baseline = _timelapse_baselines.pop(printer_id, None)
  4151. spawn_background_task(
  4152. _scan_for_timelapse_with_retries(archive_id, baseline),
  4153. name=f"scan-timelapse-{archive_id}",
  4154. )
  4155. log_timing("Timelapse scan scheduled")
  4156. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  4157. # AMS sensor history recording
  4158. _ams_history_task: asyncio.Task | None = None
  4159. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  4160. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  4161. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  4162. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  4163. _ams_alarm_cooldown: dict[str, datetime] = {}
  4164. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  4165. def _ams_has_filament(ams_data: dict) -> bool:
  4166. """True if this AMS unit has at least one tray slot holding filament.
  4167. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  4168. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  4169. still report sensor readings, but those readings are ambient and not
  4170. actionable: no filament to dry, no humidity to push down. #1619 — gate
  4171. humidity/temperature alarms on this check so empty units don't generate
  4172. hourly noise. Sensor history still records regardless so the UI charts
  4173. stay continuous.
  4174. Fallback path inspects the `tray` array's `tray_type` fields for setups
  4175. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  4176. """
  4177. bits = ams_data.get("tray_exist_bits")
  4178. if isinstance(bits, str) and bits.strip():
  4179. try:
  4180. return int(bits, 16) > 0
  4181. except ValueError:
  4182. pass
  4183. trays = ams_data.get("tray")
  4184. if isinstance(trays, list):
  4185. return any(
  4186. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  4187. )
  4188. return False
  4189. async def record_ams_history():
  4190. """Background task to record AMS humidity and temperature data."""
  4191. logger = logging.getLogger(__name__)
  4192. # Wait a short time for MQTT connections to establish on startup
  4193. await asyncio.sleep(10)
  4194. while True:
  4195. try:
  4196. from backend.app.models.ams_history import AMSSensorHistory
  4197. from backend.app.models.printer import Printer
  4198. from backend.app.models.settings import Settings
  4199. async with async_session() as db:
  4200. # Get all active printers
  4201. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  4202. printers = result.scalars().all()
  4203. # Get alarm thresholds from settings
  4204. humidity_threshold = 60.0 # Default: fair threshold
  4205. temp_threshold = 35.0 # Default: fair threshold
  4206. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  4207. setting = result.scalar_one_or_none()
  4208. if setting:
  4209. try:
  4210. humidity_threshold = float(setting.value)
  4211. except (ValueError, TypeError):
  4212. pass # Keep default threshold if stored value is invalid
  4213. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  4214. setting = result.scalar_one_or_none()
  4215. if setting:
  4216. try:
  4217. temp_threshold = float(setting.value)
  4218. except (ValueError, TypeError):
  4219. pass # Keep default threshold if stored value is invalid
  4220. recorded_count = 0
  4221. for printer in printers:
  4222. # Get current state from printer manager
  4223. state = printer_manager.get_status(printer.id)
  4224. if not state or not state.connected or not state.raw_data:
  4225. continue # Skip disconnected printers - don't use stale data
  4226. raw_data = state.raw_data
  4227. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  4228. continue
  4229. # Record data for each AMS unit
  4230. for ams_data in raw_data["ams"]:
  4231. ams_id = int(ams_data.get("id", 0))
  4232. # Get humidity (prefer humidity_raw)
  4233. humidity_raw = ams_data.get("humidity_raw")
  4234. humidity_idx = ams_data.get("humidity")
  4235. humidity = None
  4236. if humidity_raw is not None:
  4237. try:
  4238. humidity = float(humidity_raw)
  4239. except (ValueError, TypeError):
  4240. pass # Skip unparseable humidity; will try fallback
  4241. if humidity is None and humidity_idx is not None:
  4242. try:
  4243. humidity = float(humidity_idx)
  4244. except (ValueError, TypeError):
  4245. pass # Skip unparseable humidity index value
  4246. # Get temperature
  4247. temperature = None
  4248. temp_str = ams_data.get("temp")
  4249. if temp_str is not None:
  4250. try:
  4251. temperature = float(temp_str)
  4252. except (ValueError, TypeError):
  4253. pass # Skip unparseable temperature value
  4254. # Skip if no data
  4255. if humidity is None and temperature is None:
  4256. continue
  4257. # Record the data point
  4258. history = AMSSensorHistory(
  4259. printer_id=printer.id,
  4260. ams_id=ams_id,
  4261. humidity=humidity,
  4262. humidity_raw=float(humidity_raw) if humidity_raw else None,
  4263. temperature=temperature,
  4264. )
  4265. db.add(history)
  4266. recorded_count += 1
  4267. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  4268. is_ams_ht = ams_id >= 128
  4269. if is_ams_ht:
  4270. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  4271. else:
  4272. ams_label = f"AMS-{chr(65 + ams_id)}"
  4273. # Skip alarm dispatch for empty AMS units — humidity /
  4274. # temperature readings are ambient with no filament to
  4275. # protect, and the hourly notification just becomes
  4276. # noise. Sensor history was already recorded above so
  4277. # the UI charts stay continuous (#1619). Per-AMS check
  4278. # so a multi-AMS setup with one loaded + one empty
  4279. # still alarms on the loaded unit.
  4280. if not _ams_has_filament(ams_data):
  4281. continue
  4282. # Check humidity alarm (only if above threshold)
  4283. if humidity is not None and humidity > humidity_threshold:
  4284. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  4285. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  4286. now = datetime.now(timezone.utc)
  4287. if (
  4288. last_alarm is None
  4289. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  4290. ):
  4291. _ams_alarm_cooldown[cooldown_key] = now
  4292. logger.info(
  4293. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {humidity_threshold}%"
  4294. )
  4295. try:
  4296. # Call different notification method based on AMS type
  4297. if is_ams_ht:
  4298. await notification_service.on_ams_ht_humidity_high(
  4299. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  4300. )
  4301. else:
  4302. await notification_service.on_ams_humidity_high(
  4303. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  4304. )
  4305. except Exception as e:
  4306. logger.warning("Failed to send humidity alarm: %s", e)
  4307. # Check temperature alarm (only if above threshold)
  4308. if temperature is not None and temperature > temp_threshold:
  4309. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  4310. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  4311. now = datetime.now(timezone.utc)
  4312. if (
  4313. last_alarm is None
  4314. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  4315. ):
  4316. _ams_alarm_cooldown[cooldown_key] = now
  4317. logger.info(
  4318. f"Sending temperature alarm for {printer.name} {ams_label}: {temperature}°C > {temp_threshold}°C"
  4319. )
  4320. try:
  4321. # Call different notification method based on AMS type
  4322. if is_ams_ht:
  4323. await notification_service.on_ams_ht_temperature_high(
  4324. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  4325. )
  4326. else:
  4327. await notification_service.on_ams_temperature_high(
  4328. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  4329. )
  4330. except Exception as e:
  4331. logger.warning("Failed to send temperature alarm: %s", e)
  4332. await db.commit()
  4333. if recorded_count > 0:
  4334. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  4335. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  4336. global _ams_cleanup_counter
  4337. _ams_cleanup_counter += 1
  4338. if _ams_cleanup_counter >= 288:
  4339. _ams_cleanup_counter = 0
  4340. # Get retention days from settings
  4341. from backend.app.models.settings import Settings
  4342. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  4343. setting = result.scalar_one_or_none()
  4344. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  4345. cutoff = datetime.utcnow() - timedelta(days=retention_days)
  4346. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  4347. await db.commit()
  4348. if result.rowcount > 0:
  4349. logger.info(
  4350. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  4351. )
  4352. # Wait until next recording interval
  4353. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  4354. except asyncio.CancelledError:
  4355. break
  4356. except Exception as e:
  4357. logger.warning("AMS history recording failed: %s", e)
  4358. await asyncio.sleep(60) # Wait a bit before retrying
  4359. def start_ams_history_recording():
  4360. """Start the AMS history recording background task."""
  4361. global _ams_history_task
  4362. if _ams_history_task is None:
  4363. _ams_history_task = asyncio.create_task(record_ams_history())
  4364. logging.getLogger(__name__).info("AMS history recording started")
  4365. def stop_ams_history_recording():
  4366. """Stop the AMS history recording background task."""
  4367. global _ams_history_task
  4368. if _ams_history_task:
  4369. _ams_history_task.cancel()
  4370. _ams_history_task = None
  4371. logging.getLogger(__name__).info("AMS history recording stopped")
  4372. # Printer runtime tracking
  4373. _runtime_tracking_task: asyncio.Task | None = None
  4374. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  4375. async def track_printer_runtime():
  4376. """Background task to track printer active runtime (RUNNING state only).
  4377. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  4378. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  4379. which track mechanical wear. Pause time has no motion and no wear, so
  4380. counting it inflates maintenance warnings (#1521).
  4381. """
  4382. logger = logging.getLogger(__name__)
  4383. # Wait for MQTT connections to establish on startup
  4384. await asyncio.sleep(15)
  4385. while True:
  4386. try:
  4387. from backend.app.models.printer import Printer
  4388. # Fetch printer IDs in a short-lived read-only session
  4389. async with async_session() as db:
  4390. result = await db.execute(
  4391. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  4392. Printer.is_active.is_(True)
  4393. )
  4394. )
  4395. printer_rows = result.all()
  4396. now = datetime.now(timezone.utc)
  4397. updated_count = 0
  4398. # Update each printer in its own short session to minimise write-lock
  4399. # hold time and avoid blocking critical commits like queue status
  4400. # updates (#897).
  4401. for pid, pname, runtime_secs, last_update in printer_rows:
  4402. state = printer_manager.get_status(pid)
  4403. if not state:
  4404. logger.debug("[%s] Runtime tracking: no state available", pname)
  4405. continue
  4406. if not state.connected:
  4407. logger.debug("[%s] Runtime tracking: not connected", pname)
  4408. continue
  4409. needs_commit = False
  4410. new_runtime = runtime_secs
  4411. new_last_update = last_update
  4412. if state.state == "RUNNING":
  4413. if last_update:
  4414. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  4415. elapsed = (now - lu).total_seconds()
  4416. if elapsed > 0:
  4417. new_runtime = runtime_secs + int(elapsed)
  4418. updated_count += 1
  4419. needs_commit = True
  4420. logger.debug(
  4421. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  4422. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  4423. )
  4424. else:
  4425. needs_commit = True
  4426. logger.debug("[%s] Runtime tracking: first active detection", pname)
  4427. new_last_update = now
  4428. else:
  4429. if last_update is not None:
  4430. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  4431. new_last_update = None
  4432. needs_commit = True
  4433. if needs_commit:
  4434. try:
  4435. async with async_session() as db:
  4436. result = await db.execute(select(Printer).where(Printer.id == pid))
  4437. printer = result.scalar_one_or_none()
  4438. if printer:
  4439. printer.runtime_seconds = new_runtime
  4440. printer.last_runtime_update = new_last_update
  4441. await db.commit()
  4442. except Exception as e:
  4443. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  4444. if updated_count > 0:
  4445. logger.debug("Updated runtime for %s printer(s)", updated_count)
  4446. except asyncio.CancelledError:
  4447. logger.info("Runtime tracking cancelled")
  4448. break
  4449. except Exception as e:
  4450. logger.warning("Runtime tracking failed: %s", e)
  4451. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  4452. def start_runtime_tracking():
  4453. """Start the printer runtime tracking background task."""
  4454. global _runtime_tracking_task
  4455. if _runtime_tracking_task is None:
  4456. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  4457. logging.getLogger(__name__).info("Printer runtime tracking started")
  4458. def stop_runtime_tracking():
  4459. """Stop the printer runtime tracking background task."""
  4460. global _runtime_tracking_task
  4461. if _runtime_tracking_task:
  4462. _runtime_tracking_task.cancel()
  4463. _runtime_tracking_task = None
  4464. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  4465. # SpoolBuddy device watchdog
  4466. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  4467. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  4468. async def _spoolbuddy_watchdog_loop():
  4469. """Periodic check for SpoolBuddy devices that have gone offline."""
  4470. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  4471. while True:
  4472. try:
  4473. await spoolbuddy_watchdog()
  4474. except asyncio.CancelledError:
  4475. break
  4476. except Exception as e:
  4477. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  4478. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  4479. def start_spoolbuddy_watchdog():
  4480. global _spoolbuddy_watchdog_task
  4481. if _spoolbuddy_watchdog_task is None:
  4482. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  4483. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  4484. def stop_spoolbuddy_watchdog():
  4485. global _spoolbuddy_watchdog_task
  4486. if _spoolbuddy_watchdog_task:
  4487. _spoolbuddy_watchdog_task.cancel()
  4488. _spoolbuddy_watchdog_task = None
  4489. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  4490. # Camera stream orphan cleanup
  4491. _camera_cleanup_task: asyncio.Task | None = None
  4492. CAMERA_CLEANUP_INTERVAL = 60
  4493. async def _camera_cleanup_loop():
  4494. """Periodically clean up orphaned ffmpeg processes."""
  4495. from backend.app.api.routes.camera import cleanup_orphaned_streams
  4496. while True:
  4497. try:
  4498. await cleanup_orphaned_streams()
  4499. except asyncio.CancelledError:
  4500. break
  4501. except Exception as e:
  4502. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  4503. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  4504. def start_camera_cleanup():
  4505. global _camera_cleanup_task
  4506. if _camera_cleanup_task is None:
  4507. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  4508. logging.getLogger(__name__).info("Camera stream cleanup started")
  4509. def stop_camera_cleanup():
  4510. global _camera_cleanup_task
  4511. if _camera_cleanup_task:
  4512. _camera_cleanup_task.cancel()
  4513. _camera_cleanup_task = None
  4514. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  4515. # ---------------------------------------------------------------------------
  4516. # Expected-print TTL eviction
  4517. # ---------------------------------------------------------------------------
  4518. def _evict_stale_expected_prints() -> None:
  4519. """Remove entries from _expected_prints / _expected_print_creators that are
  4520. older than _EXPECTED_PRINT_TTL_SECONDS.
  4521. This prevents unbounded growth when a print is registered (via
  4522. register_expected_print) but on_print_start never fires — e.g. because the
  4523. printer disconnects, the app restarts, or the print is started directly from
  4524. the printer panel without going through the queue.
  4525. """
  4526. # Use monotonic time so the TTL is unaffected by system clock adjustments
  4527. # (e.g. NTP sync, DST changes).
  4528. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  4529. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  4530. if not stale_keys:
  4531. return
  4532. evicted_archive_ids: set[int] = set()
  4533. for key in stale_keys:
  4534. archive_id = _expected_prints.pop(key, None)
  4535. if archive_id is not None:
  4536. evicted_archive_ids.add(archive_id)
  4537. _expected_print_creators.pop(key, None)
  4538. _expected_print_registered_at.pop(key, None)
  4539. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  4540. # that have no remaining live keys in _expected_prints (all variants
  4541. # were just evicted).
  4542. live_archive_ids = set(_expected_prints.values())
  4543. for archive_id in evicted_archive_ids:
  4544. if archive_id not in live_archive_ids:
  4545. _print_ams_mappings.pop(archive_id, None)
  4546. _print_plate_ids.pop(archive_id, None)
  4547. logging.getLogger(__name__).info(
  4548. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  4549. )
  4550. async def _expected_prints_cleanup_loop() -> None:
  4551. """Background task: periodically evict stale expected-print entries."""
  4552. while True:
  4553. try:
  4554. _evict_stale_expected_prints()
  4555. except asyncio.CancelledError:
  4556. raise
  4557. except Exception as e:
  4558. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  4559. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  4560. def start_expected_prints_cleanup() -> None:
  4561. global _expected_prints_cleanup_task
  4562. if _expected_prints_cleanup_task is None:
  4563. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  4564. logging.getLogger(__name__).info("Expected prints cleanup started")
  4565. def stop_expected_prints_cleanup() -> None:
  4566. global _expected_prints_cleanup_task
  4567. if _expected_prints_cleanup_task:
  4568. _expected_prints_cleanup_task.cancel()
  4569. _expected_prints_cleanup_task = None
  4570. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  4571. # ---------------------------------------------------------------------------
  4572. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  4573. # ---------------------------------------------------------------------------
  4574. _auth_cleanup_task: asyncio.Task | None = None
  4575. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  4576. async def _run_auth_cleanup() -> None:
  4577. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  4578. from backend.app.core.database import async_session
  4579. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  4580. from backend.app.models.user_totp import UserTOTP
  4581. now = datetime.now(timezone.utc)
  4582. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  4583. try:
  4584. async with async_session() as db:
  4585. stale_cutoff = now - timedelta(hours=1)
  4586. result = await db.execute(
  4587. select(UserTOTP).where(
  4588. UserTOTP.is_enabled.is_(False),
  4589. UserTOTP.created_at < stale_cutoff,
  4590. )
  4591. )
  4592. stale_records = result.scalars().all()
  4593. if stale_records:
  4594. for rec in stale_records:
  4595. await db.delete(rec)
  4596. await db.commit()
  4597. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  4598. except Exception as e:
  4599. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  4600. # Remove expired revoked-JTI entries (they are no longer needed once the
  4601. # original token's exp has passed — the token would be rejected by JWT
  4602. # signature verification regardless).
  4603. try:
  4604. async with async_session() as db:
  4605. await db.execute(
  4606. delete(AuthEphemeralToken).where(
  4607. AuthEphemeralToken.token_type == "revoked_jti",
  4608. AuthEphemeralToken.expires_at < now,
  4609. )
  4610. )
  4611. await db.commit()
  4612. except Exception as e:
  4613. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  4614. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  4615. # Events outside this window can never affect rate-limit decisions — they only
  4616. # consume DB space. Use the same window constant as the rate limiter so the
  4617. # two are always in sync.
  4618. try:
  4619. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  4620. async with async_session() as db:
  4621. await db.execute(
  4622. delete(AuthRateLimitEvent).where(
  4623. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  4624. )
  4625. )
  4626. await db.commit()
  4627. except Exception as e:
  4628. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  4629. async def _auth_cleanup_loop() -> None:
  4630. """Periodic background task: run auth cleanup every hour."""
  4631. while True:
  4632. try:
  4633. await _run_auth_cleanup()
  4634. except asyncio.CancelledError:
  4635. break
  4636. except Exception as e:
  4637. logging.warning("Auth cleanup loop error: %s", e)
  4638. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  4639. def start_auth_cleanup() -> None:
  4640. global _auth_cleanup_task
  4641. if _auth_cleanup_task is None:
  4642. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  4643. logging.getLogger(__name__).info("Auth periodic cleanup started")
  4644. def stop_auth_cleanup() -> None:
  4645. global _auth_cleanup_task
  4646. if _auth_cleanup_task:
  4647. _auth_cleanup_task.cancel()
  4648. _auth_cleanup_task = None
  4649. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  4650. @asynccontextmanager
  4651. async def lifespan(app: FastAPI):
  4652. # Startup
  4653. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  4654. # anything else can spawn tasks that might trip it.
  4655. from backend.app.core.asyncio_handlers import install_proactor_reset_filter
  4656. install_proactor_reset_filter()
  4657. await init_db()
  4658. # Register an app-scoped httpx client for Bambu Cloud services so
  4659. # per-request BambuCloudService instances reuse the same connection pool
  4660. # (important for routes like /cloud/filament-info that chain many
  4661. # get_setting_detail calls). The shared client stores no region/token
  4662. # state, so the per-request ownership pattern that fixed the region-bleed
  4663. # bug is preserved.
  4664. import httpx as _httpx
  4665. from backend.app.services.bambu_cloud import set_shared_http_client
  4666. from backend.app.services.makerworld import (
  4667. set_shared_http_client as set_shared_makerworld_http_client,
  4668. )
  4669. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  4670. set_shared_http_client(_shared_cloud_http_client)
  4671. # Reuse the same connection pool for MakerWorld — different host, same
  4672. # keep-alive pool saves a TLS handshake per request.
  4673. set_shared_makerworld_http_client(_shared_cloud_http_client)
  4674. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  4675. # This can happen when a print was cancelled mid-print on versions before this fix.
  4676. try:
  4677. async with async_session() as db:
  4678. from backend.app.models.print_queue import PrintQueueItem
  4679. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  4680. aborted_items = result.scalars().all()
  4681. if aborted_items:
  4682. for item in aborted_items:
  4683. item.status = "cancelled"
  4684. await db.commit()
  4685. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  4686. except Exception as e:
  4687. logging.warning("Failed to fix aborted queue items: %s", e)
  4688. # Restore debug logging state from previous session
  4689. await init_debug_logging()
  4690. # Set up printer manager callbacks
  4691. loop = asyncio.get_event_loop()
  4692. printer_manager.set_event_loop(loop)
  4693. printer_manager.set_status_change_callback(on_printer_status_change)
  4694. printer_manager.set_print_start_callback(on_print_start)
  4695. printer_manager.set_print_complete_callback(on_print_complete)
  4696. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  4697. printer_manager.set_ams_change_callback(on_ams_change)
  4698. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  4699. await printer_manager.load_awaiting_plate_clear_from_db()
  4700. # Layer change callback for external camera timelapse
  4701. async def on_layer_change(printer_id: int, layer_num: int):
  4702. """Capture timelapse frame on layer change + first layer notification."""
  4703. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  4704. await tl_layer_change(printer_id, layer_num)
  4705. # First layer complete notification (layer_num >= 2 means layer 1 is done)
  4706. if 2 <= layer_num <= 5 and not _first_layer_notified.get(printer_id, False):
  4707. _first_layer_notified[printer_id] = True
  4708. try:
  4709. async with async_session() as db:
  4710. from backend.app.models.printer import Printer
  4711. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4712. printer = result.scalar_one_or_none()
  4713. if not printer:
  4714. return
  4715. printer_name = printer.name
  4716. client = printer_manager.get_client(printer_id)
  4717. state = client.state if client else None
  4718. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  4719. total_layers = state.total_layers if state else 0
  4720. image_data = await _capture_snapshot_for_notification(
  4721. printer_id, printer, logging.getLogger(__name__)
  4722. )
  4723. await notification_service.on_first_layer_complete(
  4724. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  4725. )
  4726. except Exception as e:
  4727. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  4728. printer_manager.set_layer_change_callback(on_layer_change)
  4729. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  4730. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  4731. waiter = _bed_cool_waiters.get(printer_id)
  4732. if not waiter:
  4733. return
  4734. threshold = waiter["threshold"]
  4735. if bed_temp > threshold:
  4736. return
  4737. # Bed is at or below threshold — fire notification and remove waiter
  4738. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  4739. if not waiter_info:
  4740. return # Another callback already handled it
  4741. bed_cool_logger = logging.getLogger(__name__)
  4742. bed_cool_logger.info(
  4743. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  4744. bed_temp,
  4745. printer_id,
  4746. threshold,
  4747. )
  4748. try:
  4749. printer_info = printer_manager.get_printer(printer_id)
  4750. p_name = printer_info.name if printer_info else "Unknown"
  4751. async with async_session() as db:
  4752. await notification_service.on_bed_cooled(
  4753. printer_id=printer_id,
  4754. printer_name=p_name,
  4755. bed_temp=bed_temp,
  4756. threshold=threshold,
  4757. filename=waiter_info["filename"],
  4758. db=db,
  4759. )
  4760. except Exception as e:
  4761. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  4762. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  4763. async def on_drying_complete(printer_id: int, ams_id: int):
  4764. """Smart-plug auto-off-after-drying trigger (#1349).
  4765. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  4766. manager walks all plugs linked to this printer and turns off only
  4767. the ones with ``auto_off_after_drying`` enabled, after their
  4768. per-plug delay. Multiple AMS units finishing close together (e.g. a
  4769. dual-AMS dry that ends within the same MQTT push) call this once
  4770. per unit — the manager's ``_cancel_pending_off`` collapses
  4771. repeated scheduling on the same plug to one timer, so duplicate
  4772. fires are safe.
  4773. """
  4774. try:
  4775. async with async_session() as db:
  4776. await smart_plug_manager.on_drying_complete(printer_id, db)
  4777. except Exception as e:
  4778. logging.getLogger(__name__).warning(
  4779. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  4780. printer_id,
  4781. ams_id,
  4782. e,
  4783. )
  4784. printer_manager.set_drying_complete_callback(on_drying_complete)
  4785. # Initialize MQTT relay from settings
  4786. async with async_session() as db:
  4787. from backend.app.api.routes.settings import get_setting
  4788. mqtt_settings = {
  4789. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  4790. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  4791. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  4792. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  4793. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  4794. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  4795. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  4796. }
  4797. await mqtt_relay.configure(mqtt_settings)
  4798. # Restore MQTT smart plug subscriptions
  4799. if mqtt_settings.get("mqtt_enabled"):
  4800. from backend.app.models.smart_plug import SmartPlug
  4801. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  4802. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  4803. mqtt_plugs = result.scalars().all()
  4804. restored = 0
  4805. for plug in mqtt_plugs:
  4806. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  4807. restored += 1
  4808. if restored:
  4809. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  4810. # Connect to all active printers
  4811. async with async_session() as db:
  4812. await init_printer_connections(db)
  4813. # Auto-connect to Spoolman if enabled
  4814. async with async_session() as db:
  4815. from backend.app.api.routes.settings import get_setting
  4816. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  4817. spoolman_url = await get_setting(db, "spoolman_url")
  4818. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  4819. try:
  4820. client = await init_spoolman_client(spoolman_url)
  4821. if await client.health_check():
  4822. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  4823. # Ensure the 'tag' extra field exists for RFID/UUID storage
  4824. field_ok = await client.ensure_tag_extra_field()
  4825. if not field_ok:
  4826. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  4827. # Register the BambuStudio slicer-preset fields used by the
  4828. # spool-edit / assign flow. Spoolman rejects PATCHes with
  4829. # unknown extra keys, so these must exist before any update
  4830. # that touches them.
  4831. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  4832. if not await client.ensure_extra_field(field_name):
  4833. logging.warning(
  4834. "Spoolman extra field %r registration failed — "
  4835. "spool slicer-preset edits will return 502",
  4836. field_name,
  4837. )
  4838. else:
  4839. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  4840. except Exception as e:
  4841. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  4842. # Start the print scheduler
  4843. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  4844. # Start background dispatch worker for send/start operations
  4845. await background_dispatch.start()
  4846. # Start the smart plug scheduler for time-based on/off
  4847. smart_plug_manager.start_scheduler()
  4848. # Resume any pending auto-offs that were interrupted by restart
  4849. await smart_plug_manager.resume_pending_auto_offs()
  4850. # Start the notification digest scheduler
  4851. notification_service.start_digest_scheduler()
  4852. # Start the GitHub backup scheduler
  4853. await github_backup_service.start_scheduler()
  4854. # Start the local backup scheduler
  4855. await local_backup_service.start_scheduler()
  4856. await obico_detection_service.start()
  4857. # Start the library trash sweeper (#1008)
  4858. await library_trash_service.start_scheduler()
  4859. # Start the archive auto-purge sweeper (#1008 follow-up)
  4860. await archive_purge_service.start_scheduler()
  4861. # Start AMS history recording
  4862. start_ams_history_recording()
  4863. # Start printer runtime tracking
  4864. start_runtime_tracking()
  4865. # Start SpoolBuddy device watchdog
  4866. start_spoolbuddy_watchdog()
  4867. # Start camera stream orphan cleanup
  4868. start_camera_cleanup()
  4869. # Start expected-print TTL eviction (prevents memory leak when prints are
  4870. # registered but on_print_start never fires)
  4871. start_expected_prints_cleanup()
  4872. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  4873. start_auth_cleanup()
  4874. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  4875. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  4876. from backend.app.services.loop_watchdog import start_loop_watchdog
  4877. start_loop_watchdog()
  4878. # Initialize virtual printer manager and sync from DB
  4879. from backend.app.services.virtual_printer import virtual_printer_manager
  4880. virtual_printer_manager.set_session_factory(async_session)
  4881. virtual_printer_manager.set_printer_manager(printer_manager)
  4882. try:
  4883. await virtual_printer_manager.sync_from_db()
  4884. logging.info("Virtual printer manager synced from database")
  4885. except Exception as e:
  4886. logging.warning("Failed to sync virtual printers: %s", e)
  4887. yield
  4888. # Shutdown
  4889. print_scheduler.stop()
  4890. await background_dispatch.stop()
  4891. smart_plug_manager.stop_scheduler()
  4892. notification_service.stop_digest_scheduler()
  4893. github_backup_service.stop_scheduler()
  4894. local_backup_service.stop_scheduler()
  4895. library_trash_service.stop_scheduler()
  4896. archive_purge_service.stop_scheduler()
  4897. obico_detection_service.stop()
  4898. stop_ams_history_recording()
  4899. stop_runtime_tracking()
  4900. stop_spoolbuddy_watchdog()
  4901. stop_camera_cleanup()
  4902. from backend.app.services.loop_watchdog import stop_loop_watchdog
  4903. stop_loop_watchdog()
  4904. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  4905. # cleanly rather than waiting on a queue that nothing will ever fill.
  4906. try:
  4907. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  4908. await shutdown_all_broadcasters()
  4909. except Exception as e:
  4910. logging.warning("Failed to shut down camera broadcasters: %s", e)
  4911. stop_expected_prints_cleanup()
  4912. stop_auth_cleanup()
  4913. printer_manager.disconnect_all()
  4914. await close_spoolman_client()
  4915. # Stop all virtual printer services
  4916. await virtual_printer_manager.stop_all()
  4917. await mqtt_smart_plug_service.disconnect(timeout=2)
  4918. await mqtt_relay.disconnect(timeout=2)
  4919. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  4920. set_shared_http_client(None)
  4921. set_shared_makerworld_http_client(None)
  4922. await _shared_cloud_http_client.aclose()
  4923. # Checkpoint WAL (SQLite only) and close all database connections
  4924. from backend.app.core.db_dialect import is_sqlite
  4925. if is_sqlite():
  4926. try:
  4927. async with engine.begin() as conn:
  4928. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  4929. logging.info("WAL checkpoint completed")
  4930. except Exception as e:
  4931. logging.warning("WAL checkpoint failed: %s", e)
  4932. await engine.dispose()
  4933. app = FastAPI(
  4934. title=app_settings.app_name,
  4935. description="Archive and manage Bambu Lab 3MF files",
  4936. version=APP_VERSION,
  4937. lifespan=lifespan,
  4938. )
  4939. # =============================================================================
  4940. # Authentication Middleware - Secures ALL API routes by default
  4941. # =============================================================================
  4942. # Public routes that don't require authentication even when auth is enabled
  4943. PUBLIC_API_ROUTES = {
  4944. # Auth routes needed before/during login
  4945. "/api/v1/auth/status",
  4946. "/api/v1/auth/login",
  4947. "/api/v1/auth/setup", # Needed for initial setup and recovery
  4948. # Advanced auth status needed for login page
  4949. "/api/v1/auth/advanced-auth/status",
  4950. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  4951. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  4952. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  4953. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  4954. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  4955. # OIDC routes that must be reachable without a JWT
  4956. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  4957. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  4958. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  4959. # Version check for updates (no sensitive data)
  4960. "/api/v1/updates/version",
  4961. # Metrics endpoint handles its own prometheus_token authentication
  4962. "/api/v1/metrics",
  4963. }
  4964. # Route prefixes that are public (for routes with dynamic segments)
  4965. PUBLIC_API_PREFIXES = [
  4966. # WebSocket connections handle their own auth
  4967. "/api/v1/ws",
  4968. # OIDC authorize redirects — include provider_id in path
  4969. "/api/v1/auth/oidc/authorize/",
  4970. ]
  4971. # Route patterns that are public (read-only display data)
  4972. # These are checked with "in path" - needed because browsers load images/videos
  4973. # via <img src> and <video src> which don't include Authorization headers
  4974. PUBLIC_API_PATTERNS = [
  4975. # Thumbnails
  4976. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  4977. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  4978. # Images and media
  4979. "/photos/", # /archives/{id}/photos/{filename}
  4980. "/project-image/", # /archives/{id}/project-image/{path}
  4981. "/qrcode", # /archives/{id}/qrcode
  4982. "/timelapse", # /archives/{id}/timelapse (video)
  4983. "/cover", # /printers/{id}/cover
  4984. "/icon", # /external-links/{id}/icon
  4985. # Camera (streams loaded via <img> tag)
  4986. "/camera/stream", # /printers/{id}/camera/stream
  4987. "/camera/snapshot", # /printers/{id}/camera/snapshot
  4988. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  4989. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  4990. # download token in the URL path instead.
  4991. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  4992. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  4993. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  4994. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  4995. ]
  4996. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  4997. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  4998. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  4999. Format: comma-separated list of ``scheme://host[:port]`` origins.
  5000. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  5001. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  5002. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  5003. Invalid entries are dropped with a warning rather than failing startup, so
  5004. a typo in one origin doesn't take the whole deployment down.
  5005. """
  5006. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  5007. if not raw:
  5008. return ()
  5009. valid: list[str] = []
  5010. for item in raw.split(","):
  5011. candidate = item.strip()
  5012. if not candidate:
  5013. continue
  5014. try:
  5015. parsed = urlparse(candidate)
  5016. except ValueError as e:
  5017. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  5018. continue
  5019. if parsed.scheme not in ("http", "https"):
  5020. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  5021. continue
  5022. if not parsed.netloc:
  5023. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  5024. continue
  5025. if parsed.path and parsed.path != "/":
  5026. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  5027. continue
  5028. if parsed.query or parsed.fragment:
  5029. _security_headers_logger.warning(
  5030. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  5031. )
  5032. continue
  5033. if "*" in parsed.netloc:
  5034. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  5035. continue
  5036. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  5037. if valid:
  5038. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  5039. return tuple(valid)
  5040. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  5041. def _frame_ancestors(default_value: str) -> str:
  5042. """Compose the ``frame-ancestors`` CSP directive (#1191).
  5043. ``default_value`` is the strict directive used when the operator has not
  5044. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  5045. docs) or ``'self'`` (gcode-viewer, served same-origin). When trusted origins
  5046. are configured, ``'self'`` is always included so same-origin embedding never
  5047. breaks even if an operator forgets to add their own origin to the list.
  5048. """
  5049. if _TRUSTED_FRAME_ORIGINS:
  5050. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  5051. return f"frame-ancestors {default_value};"
  5052. @app.middleware("http")
  5053. async def security_headers_middleware(request, call_next):
  5054. """Add standard HTTP security headers to every response."""
  5055. # Per-request nonce stamped into `script-src` (#1460). On its own this
  5056. # changes nothing for Bambuddy's own pages — index.html has no inline
  5057. # scripts since the SW registration moved to /sw-register.js. The reason
  5058. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  5059. # script injected into the HTML on the edge, with a fresh hash on every
  5060. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  5061. # it clones the same nonce onto its injected <script>, and the inline
  5062. # script passes the policy without us needing 'unsafe-inline'. See
  5063. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  5064. csp_nonce = secrets.token_urlsafe(16)
  5065. response = await call_next(request)
  5066. response.headers["X-Content-Type-Options"] = "nosniff"
  5067. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  5068. # browsers honour CSP frame-ancestors instead, and the legacy
  5069. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  5070. # When operators have explicitly allowlisted trusted frame origins (#1191
  5071. # — typically Home Assistant on a different port), drop X-Frame-Options
  5072. # and let the CSP-side frame-ancestors directive govern embedding.
  5073. if not _TRUSTED_FRAME_ORIGINS:
  5074. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  5075. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  5076. # Content-Security-Policy for the React SPA.
  5077. # Notes:
  5078. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  5079. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  5080. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  5081. # - media-src blob:: timelapse video player uses Blob URLs.
  5082. # - font-src data:: some icon fonts are embedded as data URIs.
  5083. if request.url.path.startswith("/gcode-viewer"):
  5084. # The gcode viewer is embedded in an iframe served by this same origin,
  5085. # so frame-ancestors must allow 'self'. prettygcode.js also uses eval()
  5086. # internally, so script-src needs 'unsafe-eval'.
  5087. response.headers["Content-Security-Policy"] = (
  5088. "default-src 'self'; "
  5089. "script-src 'self' 'unsafe-eval'; "
  5090. "style-src 'self' 'unsafe-inline'; "
  5091. "img-src 'self' data: blob:; "
  5092. "media-src 'self' blob:; "
  5093. "connect-src 'self' ws: wss:; "
  5094. "font-src 'self' data:; "
  5095. "object-src 'none'; "
  5096. "base-uri 'self'; "
  5097. "frame-src 'self' http: https:; " + _frame_ancestors("'self'")
  5098. )
  5099. elif request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  5100. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  5101. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  5102. # default CSP would render a blank page.
  5103. response.headers["Content-Security-Policy"] = (
  5104. "default-src 'self'; "
  5105. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  5106. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  5107. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  5108. "connect-src 'self'; "
  5109. "font-src 'self' data: https://fonts.gstatic.com; "
  5110. "worker-src 'self' blob:; "
  5111. "object-src 'none'; "
  5112. "base-uri 'self'; " + _frame_ancestors("'none'")
  5113. )
  5114. else:
  5115. response.headers["Content-Security-Policy"] = (
  5116. "default-src 'self'; "
  5117. f"script-src 'self' 'nonce-{csp_nonce}'; "
  5118. "style-src 'self' 'unsafe-inline'; "
  5119. "img-src 'self' data: blob:; "
  5120. "media-src 'self' blob:; "
  5121. "connect-src 'self' ws: wss:; "
  5122. "font-src 'self' data:; "
  5123. "object-src 'none'; "
  5124. "base-uri 'self'; "
  5125. "frame-src 'self' http: https:; " + _frame_ancestors("'none'")
  5126. )
  5127. if request.url.scheme == "https":
  5128. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  5129. return response
  5130. @app.middleware("http")
  5131. async def auth_middleware(request, call_next):
  5132. """Enforce authentication on all API routes when auth is enabled.
  5133. This middleware provides defense-in-depth by checking auth at the API gateway level,
  5134. regardless of whether individual routes have auth dependencies.
  5135. """
  5136. from starlette.responses import JSONResponse
  5137. path = request.url.path
  5138. # Only apply to API routes
  5139. if not path.startswith("/api/"):
  5140. return await call_next(request)
  5141. # Allow public routes
  5142. if path in PUBLIC_API_ROUTES:
  5143. return await call_next(request)
  5144. # Allow public prefixes
  5145. for prefix in PUBLIC_API_PREFIXES:
  5146. if path.startswith(prefix):
  5147. return await call_next(request)
  5148. # Allow public patterns (read-only display data like thumbnails)
  5149. for pattern in PUBLIC_API_PATTERNS:
  5150. if pattern in path:
  5151. return await call_next(request)
  5152. # Check if auth is enabled. Fail CLOSED on any exception during the
  5153. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  5154. # an attacker who could force a DB exception (e.g. file-descriptor
  5155. # exhaustion via login flood) bypass auth on every protected endpoint.
  5156. try:
  5157. async with async_session() as db:
  5158. from backend.app.core.auth import is_auth_enabled
  5159. auth_enabled = await is_auth_enabled(db)
  5160. if not auth_enabled:
  5161. # Auth disabled, allow all requests
  5162. return await call_next(request)
  5163. except Exception:
  5164. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  5165. return JSONResponse(
  5166. status_code=503,
  5167. content={"detail": "Authentication service temporarily unavailable"},
  5168. )
  5169. # Auth is enabled - require valid token
  5170. auth_header = request.headers.get("Authorization")
  5171. x_api_key = request.headers.get("X-API-Key")
  5172. # Check for API key auth first
  5173. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  5174. # API key authentication - let the request through to be validated by route handler
  5175. # API keys are validated per-route since they have different permission levels
  5176. return await call_next(request)
  5177. # Check for JWT auth
  5178. if not auth_header or not auth_header.startswith("Bearer "):
  5179. return JSONResponse(
  5180. status_code=401,
  5181. content={"detail": "Authentication required"},
  5182. headers={"WWW-Authenticate": "Bearer"},
  5183. )
  5184. # Validate JWT token
  5185. import jwt
  5186. try:
  5187. from backend.app.core.auth import (
  5188. ALGORITHM,
  5189. SECRET_KEY,
  5190. _is_token_fresh,
  5191. get_user_by_username,
  5192. is_jti_revoked,
  5193. )
  5194. token = auth_header.replace("Bearer ", "")
  5195. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  5196. username = payload.get("sub")
  5197. if not username:
  5198. raise ValueError("No username in token")
  5199. jti = payload.get("jti")
  5200. if not jti:
  5201. raise ValueError("No jti in token")
  5202. iat = payload.get("iat")
  5203. # Reject revoked tokens (defense-in-depth gateway check)
  5204. if await is_jti_revoked(jti):
  5205. return JSONResponse(
  5206. status_code=401,
  5207. content={"detail": "Token has been revoked"},
  5208. headers={"WWW-Authenticate": "Bearer"},
  5209. )
  5210. # Verify user exists, is active, and token is still fresh (L-R8-A)
  5211. async with async_session() as db:
  5212. user = await get_user_by_username(db, username)
  5213. if not user or not user.is_active:
  5214. return JSONResponse(
  5215. status_code=401,
  5216. content={"detail": "User not found or inactive"},
  5217. headers={"WWW-Authenticate": "Bearer"},
  5218. )
  5219. if not _is_token_fresh(iat, user):
  5220. return JSONResponse(
  5221. status_code=401,
  5222. content={"detail": "Token no longer valid"},
  5223. headers={"WWW-Authenticate": "Bearer"},
  5224. )
  5225. except jwt.ExpiredSignatureError:
  5226. return JSONResponse(
  5227. status_code=401,
  5228. content={"detail": "Token has expired"},
  5229. headers={"WWW-Authenticate": "Bearer"},
  5230. )
  5231. except (jwt.InvalidTokenError, ValueError, Exception):
  5232. return JSONResponse(
  5233. status_code=401,
  5234. content={"detail": "Invalid token"},
  5235. headers={"WWW-Authenticate": "Bearer"},
  5236. )
  5237. return await call_next(request)
  5238. @app.middleware("http")
  5239. async def trace_id_middleware(request, call_next):
  5240. """Stamp every HTTP request with a trace ID and echo it back.
  5241. Decorated AFTER auth_middleware on purpose: Starlette stacks
  5242. @app.middleware decorators LIFO, so the last-decorated runs first
  5243. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  5244. which means auth-middleware log lines (and every line emitted on the
  5245. way down to and back from the route handler) all carry the same
  5246. trace ID. If we put it before auth, auth's logs would be stamped
  5247. with the *previous* request's ID — useless for correlation.
  5248. Honours an inbound ``X-Trace-Id`` header so callers running their
  5249. own tracing can correlate their span IDs with our log lines, but
  5250. only if the value passes the whitelist gate in
  5251. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  5252. rejected (too long, contains control chars, etc.) silently triggers
  5253. a freshly minted server-side ID rather than failing the request.
  5254. The minted (or echoed) ID is set on a ContextVar so that every log
  5255. record emitted during the request — application logs *and* uvicorn's
  5256. access log — carries it via TraceIDFilter, and is also written to
  5257. the ``X-Trace-Id`` response header so clients can pin a server-side
  5258. log search to the exact request they made.
  5259. """
  5260. from backend.app.core.trace import (
  5261. generate_trace_id,
  5262. normalise_inbound_trace_id,
  5263. trace_id_var,
  5264. )
  5265. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  5266. trace_id = inbound if inbound is not None else generate_trace_id()
  5267. token = trace_id_var.set(trace_id)
  5268. try:
  5269. response = await call_next(request)
  5270. finally:
  5271. # Reset the ContextVar so a record emitted in a totally
  5272. # unrelated background task that just happens to inherit this
  5273. # context doesn't keep referencing this request's ID forever.
  5274. # In practice ContextVar.reset is best-effort under asyncio
  5275. # task-spawn semantics, but the cost is one attribute write so
  5276. # we may as well do it.
  5277. trace_id_var.reset(token)
  5278. response.headers["X-Trace-Id"] = trace_id
  5279. return response
  5280. # API routes
  5281. app.include_router(auth.router, prefix=app_settings.api_prefix)
  5282. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  5283. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  5284. app.include_router(users.router, prefix=app_settings.api_prefix)
  5285. app.include_router(groups.router, prefix=app_settings.api_prefix)
  5286. app.include_router(printers.router, prefix=app_settings.api_prefix)
  5287. app.include_router(archives.router, prefix=app_settings.api_prefix)
  5288. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  5289. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  5290. app.include_router(labels.router, prefix=app_settings.api_prefix)
  5291. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  5292. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  5293. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  5294. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  5295. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  5296. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  5297. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  5298. app.include_router(background_dispatch_routes.router, prefix=app_settings.api_prefix)
  5299. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  5300. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  5301. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  5302. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  5303. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  5304. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  5305. app.include_router(updates.router, prefix=app_settings.api_prefix)
  5306. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  5307. app.include_router(camera.router, prefix=app_settings.api_prefix)
  5308. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  5309. app.include_router(projects.router, prefix=app_settings.api_prefix)
  5310. app.include_router(library.router, prefix=app_settings.api_prefix)
  5311. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  5312. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  5313. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  5314. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  5315. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  5316. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  5317. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  5318. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  5319. app.include_router(system.router, prefix=app_settings.api_prefix)
  5320. app.include_router(support.router, prefix=app_settings.api_prefix)
  5321. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  5322. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  5323. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  5324. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  5325. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  5326. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  5327. app.include_router(obico.router, prefix=app_settings.api_prefix)
  5328. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  5329. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  5330. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  5331. # Serve static files (React build)
  5332. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  5333. app.mount(
  5334. "/assets",
  5335. StaticFiles(directory=app_settings.static_dir / "assets"),
  5336. name="assets",
  5337. )
  5338. if (app_settings.static_dir / "img").exists():
  5339. app.mount(
  5340. "/img",
  5341. StaticFiles(directory=app_settings.static_dir / "img"),
  5342. name="img",
  5343. )
  5344. if (app_settings.static_dir / "icons").exists():
  5345. app.mount(
  5346. "/icons",
  5347. StaticFiles(directory=app_settings.static_dir / "icons"),
  5348. name="icons",
  5349. )
  5350. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  5351. # falls through to the SPA catch-all and returns index.html, which the
  5352. # browser's font sanitizer rejects ("downloadable font: rejected by
  5353. # sanitizer").
  5354. if (app_settings.static_dir / "fonts").exists():
  5355. app.mount(
  5356. "/fonts",
  5357. StaticFiles(directory=app_settings.static_dir / "fonts"),
  5358. name="fonts",
  5359. )
  5360. @app.get("/")
  5361. async def serve_frontend():
  5362. """Serve the React frontend."""
  5363. index_file = app_settings.static_dir / "index.html"
  5364. if index_file.exists():
  5365. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  5366. return {
  5367. "message": "Bambuddy API",
  5368. "docs": "/docs",
  5369. "frontend": "Build and place React app in /static directory",
  5370. }
  5371. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  5372. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  5373. # forever, but the HTML wrapping it is the only file that knows which hash
  5374. # is current. Without explicit cache-control headers Chromium decides
  5375. # heuristically (typically 10% of the time since Last-Modified) and on
  5376. # long-running kiosks happily serves stale HTML across browser restarts.
  5377. # That stale HTML references an old bundle hash, the old bundle is also
  5378. # in the disk cache, and the user ends up running pre-update JS forever
  5379. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  5380. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  5381. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  5382. @app.get("/health")
  5383. async def health_check():
  5384. """Health check endpoint."""
  5385. return {"status": "healthy"}
  5386. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  5387. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  5388. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  5389. # in deployment debugging.
  5390. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  5391. async def serve_manifest():
  5392. """Serve PWA manifest."""
  5393. manifest_file = app_settings.static_dir / "manifest.json"
  5394. if manifest_file.exists():
  5395. return FileResponse(manifest_file, media_type="application/manifest+json")
  5396. return {"error": "Manifest not found"}
  5397. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  5398. async def serve_service_worker():
  5399. """Serve service worker."""
  5400. sw_file = app_settings.static_dir / "sw.js"
  5401. if sw_file.exists():
  5402. return FileResponse(
  5403. sw_file,
  5404. media_type="application/javascript",
  5405. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  5406. )
  5407. return {"error": "Service worker not found"}
  5408. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  5409. async def serve_sw_register():
  5410. """Serve the service-worker registration bootstrap script.
  5411. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  5412. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  5413. """
  5414. reg_file = app_settings.static_dir / "sw-register.js"
  5415. if reg_file.exists():
  5416. return FileResponse(reg_file, media_type="application/javascript")
  5417. return {"error": "sw-register.js not found"}
  5418. # ── GCode viewer static files ────────────────────────────────────────────────
  5419. # Served via explicit routes so ordering is guaranteed (app.mount() loses
  5420. # to the /{full_path:path} catch-all in some Starlette versions).
  5421. _gcode_viewer_dir = (app_settings.static_dir.parent / "gcode_viewer").resolve()
  5422. # Surface packaging gaps at startup instead of as silent runtime 404s. If the
  5423. # directory is missing the explicit @app.get("/gcode-viewer/...") routes below
  5424. # return bare HTTPException(404) which renders as {"detail":"Not Found"} in
  5425. # the 3D Preview iframe (#1218) — easy to miss in normal operation, easy to
  5426. # spot if the operator scans the startup log or a support bundle.
  5427. if not (_gcode_viewer_dir / "index.html").is_file():
  5428. logging.getLogger(__name__).error(
  5429. "Embedded GCode viewer assets missing at %s — /gcode-viewer/ will return 404 "
  5430. "and 3D Preview will fail. This indicates a packaging bug; the gcode_viewer/ "
  5431. "directory must be present alongside static/.",
  5432. _gcode_viewer_dir,
  5433. )
  5434. def _gcode_viewer_response(rel: str) -> FileResponse:
  5435. from fastapi import HTTPException as _HTTPException
  5436. safe = (_gcode_viewer_dir / rel).resolve()
  5437. if not safe.is_relative_to(_gcode_viewer_dir):
  5438. raise _HTTPException(status_code=403)
  5439. if safe.is_file():
  5440. mt, _ = _mimetypes.guess_type(str(safe))
  5441. return FileResponse(str(safe), media_type=mt or "application/octet-stream")
  5442. raise _HTTPException(status_code=404)
  5443. @app.get("/gcode-viewer/")
  5444. async def serve_gcode_viewer_index() -> FileResponse:
  5445. """Raw PrettyGCode viewer for the iframe. The bare ``/gcode-viewer``
  5446. (no trailing slash) intentionally falls through to the SPA catch-all so a
  5447. full-page reload re-enters the React layout instead of serving the iframe
  5448. contents standalone."""
  5449. return _gcode_viewer_response("index.html")
  5450. @app.get("/gcode-viewer/{file_path:path}")
  5451. async def serve_gcode_viewer_file(file_path: str) -> FileResponse:
  5452. return _gcode_viewer_response(file_path)
  5453. # Catch-all route for React Router (must be last)
  5454. @app.get("/{full_path:path}")
  5455. async def serve_spa(full_path: str):
  5456. """Serve React app for client-side routing."""
  5457. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  5458. if full_path.startswith("api/"):
  5459. from fastapi import HTTPException
  5460. raise HTTPException(status_code=404, detail="Not found")
  5461. index_file = app_settings.static_dir / "index.html"
  5462. if index_file.exists():
  5463. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  5464. return {"error": "Frontend not built"}