main.py 292 KB

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