main.py 283 KB

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