main.py 292 KB

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