main.py 217 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695
  1. import asyncio
  2. import logging
  3. import mimetypes as _mimetypes
  4. import posixpath
  5. import time
  6. from contextlib import asynccontextmanager
  7. from datetime import datetime, timedelta, timezone
  8. from logging.handlers import RotatingFileHandler
  9. from fastapi import FastAPI
  10. from fastapi.responses import FileResponse
  11. from fastapi.staticfiles import StaticFiles
  12. from sqlalchemy import delete, or_, select, text
  13. from backend.app.api.routes import (
  14. ams_history,
  15. api_keys,
  16. archive_purge,
  17. archives,
  18. auth,
  19. background_dispatch as background_dispatch_routes,
  20. bug_report,
  21. camera,
  22. cloud,
  23. discovery,
  24. external_links,
  25. filaments,
  26. firmware,
  27. github_backup,
  28. groups,
  29. inventory,
  30. kprofiles,
  31. library,
  32. library_trash,
  33. local_backup,
  34. local_presets,
  35. maintenance,
  36. makerworld,
  37. metrics,
  38. mfa,
  39. notification_templates,
  40. notifications,
  41. obico,
  42. pending_uploads,
  43. print_log,
  44. print_queue,
  45. printers,
  46. projects,
  47. settings as settings_routes,
  48. smart_plugs,
  49. spoolbuddy,
  50. spoolman,
  51. spoolman_inventory,
  52. support,
  53. system,
  54. updates,
  55. user_notifications,
  56. users,
  57. virtual_printers,
  58. webhook,
  59. websocket,
  60. )
  61. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  62. from backend.app.api.routes.support import init_debug_logging
  63. from backend.app.core.config import APP_VERSION, settings as app_settings
  64. from backend.app.core.database import async_session, engine, init_db
  65. from backend.app.core.websocket import ws_manager
  66. from backend.app.models.smart_plug import SmartPlug
  67. from backend.app.services.archive import ArchiveService
  68. from backend.app.services.archive_purge import archive_purge_service
  69. from backend.app.services.background_dispatch import background_dispatch
  70. from backend.app.services.bambu_ftp import (
  71. FileNotOnPrinterError,
  72. cache_3mf_download,
  73. clear_3mf_cache,
  74. download_file_async,
  75. get_cached_3mf,
  76. get_ftp_retry_settings,
  77. with_ftp_retry,
  78. )
  79. from backend.app.services.bambu_mqtt import PrinterState
  80. from backend.app.services.github_backup import github_backup_service
  81. from backend.app.services.homeassistant import homeassistant_service
  82. from backend.app.services.library_trash import library_trash_service
  83. from backend.app.services.local_backup import local_backup_service
  84. from backend.app.services.mqtt_relay import mqtt_relay
  85. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  86. from backend.app.services.notification_service import notification_service
  87. from backend.app.services.obico_detection import obico_detection_service
  88. from backend.app.services.print_scheduler import scheduler as print_scheduler
  89. from backend.app.services.printer_manager import (
  90. init_printer_connections,
  91. printer_manager,
  92. printer_state_to_dict,
  93. )
  94. from backend.app.services.smart_plug_manager import smart_plug_manager
  95. from backend.app.services.spool_assignment_notifications import (
  96. notify_missing_spool_assignments_on_print_start,
  97. )
  98. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  99. from backend.app.services.spoolman_tracking import (
  100. cleanup_tracking as _cleanup_spoolman_tracking,
  101. report_usage as _report_spoolman_usage,
  102. store_print_data as _store_spoolman_print_data,
  103. )
  104. from backend.app.services.tasmota import tasmota_service
  105. # =============================================================================
  106. # Dependency Check - runs before other imports to give helpful error messages
  107. # =============================================================================
  108. def _start_error_server(missing_packages: list):
  109. """Start a minimal HTTP server to display dependency errors in browser."""
  110. import os
  111. import signal
  112. from http.server import BaseHTTPRequestHandler, HTTPServer
  113. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  114. html = f"""<!DOCTYPE html>
  115. <html>
  116. <head>
  117. <title>Bambuddy - Setup Required</title>
  118. <style>
  119. body {{
  120. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  121. background: #0f172a; color: #e2e8f0;
  122. display: flex; justify-content: center; align-items: center;
  123. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  124. }}
  125. .container {{
  126. background: #1e293b; border-radius: 12px; padding: 40px;
  127. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  128. }}
  129. h1 {{ color: #f87171; margin-bottom: 10px; }}
  130. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  131. .packages {{
  132. background: #0f172a; border-radius: 8px; padding: 20px;
  133. margin: 20px 0; text-align: left;
  134. }}
  135. .packages ul {{ margin: 0; padding-left: 20px; }}
  136. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  137. .command {{
  138. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  139. margin: 15px 0; font-family: monospace; color: #4ade80;
  140. text-align: left; overflow-x: auto;
  141. }}
  142. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  143. </style>
  144. </head>
  145. <body>
  146. <div class="container">
  147. <h1>Setup Required</h1>
  148. <h2>Missing Python packages</h2>
  149. <div class="packages"><ul>{packages_html}</ul></div>
  150. <p>To fix, run this command on your server:</p>
  151. <div class="command">pip install -r requirements.txt</div>
  152. <p>Or if using a virtual environment:</p>
  153. <div class="command">./venv/bin/pip install -r requirements.txt</div>
  154. <p class="note">After installing, restart Bambuddy:<br>
  155. <code>sudo systemctl restart bambuddy</code></p>
  156. </div>
  157. </body>
  158. </html>"""
  159. class ErrorHandler(BaseHTTPRequestHandler):
  160. def do_GET(self):
  161. self.send_response(503)
  162. self.send_header("Content-type", "text/html")
  163. self.end_headers()
  164. self.wfile.write(html.encode())
  165. def log_message(self, format, *args):
  166. print(f"[Error Server] {args[0]}")
  167. port = int(os.environ.get("PORT", 8000))
  168. print(f"\nStarting error server on http://0.0.0.0:{port}")
  169. print("Visit this URL in your browser to see the error details.\n")
  170. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  171. def shutdown(signum, frame):
  172. print("\nShutting down error server...")
  173. raise SystemExit(0)
  174. signal.signal(signal.SIGTERM, shutdown)
  175. signal.signal(signal.SIGINT, shutdown)
  176. server.serve_forever()
  177. def check_dependencies():
  178. """Check that all required packages are installed."""
  179. missing = []
  180. # Map of import name -> package name (for pip install)
  181. required = {
  182. "jwt": "PyJWT",
  183. "fastapi": "fastapi",
  184. "uvicorn": "uvicorn",
  185. "sqlalchemy": "sqlalchemy",
  186. "aiosqlite": "aiosqlite",
  187. "pydantic": "pydantic",
  188. "paho.mqtt": "paho-mqtt",
  189. }
  190. for module, package in required.items():
  191. try:
  192. __import__(module)
  193. except ImportError:
  194. missing.append(package)
  195. if missing:
  196. print("\n" + "=" * 60)
  197. print("ERROR: Missing required Python packages!")
  198. print("=" * 60)
  199. print(f"\nMissing packages: {', '.join(missing)}")
  200. print("\nTo fix, run:")
  201. print(" pip install -r requirements.txt")
  202. print("\nOr if using a virtual environment:")
  203. print(" ./venv/bin/pip install -r requirements.txt")
  204. print("=" * 60 + "\n")
  205. _start_error_server(missing)
  206. check_dependencies()
  207. # =============================================================================
  208. # Import settings first for logging configuration
  209. # Configure logging based on settings
  210. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  211. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  212. log_level = getattr(logging, log_level_str, logging.INFO)
  213. log_format = "%(asctime)s %(levelname)s [%(name)s] %(message)s"
  214. # Create root logger
  215. root_logger = logging.getLogger()
  216. root_logger.setLevel(log_level)
  217. # Console handler - always enabled
  218. console_handler = logging.StreamHandler()
  219. console_handler.setLevel(log_level)
  220. console_handler.setFormatter(logging.Formatter(log_format))
  221. root_logger.addHandler(console_handler)
  222. # File handler - only in production or if explicitly enabled
  223. if app_settings.log_to_file:
  224. log_file = app_settings.log_dir / "bambuddy.log"
  225. file_handler = RotatingFileHandler(
  226. log_file,
  227. maxBytes=5 * 1024 * 1024, # 5MB
  228. backupCount=3,
  229. encoding="utf-8",
  230. )
  231. file_handler.setLevel(log_level)
  232. file_handler.setFormatter(logging.Formatter(log_format))
  233. root_logger.addHandler(file_handler)
  234. logging.info("Logging to file: %s", log_file)
  235. # Reduce noise from third-party libraries in production
  236. if not app_settings.debug:
  237. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  238. logging.getLogger("httpcore").setLevel(logging.WARNING)
  239. logging.getLogger("httpx").setLevel(logging.WARNING)
  240. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  241. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  242. # Track active prints: {(printer_id, filename): archive_id}
  243. _active_prints: dict[tuple[int, str], int] = {}
  244. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  245. # {(printer_id, filename): archive_id}
  246. _expected_prints: dict[tuple[int, str], int] = {}
  247. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  248. # Used by usage tracker to map 3MF slots to physical AMS trays
  249. _print_ams_mappings: dict[int, list[int]] = {}
  250. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  251. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  252. _last_progress_milestone: dict[int, int] = {}
  253. # Track whether first layer complete notification has been sent for current print
  254. _first_layer_notified: dict[int, bool] = {}
  255. # Track HMS errors that have been notified: {printer_id: set of error codes}
  256. # This prevents sending duplicate notifications for the same error
  257. _notified_hms_errors: dict[int, set[str]] = {}
  258. # Track when HMS errors were last seen: {printer_id: timestamp}
  259. # Used to debounce clearing — prevents flapping errors from re-triggering notifications
  260. _hms_last_seen: dict[int, float] = {}
  261. _HMS_CLEAR_GRACE_SECONDS = 30.0
  262. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  263. # Used for snapshot-diff detection at print completion
  264. _timelapse_baselines: dict[int, set[str]] = {}
  265. # Track printers waiting for bed to cool after print completion.
  266. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  267. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  268. _bed_cool_waiters: dict[int, dict] = {}
  269. # Track printers where the user explicitly stopped the print from the queue UI.
  270. # When on_print_complete fires with status "failed" for these printers we treat it
  271. # as "cancelled" (stopped by user) so the correct notification email is sent.
  272. _user_stopped_printers: set[int] = set()
  273. # Track created_by_id for expected prints so the user email can be sent even when
  274. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  275. # {(printer_id, filename): created_by_id}
  276. _expected_print_creators: dict[tuple[int, str], int] = {}
  277. # TTL for expected-print entries: evict registrations older than this to prevent
  278. # unbounded growth when a print is registered but never starts (e.g. printer
  279. # disconnect, app restart, print started from the printer panel).
  280. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  281. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  282. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  283. # Cleanup loop interval
  284. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  285. _expected_prints_cleanup_task: asyncio.Task | None = None
  286. async def _get_plug_energy(plug, db) -> dict | None:
  287. """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
  288. For HA plugs, configures the service with current settings from DB.
  289. For MQTT plugs, returns data from the subscription service.
  290. For REST plugs, polls the status URL with JSON path extraction.
  291. """
  292. if plug.plug_type == "homeassistant":
  293. from backend.app.api.routes.settings import get_homeassistant_settings
  294. ha_settings = await get_homeassistant_settings(db)
  295. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  296. return await homeassistant_service.get_energy(plug)
  297. elif plug.plug_type == "mqtt":
  298. # MQTT plugs report "today" energy, not lifetime total
  299. # For per-print tracking, we use "today" as the counter (resets at midnight)
  300. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  301. if mqtt_data:
  302. return {
  303. "power": mqtt_data.power,
  304. "today": mqtt_data.energy,
  305. "total": mqtt_data.energy, # Use today as total for per-print calculations
  306. }
  307. return None
  308. elif plug.plug_type == "rest":
  309. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  310. return await rest_smart_plug_service.get_energy(plug)
  311. else:
  312. return await tasmota_service.get_energy(plug)
  313. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  314. """Capture the smart plug lifetime counter on the archive at print start.
  315. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  316. tracking survives a backend restart mid-print. The print-end handler reads
  317. this value back from the DB and computes the delta against the current
  318. plug counter.
  319. """
  320. _logger = logging.getLogger(__name__)
  321. try:
  322. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  323. plug = plug_result.scalar_one_or_none()
  324. if not plug:
  325. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  326. return False
  327. energy = await _get_plug_energy(plug, db)
  328. if not energy or energy.get("total") is None:
  329. _logger.warning("[ENERGY] No 'total' in energy response for archive %s", archive.id)
  330. return False
  331. archive.energy_start_kwh = float(energy["total"])
  332. await db.commit()
  333. _logger.info(
  334. "[ENERGY] Recorded starting energy%s for archive %s: %s kWh",
  335. f" ({context})" if context else "",
  336. archive.id,
  337. energy["total"],
  338. )
  339. return True
  340. except Exception as e:
  341. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  342. return False
  343. def register_expected_print(
  344. printer_id: int,
  345. filename: str,
  346. archive_id: int,
  347. ams_mapping: list[int] | None = None,
  348. created_by_id: int | None = None,
  349. ):
  350. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  351. # Store with multiple filename variations to catch different naming patterns
  352. _expected_prints[(printer_id, filename)] = archive_id
  353. # Also store without .3mf extension if present
  354. if filename.endswith(".3mf"):
  355. base = filename[:-4]
  356. _expected_prints[(printer_id, base)] = archive_id
  357. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  358. # Store AMS mapping for usage tracking at print completion
  359. if ams_mapping is not None:
  360. _print_ams_mappings[archive_id] = ams_mapping
  361. # Store created_by_id so the user start email can be sent even when the archive
  362. # itself has no created_by_id (e.g. library-file-based queue prints)
  363. if created_by_id is not None:
  364. _expected_print_creators[(printer_id, filename)] = created_by_id
  365. if filename.endswith(".3mf"):
  366. base = filename[:-4]
  367. _expected_print_creators[(printer_id, base)] = created_by_id
  368. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  369. # Record registration time for TTL-based eviction
  370. _registered_at = time.monotonic()
  371. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  372. if filename.endswith(".3mf"):
  373. base = filename[:-4]
  374. _expected_print_registered_at[(printer_id, base)] = _registered_at
  375. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  376. logging.getLogger(__name__).info(
  377. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}"
  378. )
  379. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  380. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  381. stored_ams_mapping = data.get("ams_mapping")
  382. if not stored_ams_mapping and archive_id:
  383. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  384. return stored_ams_mapping
  385. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  386. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  387. print completes successfully. Gated to status=='completed': failed, cancelled
  388. and aborted prints do not count as usage. Caller is responsible for committing
  389. the session. No-op when the queue item has no linked library file (e.g. reprints
  390. from an archive). See #1008."""
  391. if queue_status != "completed" or item.library_file_id is None:
  392. return
  393. from backend.app.models.library import LibraryFile
  394. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  395. if lib_file is None:
  396. return
  397. lib_file.print_count = (lib_file.print_count or 0) + 1
  398. lib_file.last_printed_at = datetime.now(timezone.utc)
  399. def mark_printer_stopped_by_user(printer_id: int) -> None:
  400. """Mark that the active print on this printer was stopped by the user from the queue UI.
  401. When on_print_complete fires with status 'failed' for a printer in this set we
  402. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  403. rather than a 'print failed' notification.
  404. """
  405. _user_stopped_printers.add(printer_id)
  406. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  407. _last_status_broadcast: dict[int, str] = {}
  408. # Track printers where we've updated nozzle_count
  409. _nozzle_count_updated: set[int] = set()
  410. async def on_printer_status_change(printer_id: int, state: PrinterState):
  411. """Handle printer status changes - broadcast via WebSocket."""
  412. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  413. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  414. temps = state.temperatures or {}
  415. nozzle_temp = round(temps.get("nozzle", 0))
  416. bed_temp = round(temps.get("bed", 0))
  417. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  418. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  419. # Auto-detect dual-nozzle printers from MQTT temperature data
  420. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  421. _nozzle_count_updated.add(printer_id)
  422. # Update nozzle_count in database
  423. async with async_session() as db:
  424. from backend.app.models.printer import Printer
  425. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  426. printer = result.scalar_one_or_none()
  427. if printer and printer.nozzle_count != 2:
  428. printer.nozzle_count = 2
  429. await db.commit()
  430. logging.getLogger(__name__).info(
  431. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  432. )
  433. # Include target temps for heating phase detection
  434. bed_target = round(temps.get("bed_target", 0))
  435. nozzle_target = round(temps.get("nozzle_target", 0))
  436. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  437. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  438. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts
  439. ams_dry_key = tuple(a.get("dry_time", 0) for a in (state.raw_data.get("ams") or [])) if state.raw_data else ()
  440. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  441. ams_tray_key = (
  442. tuple(
  443. (t.get("id"), t.get("tray_type", ""), t.get("state"))
  444. for a in (state.raw_data.get("ams") or [])
  445. for t in a.get("tray", [])
  446. )
  447. if state.raw_data
  448. else ()
  449. )
  450. status_key = (
  451. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  452. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  453. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  454. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  455. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  456. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}"
  457. )
  458. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  459. try:
  460. printer_info = printer_manager.get_printer(printer_id)
  461. if printer_info:
  462. await mqtt_relay.on_printer_status(printer_id, state, printer_info.name, printer_info.serial_number)
  463. except Exception:
  464. pass # Don't fail status callback if MQTT fails
  465. if _last_status_broadcast.get(printer_id) == status_key:
  466. return # No change, skip WebSocket broadcast
  467. _last_status_broadcast[printer_id] = status_key
  468. # Check for progress milestone notifications (25%, 50%, 75%)
  469. progress = state.progress or 0
  470. is_printing = state.state in ("RUNNING", "PRINTING")
  471. if is_printing and progress > 0:
  472. # Determine which milestone we've reached
  473. current_milestone = 0
  474. if progress >= 75:
  475. current_milestone = 75
  476. elif progress >= 50:
  477. current_milestone = 50
  478. elif progress >= 25:
  479. current_milestone = 25
  480. last_milestone = _last_progress_milestone.get(printer_id, 0)
  481. # If we've crossed a new milestone, send notification
  482. if current_milestone > last_milestone:
  483. _last_progress_milestone[printer_id] = current_milestone
  484. try:
  485. async with async_session() as db:
  486. from backend.app.models.printer import Printer
  487. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  488. printer = result.scalar_one_or_none()
  489. printer_name = printer.name if printer else f"Printer {printer_id}"
  490. filename = state.subtask_name or state.gcode_file or "Unknown"
  491. # remaining_time is in minutes, convert to seconds for notification
  492. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  493. # Capture camera snapshot for notification image attachment
  494. image_data = await _capture_snapshot_for_notification(
  495. printer_id, printer, logging.getLogger(__name__)
  496. )
  497. await notification_service.on_print_progress(
  498. printer_id,
  499. printer_name,
  500. filename,
  501. current_milestone,
  502. db,
  503. remaining_time_seconds,
  504. image_data=image_data,
  505. )
  506. except Exception as e:
  507. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  508. elif progress < 5:
  509. # Reset milestone tracking when print restarts or new print begins
  510. _last_progress_milestone[printer_id] = 0
  511. _first_layer_notified[printer_id] = False
  512. # HMS error codes that should not trigger notifications even though they
  513. # have known descriptions (e.g. user-initiated actions, not real errors).
  514. _HMS_NOTIFICATION_SUPPRESS = {
  515. "0500_400E", # Printing was cancelled (user action, not an error)
  516. }
  517. # Check for new HMS errors and send notifications
  518. current_hms_errors = getattr(state, "hms_errors", []) or []
  519. if current_hms_errors:
  520. # Build set of current error codes (using attr for uniqueness)
  521. current_error_codes = {f"{e.attr:08x}" for e in current_hms_errors}
  522. previously_notified = _notified_hms_errors.get(printer_id, set())
  523. # Find new errors that haven't been notified yet
  524. new_error_codes = current_error_codes - previously_notified
  525. # Update tracking immediately to prevent duplicate notifications from concurrent callbacks
  526. _notified_hms_errors[printer_id] = current_error_codes
  527. _hms_last_seen[printer_id] = time.time()
  528. if new_error_codes:
  529. # Get the actual new errors for the notification
  530. # Filter to severity >= 2 (skip informational/status messages like H2D sends)
  531. new_errors = [e for e in current_hms_errors if f"{e.attr:08x}" in new_error_codes and e.severity >= 2]
  532. try:
  533. async with async_session() as db:
  534. from backend.app.models.printer import Printer
  535. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  536. printer = result.scalar_one_or_none()
  537. printer_name = printer.name if printer else f"Printer {printer_id}"
  538. # Format error details for notification
  539. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  540. module_names = {
  541. 0x03: "Print/Task",
  542. 0x05: "Nozzle/Extruder",
  543. 0x07: "AMS/Filament",
  544. 0x0C: "Motion Controller",
  545. 0x12: "Chamber",
  546. }
  547. from backend.app.services.hms_errors import get_error_description
  548. # Capture camera snapshot once for all error notifications
  549. error_image_data = await _capture_snapshot_for_notification(
  550. printer_id, printer, logging.getLogger(__name__)
  551. )
  552. sent_count = 0
  553. for error in new_errors:
  554. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  555. # Build short code like "0700_8010"
  556. # Mask to 16 bits to handle printers that send larger values
  557. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  558. error_code_masked = error_code_int & 0xFFFF
  559. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  560. # Only notify for errors with known descriptions — printers
  561. # send many undocumented/phantom codes that aren't real errors.
  562. description = get_error_description(short_code)
  563. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  564. continue
  565. error_type = f"{module_name} Error"
  566. error_detail = description
  567. await notification_service.on_printer_error(
  568. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  569. )
  570. sent_count += 1
  571. if sent_count:
  572. logging.getLogger(__name__).info(
  573. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  574. )
  575. # Also publish to MQTT relay
  576. printer_info = printer_manager.get_printer(printer_id)
  577. if printer_info:
  578. errors_data = [
  579. {
  580. "code": e.code,
  581. "attr": e.attr,
  582. "module": e.module,
  583. "severity": e.severity,
  584. }
  585. for e in new_errors
  586. ]
  587. await mqtt_relay.on_printer_error(
  588. printer_id, printer_info.name, printer_info.serial_number, errors_data
  589. )
  590. except Exception as e:
  591. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  592. else:
  593. # No HMS errors — only clear tracking after a grace period to prevent
  594. # flapping errors (brief hms:[] gaps) from re-triggering notifications.
  595. # Some HMS codes (e.g. chamber temp regulation during PETG prints) toggle
  596. # on/off every few seconds as conditions fluctuate around thresholds.
  597. if printer_id in _notified_hms_errors:
  598. last_seen = _hms_last_seen.get(printer_id, 0)
  599. if time.time() - last_seen >= _HMS_CLEAR_GRACE_SECONDS:
  600. _notified_hms_errors.pop(printer_id, None)
  601. _hms_last_seen.pop(printer_id, None)
  602. await ws_manager.send_printer_status(
  603. printer_id,
  604. printer_state_to_dict(state, printer_id, printer_manager.get_model(printer_id)),
  605. )
  606. def _is_bambu_uuid(tray_uuid: str) -> bool:
  607. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  608. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  609. async def on_ams_change(printer_id: int, ams_data: list):
  610. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  611. logger = logging.getLogger(__name__)
  612. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  613. # on_print_complete may pop _active_sessions during our awaits (#880).
  614. from backend.app.services.usage_tracker import _active_sessions
  615. _print_active = printer_id in _active_sessions
  616. # MQTT relay - publish AMS change
  617. try:
  618. printer_info = printer_manager.get_printer(printer_id)
  619. if printer_info:
  620. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  621. except Exception:
  622. pass # Don't fail AMS callback if MQTT fails
  623. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  624. # This ensures frontend gets immediate updates when AMS slots are configured
  625. try:
  626. state = printer_manager.get_status(printer_id)
  627. if state:
  628. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  629. await ws_manager.send_printer_status(
  630. printer_id,
  631. printer_state_to_dict(state, printer_id, printer_manager.get_model(printer_id)),
  632. )
  633. except Exception as e:
  634. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  635. from backend.app.utils.color_utils import colors_similar as _colors_similar
  636. # Auto-unlink spool assignments with stale fingerprints
  637. try:
  638. async with async_session() as db:
  639. from sqlalchemy.orm import selectinload
  640. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  641. from backend.app.models.spool_assignment import SpoolAssignment as SA
  642. result = await db.execute(select(SA).where(SA.printer_id == printer_id).options(selectinload(SA.spool)))
  643. stale = []
  644. for assignment in result.scalars().all():
  645. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  646. if assignment.ams_id == 255:
  647. ps = printer_manager.get_status(printer_id)
  648. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  649. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  650. current_tray = None
  651. for vt in vt_tray_raw:
  652. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  653. current_tray = vt
  654. break
  655. if not current_tray:
  656. # vt_tray data may not have arrived yet — keep assignment
  657. continue
  658. else:
  659. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  660. if not current_tray:
  661. logger.info(
  662. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  663. assignment.spool_id,
  664. assignment.ams_id,
  665. assignment.tray_id,
  666. )
  667. stale.append(assignment) # Slot empty
  668. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  669. # A Bambu Lab spool is in this slot — check if it's the same spool
  670. # that's currently assigned. If yes, keep the assignment (avoids
  671. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  672. # the printer's filament preset on every startup).
  673. tray_uuid = current_tray.get("tray_uuid", "")
  674. tag_uid = current_tray.get("tag_uid", "")
  675. spool = assignment.spool
  676. spool_matches = False
  677. if spool:
  678. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  679. spool.tag_uid
  680. and tag_uid
  681. and tag_uid != "0000000000000000"
  682. and spool.tag_uid.upper() == tag_uid.upper()
  683. ):
  684. spool_matches = True
  685. if spool_matches:
  686. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  687. cur_color = current_tray.get("tray_color", "")
  688. cur_type = current_tray.get("tray_type", "")
  689. fp_color = assignment.fingerprint_color or ""
  690. fp_type = assignment.fingerprint_type or ""
  691. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  692. assignment.fingerprint_color = cur_color
  693. assignment.fingerprint_type = cur_type
  694. logger.debug(
  695. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  696. assignment.spool_id,
  697. assignment.ams_id,
  698. assignment.tray_id,
  699. )
  700. continue
  701. # Different BL spool or unrecognized — unlink so auto-assign can match
  702. logger.info(
  703. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  704. assignment.spool_id,
  705. assignment.ams_id,
  706. assignment.tray_id,
  707. tray_uuid,
  708. )
  709. stale.append(assignment)
  710. else:
  711. cur_color = current_tray.get("tray_color", "")
  712. cur_type = current_tray.get("tray_type", "")
  713. fp_color = assignment.fingerprint_color or ""
  714. fp_type = assignment.fingerprint_type or ""
  715. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  716. # Fingerprint mismatch — but check if tray now matches the
  717. # assigned spool (e.g. auto-configure changed the tray).
  718. spool = assignment.spool
  719. if spool:
  720. spool_color = (spool.rgba or "FFFFFFFF").upper()
  721. spool_type = (spool.material or "").upper()
  722. if _colors_similar(cur_color, spool_color) and cur_type.upper() == spool_type:
  723. # Tray was reconfigured to match the spool — update fingerprint
  724. logger.info(
  725. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  726. assignment.spool_id,
  727. assignment.ams_id,
  728. assignment.tray_id,
  729. )
  730. assignment.fingerprint_color = cur_color
  731. assignment.fingerprint_type = cur_type
  732. continue
  733. logger.info(
  734. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  735. assignment.spool_id,
  736. assignment.ams_id,
  737. assignment.tray_id,
  738. cur_color,
  739. cur_type,
  740. fp_color,
  741. fp_type,
  742. spool.rgba if spool else "?",
  743. spool.material if spool else "?",
  744. )
  745. stale.append(assignment) # Spool changed
  746. for a in stale:
  747. await db.delete(a)
  748. if stale:
  749. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  750. # Commit any changes (stale deletions and/or fingerprint updates)
  751. await db.commit()
  752. except Exception as e:
  753. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  754. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS)
  755. try:
  756. async with async_session() as db:
  757. from backend.app.api.routes.settings import get_setting
  758. from backend.app.models.spool_assignment import SpoolAssignment as SA
  759. from backend.app.services.spool_tag_matcher import (
  760. auto_assign_spool,
  761. create_spool_from_tray,
  762. find_matching_untagged_spool,
  763. get_spool_by_tag,
  764. is_bambu_tag,
  765. is_valid_tag,
  766. link_tag_to_inventory_spool,
  767. )
  768. _spoolman_on = await get_setting(db, "spoolman_enabled")
  769. if not _spoolman_on or _spoolman_on.lower() != "true":
  770. for ams_unit in ams_data:
  771. if not isinstance(ams_unit, dict):
  772. continue
  773. ams_id = int(ams_unit.get("id", 0))
  774. for tray in ams_unit.get("tray", []):
  775. if not isinstance(tray, dict):
  776. continue
  777. tray_id = int(tray.get("id", 0))
  778. tag_uid = tray.get("tag_uid", "")
  779. tray_uuid = tray.get("tray_uuid", "")
  780. tray_info_idx = tray.get("tray_info_idx", "")
  781. if not tray.get("tray_type"):
  782. continue # Empty slot
  783. # Check if assignment already exists for this slot
  784. existing = await db.execute(
  785. select(SA)
  786. .options(selectinload(SA.spool))
  787. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  788. )
  789. existing_assignment = existing.scalar_one_or_none()
  790. if existing_assignment:
  791. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  792. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  793. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  794. # Skip during active prints: the usage tracker handles deduction
  795. # precisely via 3MF data on print completion. Without this guard the
  796. # AMS remain% SET and the usage tracker ADD both fire from the same
  797. # MQTT message, doubling the deduction (#880).
  798. if _print_active:
  799. continue
  800. remain_raw = tray.get("remain")
  801. if (
  802. remain_raw is not None
  803. and existing_assignment.spool
  804. and not existing_assignment.spool.weight_locked
  805. ):
  806. try:
  807. remain_val = int(remain_raw)
  808. except (TypeError, ValueError):
  809. remain_val = -1
  810. if 1 <= remain_val <= 100:
  811. lw = existing_assignment.spool.label_weight or 1000
  812. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  813. current_used = existing_assignment.spool.weight_used or 0
  814. if new_used > current_used + 1:
  815. logger.info(
  816. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  817. existing_assignment.spool_id,
  818. current_used,
  819. new_used,
  820. remain_val,
  821. )
  822. existing_assignment.spool.weight_used = new_used
  823. await db.commit()
  824. continue
  825. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  826. # BL spool with RFID tag: auto-match → inventory match → auto-create
  827. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  828. if not spool:
  829. # Try matching an untagged inventory spool (same material/color)
  830. spool = await find_matching_untagged_spool(db, tray)
  831. if spool:
  832. await link_tag_to_inventory_spool(db, spool, tray)
  833. else:
  834. spool = await create_spool_from_tray(db, tray)
  835. await auto_assign_spool(
  836. printer_id,
  837. ams_id,
  838. tray_id,
  839. spool,
  840. printer_manager,
  841. db,
  842. tray_info_idx=tray_info_idx,
  843. )
  844. await db.commit()
  845. await ws_manager.broadcast(
  846. {
  847. "type": "spool_auto_assigned",
  848. "printer_id": printer_id,
  849. "ams_id": ams_id,
  850. "tray_id": tray_id,
  851. "spool_id": spool.id,
  852. }
  853. )
  854. logger.info(
  855. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  856. spool.id,
  857. printer_id,
  858. ams_id,
  859. tray_id,
  860. )
  861. elif is_valid_tag(tag_uid, tray_uuid):
  862. # Non-BL spool with some tag — let user choose
  863. await ws_manager.broadcast(
  864. {
  865. "type": "unknown_tag",
  866. "printer_id": printer_id,
  867. "ams_id": ams_id,
  868. "tray_id": tray_id,
  869. "tag_uid": tag_uid,
  870. "tray_uuid": tray_uuid,
  871. }
  872. )
  873. else:
  874. # No tag at all — let user choose from inventory
  875. await ws_manager.broadcast(
  876. {
  877. "type": "unknown_tag",
  878. "printer_id": printer_id,
  879. "ams_id": ams_id,
  880. "tray_id": tray_id,
  881. "tag_uid": "",
  882. "tray_uuid": "",
  883. }
  884. )
  885. except Exception as e:
  886. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  887. try:
  888. async with async_session() as db:
  889. from backend.app.api.routes.settings import get_setting
  890. from backend.app.models.printer import Printer
  891. # Check if Spoolman is enabled
  892. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  893. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  894. return
  895. # Check sync mode
  896. sync_mode = await get_setting(db, "spoolman_sync_mode")
  897. if sync_mode and sync_mode != "auto":
  898. return # Only sync on auto mode
  899. # Check if weight sync is disabled
  900. disable_weight_sync_str = await get_setting(db, "spoolman_disable_weight_sync")
  901. disable_weight_sync = disable_weight_sync_str and disable_weight_sync_str.lower() == "true"
  902. # Get Spoolman URL
  903. spoolman_url = await get_setting(db, "spoolman_url")
  904. if not spoolman_url:
  905. return
  906. # Get or create Spoolman client
  907. client = await get_spoolman_client()
  908. if not client:
  909. client = await init_spoolman_client(spoolman_url)
  910. # Check if Spoolman is reachable
  911. if not await client.health_check():
  912. logger.warning("Spoolman not reachable at %s", spoolman_url)
  913. return
  914. # Get printer name for location
  915. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  916. printer = result.scalar_one_or_none()
  917. printer_name = printer.name if printer else f"Printer {printer_id}"
  918. # OPTIMIZATION: Fetch all spools once before processing trays
  919. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  920. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  921. try:
  922. cached_spools = await client.get_spools()
  923. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  924. except Exception as e:
  925. logger.error(
  926. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  927. printer_id,
  928. e,
  929. )
  930. return
  931. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  932. from sqlalchemy.orm import selectinload
  933. from backend.app.models.spool_assignment import SpoolAssignment
  934. inventory_weights: dict[tuple[int, int], float] = {}
  935. try:
  936. assign_result = await db.execute(
  937. select(SpoolAssignment)
  938. .options(selectinload(SpoolAssignment.spool))
  939. .where(SpoolAssignment.printer_id == printer_id)
  940. )
  941. for assignment in assign_result.scalars().all():
  942. spool = assignment.spool
  943. if spool and spool.label_weight > 0:
  944. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  945. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  946. except Exception as e:
  947. logger.debug("Could not load inventory weights for printer %s: %s", printer_id, e)
  948. # Sync each AMS tray, tracking UUIDs and spool IDs for cleanup
  949. synced = 0
  950. current_tray_uuids: set[str] = set()
  951. synced_spool_ids: set[int] = set()
  952. for ams_unit in ams_data:
  953. ams_id = int(ams_unit.get("id", 0))
  954. trays = ams_unit.get("tray", [])
  955. for tray_data in trays:
  956. tray = client.parse_ams_tray(ams_id, tray_data)
  957. if not tray:
  958. continue # Empty tray
  959. # Track this spool's UUID as currently present in the AMS
  960. spool_tag = (
  961. tray.tray_uuid
  962. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  963. else tray.tag_uid
  964. )
  965. if spool_tag:
  966. current_tray_uuids.add(spool_tag.upper())
  967. try:
  968. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  969. result = await client.sync_ams_tray(
  970. tray,
  971. printer_name,
  972. disable_weight_sync=disable_weight_sync,
  973. cached_spools=cached_spools,
  974. inventory_remaining=inv_remaining,
  975. )
  976. if result:
  977. synced += 1
  978. if result.get("id"):
  979. synced_spool_ids.add(result["id"])
  980. # If a new spool was created, add it to the cache
  981. # so subsequent trays can find it if they reference the same tag
  982. # Check if this spool already exists in cache
  983. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  984. if not spool_exists:
  985. cached_spools.append(result)
  986. logger.debug(
  987. "[Printer %s] Added newly created spool %s to cache",
  988. printer_id,
  989. result["id"],
  990. )
  991. except Exception as e:
  992. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  993. if synced > 0:
  994. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  995. # Clear location for spools no longer in this printer's AMS
  996. try:
  997. cleared = await client.clear_location_for_removed_spools(
  998. printer_name, current_tray_uuids, cached_spools=cached_spools, synced_spool_ids=synced_spool_ids
  999. )
  1000. if cleared > 0:
  1001. logger.info("Auto-cleared location for %s spools removed from printer %s", cleared, printer_id)
  1002. except Exception as e:
  1003. logger.error("Error clearing locations for removed spools on printer %s: %s", printer_id, e)
  1004. except Exception as e:
  1005. logging.getLogger(__name__).warning(f"Spoolman AMS sync failed: {e}")
  1006. async def _capture_snapshot_for_notification(printer_id: int, printer, logger) -> bytes | None:
  1007. """Capture a camera snapshot for notification image attachment.
  1008. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  1009. Uses: external camera > buffered frame > fresh capture.
  1010. """
  1011. if not printer:
  1012. return None
  1013. try:
  1014. from backend.app.api.routes.settings import get_setting
  1015. async with async_session() as db:
  1016. capture_enabled = await get_setting(db, "capture_finish_photo")
  1017. if capture_enabled is not None and capture_enabled.lower() != "true":
  1018. return None
  1019. # Try external camera first
  1020. if printer.external_camera_enabled and printer.external_camera_url:
  1021. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  1022. from backend.app.services.external_camera import capture_frame
  1023. frame_data = await capture_frame(printer.external_camera_url, printer.external_camera_type or "mjpeg")
  1024. if frame_data and len(frame_data) <= 2_500_000:
  1025. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  1026. return _apply_camera_rotation(frame_data, printer, logger)
  1027. # Try buffered frame from active stream
  1028. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  1029. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  1030. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  1031. buffered_frame = get_buffered_frame(printer_id)
  1032. if (active_for_printer or active_chamber) and buffered_frame:
  1033. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  1034. if len(buffered_frame) <= 2_500_000:
  1035. return _apply_camera_rotation(buffered_frame, printer, logger)
  1036. # Fresh capture from printer camera
  1037. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  1038. from backend.app.services.camera import capture_camera_frame_bytes
  1039. frame_data = await capture_camera_frame_bytes(
  1040. printer.ip_address, printer.access_code, printer.model, timeout=15
  1041. )
  1042. if frame_data and len(frame_data) <= 2_500_000:
  1043. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  1044. return _apply_camera_rotation(frame_data, printer, logger)
  1045. except Exception as e:
  1046. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  1047. return None
  1048. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  1049. """Apply camera rotation to snapshot image if configured."""
  1050. rotation = getattr(printer, "camera_rotation", 0)
  1051. if not rotation or rotation == 0:
  1052. return image_data
  1053. try:
  1054. from io import BytesIO
  1055. from PIL import Image
  1056. img = Image.open(BytesIO(image_data))
  1057. # PIL rotate is counter-clockwise, so negate for clockwise rotation
  1058. img = img.rotate(-rotation, expand=True)
  1059. buf = BytesIO()
  1060. img.save(buf, format="JPEG", quality=90)
  1061. rotated = buf.getvalue()
  1062. logger.info("[SNAPSHOT] Applied %d° rotation: %s → %s bytes", rotation, len(image_data), len(rotated))
  1063. return rotated
  1064. except Exception as e:
  1065. logger.warning("[SNAPSHOT] Failed to apply rotation: %s", e)
  1066. return image_data
  1067. async def _send_print_start_notification(
  1068. printer_id: int,
  1069. data: dict,
  1070. archive_data: dict | None = None,
  1071. logger=None,
  1072. ):
  1073. """Helper to send print start notification with optional archive data."""
  1074. if logger is None:
  1075. logger = logging.getLogger(__name__)
  1076. try:
  1077. async with async_session() as db:
  1078. from backend.app.models.printer import Printer
  1079. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1080. printer = result.scalar_one_or_none()
  1081. printer_name = printer.name if printer else f"Printer {printer_id}"
  1082. # Capture camera snapshot for notification image attachment
  1083. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  1084. if image_data:
  1085. if archive_data is None:
  1086. archive_data = {}
  1087. archive_data["image_data"] = image_data
  1088. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  1089. # Send user-specific email notification for print start
  1090. if archive_data and archive_data.get("created_by_id"):
  1091. await notification_service.send_user_print_email(
  1092. event_type="user_print_start",
  1093. created_by_id=archive_data["created_by_id"],
  1094. printer_name=printer_name,
  1095. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  1096. db=db,
  1097. )
  1098. except Exception as e:
  1099. logger.warning("Notification on_print_start failed: %s", e)
  1100. async def _dispatch_user_print_email(
  1101. status: str,
  1102. created_by_id: int | None,
  1103. printer_name: str,
  1104. filename: str,
  1105. db,
  1106. ) -> None:
  1107. """Send a user-specific print-completion email based on print status.
  1108. Maps the normalised print status to the correct event type and delegates
  1109. to :meth:`NotificationService.send_user_print_email`. A single helper
  1110. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  1111. "stopped"`` dispatch block at every call site.
  1112. Does nothing if *created_by_id* is ``None``.
  1113. """
  1114. if created_by_id is None:
  1115. return
  1116. if status == "completed":
  1117. event_type = "user_print_complete"
  1118. elif status == "failed":
  1119. event_type = "user_print_failed"
  1120. elif status in ("stopped", "aborted", "cancelled"):
  1121. event_type = "user_print_stopped"
  1122. else:
  1123. return
  1124. await notification_service.send_user_print_email(
  1125. event_type=event_type,
  1126. created_by_id=created_by_id,
  1127. printer_name=printer_name,
  1128. filename=filename,
  1129. db=db,
  1130. )
  1131. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  1132. """Extract printable objects from an archive's 3MF file and store in printer state."""
  1133. try:
  1134. from backend.app.services.archive import extract_printable_objects_from_3mf
  1135. file_path = app_settings.base_dir / archive.file_path
  1136. if file_path.is_file() and str(file_path).endswith(".3mf"):
  1137. with open(file_path, "rb") as f:
  1138. threemf_data = f.read()
  1139. # Extract with positions for UI overlay
  1140. printable_objects, bbox_all = extract_printable_objects_from_3mf(threemf_data, include_positions=True)
  1141. if printable_objects:
  1142. client = printer_manager.get_client(printer_id)
  1143. if client:
  1144. client.state.printable_objects = printable_objects
  1145. client.state.printable_objects_bbox_all = bbox_all
  1146. client.state.skipped_objects = []
  1147. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  1148. except Exception as e:
  1149. logger.debug("Failed to extract printable objects from archive: %s", e)
  1150. async def on_print_start(printer_id: int, data: dict):
  1151. """Handle print start - archive the 3MF file immediately."""
  1152. logger = logging.getLogger(__name__)
  1153. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  1154. # Clear any stale user-stopped flag from previous print cycles
  1155. _user_stopped_printers.discard(printer_id)
  1156. # Cancel any active bed cooldown waiter for this printer
  1157. if _bed_cool_waiters.pop(printer_id, None):
  1158. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  1159. # Clear cached cover images so the new print's thumbnail is fetched fresh
  1160. from backend.app.api.routes.printers import clear_cover_cache
  1161. clear_cover_cache(printer_id)
  1162. await ws_manager.send_print_start(printer_id, data)
  1163. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  1164. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  1165. # MQTT relay - publish print start
  1166. try:
  1167. printer_info = printer_manager.get_printer(printer_id)
  1168. if printer_info:
  1169. await mqtt_relay.on_print_start(
  1170. printer_id,
  1171. printer_info.name,
  1172. printer_info.serial_number,
  1173. data.get("filename", ""),
  1174. data.get("subtask_name", ""),
  1175. )
  1176. except Exception:
  1177. pass # Don't fail print start callback if MQTT fails
  1178. # Capture AMS tray remain% for filament consumption tracking (skip if Spoolman handles usage)
  1179. try:
  1180. async with async_session() as db:
  1181. from backend.app.api.routes.settings import get_setting
  1182. _spoolman_on = await get_setting(db, "spoolman_enabled")
  1183. if not _spoolman_on or _spoolman_on.lower() != "true":
  1184. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  1185. await usage_on_print_start(printer_id, data, printer_manager, db=db)
  1186. except Exception as e:
  1187. logger.warning("Usage tracker on_print_start failed: %s", e)
  1188. # Track if notification was sent (to avoid sending twice)
  1189. notification_sent = False
  1190. # Smart plug automation: turn on plug when print starts
  1191. try:
  1192. async with async_session() as db:
  1193. await smart_plug_manager.on_print_start(printer_id, db)
  1194. except Exception as e:
  1195. logger.warning("Smart plug on_print_start failed: %s", e)
  1196. async with async_session() as db:
  1197. from backend.app.models.printer import Printer
  1198. from backend.app.services.bambu_ftp import list_files_async
  1199. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1200. printer = result.scalar_one_or_none()
  1201. # Plate detection check - pause if objects detected on build plate
  1202. logger.info(
  1203. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  1204. )
  1205. if printer and printer.plate_detection_enabled:
  1206. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  1207. try:
  1208. from backend.app.services.plate_detection import check_plate_empty
  1209. # Build ROI tuple from printer settings if available
  1210. roi = None
  1211. if all(
  1212. [
  1213. printer.plate_detection_roi_x is not None,
  1214. printer.plate_detection_roi_y is not None,
  1215. printer.plate_detection_roi_w is not None,
  1216. printer.plate_detection_roi_h is not None,
  1217. ]
  1218. ):
  1219. roi = (
  1220. printer.plate_detection_roi_x,
  1221. printer.plate_detection_roi_y,
  1222. printer.plate_detection_roi_w,
  1223. printer.plate_detection_roi_h,
  1224. )
  1225. # Auto-turn on chamber light if it's off for better detection
  1226. light_was_off = False
  1227. client = printer_manager.get_client(printer_id)
  1228. if client and client.state:
  1229. light_was_off = not client.state.chamber_light
  1230. if light_was_off:
  1231. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  1232. client.set_chamber_light(True)
  1233. # Wait for light to physically turn on and camera to adjust exposure
  1234. await asyncio.sleep(2.5)
  1235. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  1236. plate_result = await check_plate_empty(
  1237. printer_id=printer_id,
  1238. ip_address=printer.ip_address,
  1239. access_code=printer.access_code,
  1240. model=printer.model,
  1241. include_debug_image=False,
  1242. external_camera_url=printer.external_camera_url,
  1243. external_camera_type=printer.external_camera_type,
  1244. use_external=printer.external_camera_enabled,
  1245. roi=roi,
  1246. )
  1247. # Restore chamber light to original state
  1248. if light_was_off and client:
  1249. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  1250. client.set_chamber_light(False)
  1251. if not plate_result.needs_calibration and not plate_result.is_empty:
  1252. # Objects detected - pause the print!
  1253. logger.warning(
  1254. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  1255. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  1256. )
  1257. client = printer_manager.get_client(printer_id)
  1258. if client:
  1259. client.pause_print()
  1260. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  1261. # Send notification about plate not empty
  1262. await ws_manager.broadcast(
  1263. {
  1264. "type": "plate_not_empty",
  1265. "printer_id": printer_id,
  1266. "printer_name": printer.name,
  1267. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  1268. }
  1269. )
  1270. # Also send push notification
  1271. try:
  1272. await notification_service.on_plate_not_empty(
  1273. printer_id=printer_id,
  1274. printer_name=printer.name,
  1275. db=db,
  1276. difference_percent=plate_result.difference_percent,
  1277. )
  1278. except Exception as notif_err:
  1279. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  1280. else:
  1281. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  1282. except Exception as plate_err:
  1283. # Don't block print on plate detection errors
  1284. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  1285. if not printer:
  1286. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  1287. if not notification_sent:
  1288. await _send_print_start_notification(printer_id, data, logger=logger)
  1289. return
  1290. if not printer.auto_archive:
  1291. # auto-archive disabled — check if there's an expected print (dispatched
  1292. # by BamBuddy via queue/reprint) that already has an archive to promote.
  1293. # If so, fall through to the expected-print handling below so the archive
  1294. # is tracked in _active_prints and usage tracking works at completion.
  1295. _fn = data.get("filename", "")
  1296. _sn = data.get("subtask_name", "")
  1297. _check_keys: list[tuple[int, str]] = []
  1298. if _sn:
  1299. _check_keys += [
  1300. (printer_id, _sn),
  1301. (printer_id, f"{_sn}.3mf"),
  1302. (printer_id, f"{_sn}.gcode.3mf"),
  1303. ]
  1304. if _fn:
  1305. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  1306. _check_keys.append((printer_id, _base_fn))
  1307. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  1308. _check_keys += [
  1309. (printer_id, _no_archive_base),
  1310. (printer_id, f"{_no_archive_base}.3mf"),
  1311. ]
  1312. _has_expected = any(k in _expected_prints for k in _check_keys)
  1313. if not _has_expected:
  1314. # No expected print — truly external print (started from slicer/touchscreen)
  1315. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  1316. if not notification_sent:
  1317. _no_archive_creator: int | None = None
  1318. for _key in _check_keys:
  1319. _expected_prints.pop(_key, None)
  1320. _expected_print_registered_at.pop(_key, None)
  1321. popped_creator = _expected_print_creators.pop(_key, None)
  1322. if _no_archive_creator is None:
  1323. _no_archive_creator = popped_creator
  1324. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  1325. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  1326. return
  1327. else:
  1328. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  1329. # Get the filename and subtask_name
  1330. filename = data.get("filename", "")
  1331. subtask_name = data.get("subtask_name", "")
  1332. # MQTT subtask_id uniquely identifies a print job on the printer. When
  1333. # present, it lets us match an archive across a backend restart (#972):
  1334. # same id → same print → resume the existing row instead of cancelling
  1335. # it and recreating from scratch (which loses started_at). Treat "0"
  1336. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  1337. raw_mqtt = data.get("raw_data") or {}
  1338. subtask_id = raw_mqtt.get("subtask_id")
  1339. if subtask_id is not None:
  1340. subtask_id = str(subtask_id).strip()
  1341. if subtask_id in ("", "0"):
  1342. subtask_id = None
  1343. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  1344. # Skip calibration prints — internal printer files should not be archived
  1345. # Bambu calibration gcode lives under /usr/ (e.g. /usr/etc/print/auto_cali_for_user.gcode)
  1346. if filename and filename.startswith("/usr/"):
  1347. logger.info("[CALLBACK] Skipping archive — internal printer file detected: %s", filename)
  1348. if not notification_sent:
  1349. await _send_print_start_notification(printer_id, data, logger=logger)
  1350. return
  1351. if not filename and not subtask_name:
  1352. # Send notification without archive data (no filename)
  1353. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  1354. if not notification_sent:
  1355. await _send_print_start_notification(printer_id, data, logger=logger)
  1356. return
  1357. # Check if this is an expected print from reprint/scheduled
  1358. # Build list of possible keys to check
  1359. expected_keys = []
  1360. if subtask_name:
  1361. expected_keys.append((printer_id, subtask_name))
  1362. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  1363. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  1364. if filename:
  1365. fname = filename.split("/")[-1] if "/" in filename else filename
  1366. expected_keys.append((printer_id, fname))
  1367. # Strip extensions to match
  1368. base = fname.replace(".gcode", "").replace(".3mf", "")
  1369. expected_keys.append((printer_id, base))
  1370. expected_keys.append((printer_id, f"{base}.3mf"))
  1371. expected_archive_id = None
  1372. for key in expected_keys:
  1373. expected_archive_id = _expected_prints.pop(key, None)
  1374. _expected_print_registered_at.pop(key, None)
  1375. if expected_archive_id:
  1376. # Clean up other possible keys for this print
  1377. for other_key in expected_keys:
  1378. _expected_prints.pop(other_key, None)
  1379. _expected_print_registered_at.pop(other_key, None)
  1380. break
  1381. if expected_archive_id:
  1382. # This is a reprint/scheduled print - use existing archive, don't create new one
  1383. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  1384. from backend.app.models.archive import PrintArchive
  1385. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  1386. archive = result.scalar_one_or_none()
  1387. if archive:
  1388. # Update archive status to printing
  1389. archive.status = "printing"
  1390. archive.started_at = datetime.now(timezone.utc)
  1391. if subtask_id and not archive.subtask_id:
  1392. archive.subtask_id = subtask_id
  1393. await db.commit()
  1394. # Track as active print
  1395. _active_prints[(printer_id, archive.filename)] = archive.id
  1396. if subtask_name:
  1397. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  1398. # Inject ams_mapping into usage tracker session — the session was created
  1399. # before expected-print promotion, so it may have ams_mapping=None when
  1400. # the MQTT request topic subscription failed (common on P1S/A1).
  1401. _stored_map = _print_ams_mappings.get(expected_archive_id)
  1402. if _stored_map:
  1403. try:
  1404. from backend.app.services.usage_tracker import _active_sessions
  1405. _ut_session = _active_sessions.get(printer_id)
  1406. if _ut_session and not _ut_session.ams_mapping:
  1407. _ut_session.ams_mapping = _stored_map
  1408. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  1409. except Exception:
  1410. pass
  1411. # Set up energy tracking (#941: persist start on archive row)
  1412. await _record_energy_start(archive, printer_id, db, context="expected-print")
  1413. await ws_manager.send_archive_updated(
  1414. {
  1415. "id": archive.id,
  1416. "status": "printing",
  1417. }
  1418. )
  1419. # Send notification with archive data (reprint/scheduled)
  1420. if not notification_sent:
  1421. # Use archive's created_by_id; fall back to the creator registered via
  1422. # register_expected_print (handles library-file-based queue items where
  1423. # the freshly-created archive has no created_by_id yet).
  1424. # Pop ALL matching keys so no stale entries remain in the dict.
  1425. fallback_creator = None
  1426. for key in expected_keys:
  1427. popped = _expected_print_creators.pop(key, None)
  1428. if fallback_creator is None:
  1429. fallback_creator = popped
  1430. archive_data = {
  1431. "print_time_seconds": archive.print_time_seconds,
  1432. "created_by_id": archive.created_by_id or fallback_creator,
  1433. }
  1434. await _send_print_start_notification(printer_id, data, archive_data, logger)
  1435. # Extract printable objects from the archived 3MF file
  1436. _load_objects_from_archive(archive, printer_id, logger)
  1437. # Store Spoolman tracking data for per-filament usage reporting
  1438. try:
  1439. await _store_spoolman_print_data(
  1440. printer_id,
  1441. archive.id,
  1442. archive.file_path,
  1443. db,
  1444. printer_manager,
  1445. ams_mapping=_get_start_ams_mapping(data, archive.id),
  1446. )
  1447. except Exception as e:
  1448. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  1449. return # Skip creating a new archive
  1450. # Check if there's already a "printing" archive for this printer/file
  1451. # This prevents duplicates when backend restarts during an active print
  1452. from backend.app.models.archive import PrintArchive
  1453. existing_archive: PrintArchive | None = None
  1454. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  1455. # across a backend restart for the same print, so this is the most
  1456. # reliable way to reattach. We also accept a previously stale-cancelled
  1457. # archive here so users upgrading mid-print get revived when the row
  1458. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  1459. if subtask_id:
  1460. by_id = await db.execute(
  1461. select(PrintArchive)
  1462. .where(PrintArchive.printer_id == printer_id)
  1463. .where(PrintArchive.subtask_id == subtask_id)
  1464. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  1465. .order_by(PrintArchive.created_at.desc())
  1466. .limit(1)
  1467. )
  1468. candidate = by_id.scalar_one_or_none()
  1469. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  1470. existing_archive = candidate
  1471. # Fallback match: name-based lookup. Kept as-is for prints whose
  1472. # subtask_id is missing ("0" / local / non-cloud prints).
  1473. if existing_archive is None:
  1474. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  1475. existing = await db.execute(
  1476. select(PrintArchive)
  1477. .where(PrintArchive.printer_id == printer_id)
  1478. .where(PrintArchive.status == "printing")
  1479. .where(
  1480. or_(
  1481. PrintArchive.print_name == check_name,
  1482. PrintArchive.filename.in_(
  1483. [
  1484. f"{check_name}.3mf",
  1485. f"{check_name}.gcode.3mf",
  1486. ]
  1487. ),
  1488. )
  1489. )
  1490. .order_by(PrintArchive.created_at.desc())
  1491. .limit(1)
  1492. )
  1493. existing_archive = existing.scalar_one_or_none()
  1494. if existing_archive:
  1495. # subtask_id match → always resume, regardless of age. Same print,
  1496. # just a backend restart. Revive if it was previously stale-cancelled.
  1497. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  1498. if subtask_match:
  1499. if existing_archive.status == "cancelled":
  1500. logger.warning(
  1501. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  1502. existing_archive.id,
  1503. subtask_id,
  1504. )
  1505. existing_archive.status = "printing"
  1506. existing_archive.failure_reason = None
  1507. await db.commit()
  1508. else:
  1509. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  1510. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  1511. if existing_archive.energy_start_kwh is None:
  1512. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  1513. if not notification_sent:
  1514. archive_data = {
  1515. "print_time_seconds": existing_archive.print_time_seconds,
  1516. "created_by_id": existing_archive.created_by_id,
  1517. }
  1518. await _send_print_start_notification(printer_id, data, archive_data, logger)
  1519. _load_objects_from_archive(existing_archive, printer_id, logger)
  1520. return
  1521. # Name-match only: fall back to the legacy 4h staleness heuristic.
  1522. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  1523. if archive_age.total_seconds() > 4 * 60 * 60: # 4 hours
  1524. logger.warning(
  1525. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}), "
  1526. f"marking as cancelled and creating new archive"
  1527. )
  1528. existing_archive.status = "cancelled"
  1529. existing_archive.failure_reason = "Stale - print likely cancelled or failed without status update"
  1530. await db.commit()
  1531. # Fall through to create new archive (don't return)
  1532. _existing_archive = None # Clear so we don't use stale archive
  1533. else:
  1534. logger.info(
  1535. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  1536. )
  1537. # Track this as the active print
  1538. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  1539. # Attach subtask_id retroactively so future restarts can resume
  1540. if subtask_id and not existing_archive.subtask_id:
  1541. existing_archive.subtask_id = subtask_id
  1542. await db.commit()
  1543. # Also set up energy tracking if not already tracked (#941: persisted column)
  1544. if existing_archive.energy_start_kwh is None:
  1545. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  1546. # Send notification with archive data (existing archive)
  1547. if not notification_sent:
  1548. archive_data = {
  1549. "print_time_seconds": existing_archive.print_time_seconds,
  1550. "created_by_id": existing_archive.created_by_id,
  1551. }
  1552. await _send_print_start_notification(printer_id, data, archive_data, logger)
  1553. # Extract printable objects from the archived 3MF file
  1554. _load_objects_from_archive(existing_archive, printer_id, logger)
  1555. return
  1556. # Build list of possible 3MF filenames to try
  1557. possible_names = []
  1558. # Bambu printers typically store files as "Name.gcode.3mf"
  1559. # The subtask_name is usually the best source for the filename
  1560. if subtask_name:
  1561. # Try common Bambu naming patterns
  1562. possible_names.append(f"{subtask_name}.gcode.3mf")
  1563. possible_names.append(f"{subtask_name}.3mf")
  1564. # Try original filename with .3mf extension
  1565. if filename:
  1566. # Extract just the filename part, not the full path
  1567. fname = filename.split("/")[-1] if "/" in filename else filename
  1568. if fname.endswith(".3mf"):
  1569. possible_names.append(fname)
  1570. elif fname.endswith(".gcode"):
  1571. base = fname.rsplit(".", 1)[0]
  1572. possible_names.append(f"{base}.gcode.3mf")
  1573. possible_names.append(f"{base}.3mf")
  1574. else:
  1575. possible_names.append(f"{fname}.gcode.3mf")
  1576. possible_names.append(f"{fname}.3mf")
  1577. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  1578. space_variants = []
  1579. for name in possible_names:
  1580. if " " in name:
  1581. space_variants.append(name.replace(" ", "_"))
  1582. possible_names.extend(space_variants)
  1583. # Remove duplicates while preserving order
  1584. seen = set()
  1585. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  1586. logger.info("Trying filenames: %s", possible_names)
  1587. # Try to find and download the 3MF file
  1588. temp_path = None
  1589. downloaded_filename = None
  1590. # Cache check: cover endpoint may have already pulled this 3MF during
  1591. # the print (frontend opens the card and shows the thumbnail) — reuse
  1592. # that file instead of re-downloading 36MB over the same FTP link that
  1593. # just served it (#972). The cache keys on a normalized filename so
  1594. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  1595. for try_filename in possible_names:
  1596. if not try_filename.endswith(".3mf"):
  1597. continue
  1598. cached = get_cached_3mf(printer_id, try_filename)
  1599. if cached:
  1600. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  1601. temp_path = cached
  1602. downloaded_filename = try_filename
  1603. break
  1604. # Get FTP retry settings
  1605. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1606. for try_filename in possible_names if not downloaded_filename else []:
  1607. if not try_filename.endswith(".3mf"):
  1608. continue
  1609. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  1610. # printers, so try it first — deferring it to last cost #972's reporter
  1611. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  1612. # landing on the path that actually had the file.
  1613. remote_paths = [
  1614. f"/{try_filename}",
  1615. f"/cache/{try_filename}",
  1616. f"/model/{try_filename}",
  1617. f"/data/{try_filename}",
  1618. f"/data/Metadata/{try_filename}",
  1619. ]
  1620. temp_path = app_settings.archive_dir / "temp" / try_filename
  1621. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1622. for remote_path in remote_paths:
  1623. logger.debug("Trying FTP download: %s", remote_path)
  1624. try:
  1625. if ftp_retry_enabled:
  1626. downloaded = await with_ftp_retry(
  1627. download_file_async,
  1628. printer.ip_address,
  1629. printer.access_code,
  1630. remote_path,
  1631. temp_path,
  1632. timeout=ftp_timeout,
  1633. socket_timeout=ftp_timeout,
  1634. printer_model=printer.model,
  1635. max_retries=ftp_retry_count,
  1636. retry_delay=ftp_retry_delay,
  1637. operation_name=f"Download 3MF from {remote_path}",
  1638. non_retry_exceptions=(FileNotOnPrinterError,),
  1639. )
  1640. else:
  1641. downloaded = await download_file_async(
  1642. printer.ip_address,
  1643. printer.access_code,
  1644. remote_path,
  1645. temp_path,
  1646. timeout=ftp_timeout,
  1647. socket_timeout=ftp_timeout,
  1648. printer_model=printer.model,
  1649. )
  1650. if downloaded:
  1651. downloaded_filename = try_filename
  1652. logger.info("Downloaded: %s", remote_path)
  1653. # Populate shared cache so the cover endpoint (if it
  1654. # runs next) doesn't refetch the same 36MB over FTP.
  1655. cache_3mf_download(printer_id, try_filename, temp_path)
  1656. break
  1657. except FileNotOnPrinterError:
  1658. # 550 — file isn't at this path. Advance to next candidate
  1659. # without burning the retry budget.
  1660. logger.debug("3MF not at %s (550), trying next path", remote_path)
  1661. except Exception as e:
  1662. logger.debug("FTP download failed for %s: %s", remote_path, e)
  1663. if downloaded_filename:
  1664. break
  1665. # If still not found, try listing directories to find matching file
  1666. # Different printer models use different directory structures
  1667. if not downloaded_filename and (filename or subtask_name):
  1668. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  1669. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  1670. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  1671. for search_dir in search_dirs:
  1672. if downloaded_filename:
  1673. break
  1674. try:
  1675. dir_files = await list_files_async(
  1676. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  1677. )
  1678. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  1679. if threemf_files:
  1680. logger.info(
  1681. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  1682. )
  1683. for f in dir_files:
  1684. if f.get("is_directory"):
  1685. continue
  1686. fname = f.get("name", "")
  1687. # Normalize both for comparison (spaces and underscores are equivalent)
  1688. fname_normalized = fname.lower().replace(" ", "_")
  1689. search_normalized = search_term.replace(" ", "_")
  1690. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  1691. logger.info("Found matching file in %s: %s", search_dir, fname)
  1692. temp_path = app_settings.archive_dir / "temp" / fname
  1693. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1694. remote_full_path = posixpath.join(search_dir, fname)
  1695. if ftp_retry_enabled:
  1696. downloaded = await with_ftp_retry(
  1697. download_file_async,
  1698. printer.ip_address,
  1699. printer.access_code,
  1700. remote_full_path,
  1701. temp_path,
  1702. timeout=ftp_timeout,
  1703. socket_timeout=ftp_timeout,
  1704. printer_model=printer.model,
  1705. max_retries=ftp_retry_count,
  1706. retry_delay=ftp_retry_delay,
  1707. operation_name=f"Download 3MF from {remote_full_path}",
  1708. )
  1709. else:
  1710. downloaded = await download_file_async(
  1711. printer.ip_address,
  1712. printer.access_code,
  1713. remote_full_path,
  1714. temp_path,
  1715. timeout=ftp_timeout,
  1716. socket_timeout=ftp_timeout,
  1717. printer_model=printer.model,
  1718. )
  1719. if downloaded:
  1720. downloaded_filename = fname
  1721. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  1722. cache_3mf_download(printer_id, fname, temp_path)
  1723. break
  1724. except Exception as e:
  1725. logger.debug("Failed to list %s: %s", search_dir, e)
  1726. if not downloaded_filename or not temp_path:
  1727. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  1728. # Create a fallback archive without 3MF data so the print is still tracked
  1729. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  1730. try:
  1731. from backend.app.models.archive import PrintArchive
  1732. # Derive print name from subtask_name or filename
  1733. print_name = subtask_name or filename
  1734. if print_name:
  1735. # Clean up the name (remove extensions, path parts)
  1736. print_name = print_name.split("/")[-1]
  1737. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  1738. else:
  1739. print_name = "Unknown Print"
  1740. # Recover estimated print time from MQTT (best-effort for notifications)
  1741. fallback_print_time = None
  1742. mqtt_remaining = data.get("remaining_time")
  1743. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  1744. fallback_print_time = int(mqtt_remaining)
  1745. if fallback_print_time is None:
  1746. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  1747. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  1748. fallback_print_time = int(mc_remaining * 60)
  1749. # Create minimal archive entry
  1750. fallback_archive = PrintArchive(
  1751. printer_id=printer_id,
  1752. filename=filename or f"{print_name}.3mf",
  1753. file_path="", # Empty - no 3MF file available
  1754. file_size=0,
  1755. print_name=print_name,
  1756. print_time_seconds=fallback_print_time,
  1757. status="printing",
  1758. started_at=datetime.now(timezone.utc),
  1759. subtask_id=subtask_id,
  1760. extra_data={"no_3mf_available": True, "original_subtask": subtask_name, "_print_data": data},
  1761. )
  1762. db.add(fallback_archive)
  1763. await db.commit()
  1764. await db.refresh(fallback_archive)
  1765. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  1766. # Start timelapse session if external camera is enabled
  1767. if printer.external_camera_enabled and printer.external_camera_url:
  1768. from backend.app.services.layer_timelapse import start_session
  1769. start_session(
  1770. printer_id,
  1771. fallback_archive.id,
  1772. printer.external_camera_url,
  1773. printer.external_camera_type or "mjpeg",
  1774. )
  1775. logger.info("Started layer timelapse for printer %s, archive %s", printer_id, fallback_archive.id)
  1776. # Track as active print
  1777. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  1778. if filename:
  1779. _active_prints[(printer_id, filename)] = fallback_archive.id
  1780. if subtask_name:
  1781. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  1782. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  1783. # Record starting energy if smart plug available (#941: persisted column)
  1784. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  1785. # Send WebSocket notification
  1786. await ws_manager.send_archive_created(
  1787. {
  1788. "id": fallback_archive.id,
  1789. "printer_id": fallback_archive.printer_id,
  1790. "filename": fallback_archive.filename,
  1791. "print_name": fallback_archive.print_name,
  1792. "status": fallback_archive.status,
  1793. }
  1794. )
  1795. # MQTT relay - publish archive created
  1796. try:
  1797. await mqtt_relay.on_archive_created(
  1798. archive_id=fallback_archive.id,
  1799. print_name=fallback_archive.print_name,
  1800. printer_name=printer.name,
  1801. status=fallback_archive.status,
  1802. )
  1803. except Exception:
  1804. pass # Don't fail if MQTT fails
  1805. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  1806. try:
  1807. await _store_spoolman_print_data(
  1808. printer_id,
  1809. fallback_archive.id,
  1810. fallback_archive.file_path,
  1811. db,
  1812. printer_manager,
  1813. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  1814. )
  1815. except Exception as e:
  1816. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  1817. # Send notification without archive data (file not found)
  1818. if not notification_sent:
  1819. await _send_print_start_notification(printer_id, data, logger=logger)
  1820. return
  1821. except Exception as e:
  1822. logger.error("Failed to create fallback archive: %s", e)
  1823. # Send notification without archive data (file not found)
  1824. if not notification_sent:
  1825. await _send_print_start_notification(printer_id, data, logger=logger)
  1826. return
  1827. try:
  1828. # Archive the file with status "printing"
  1829. service = ArchiveService(db)
  1830. archive = await service.archive_print(
  1831. printer_id=printer_id,
  1832. source_file=temp_path,
  1833. print_data={**data, "status": "printing"},
  1834. subtask_id=subtask_id,
  1835. )
  1836. if archive:
  1837. # Track this active print (use both original filename and downloaded filename)
  1838. _active_prints[(printer_id, downloaded_filename)] = archive.id
  1839. if filename and filename != downloaded_filename:
  1840. _active_prints[(printer_id, filename)] = archive.id
  1841. if subtask_name:
  1842. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  1843. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  1844. # Start timelapse session if external camera is enabled
  1845. if printer.external_camera_enabled and printer.external_camera_url:
  1846. from backend.app.services.layer_timelapse import start_session
  1847. start_session(
  1848. printer_id,
  1849. archive.id,
  1850. printer.external_camera_url,
  1851. printer.external_camera_type or "mjpeg",
  1852. )
  1853. logger.info("Started layer timelapse for printer %s, archive %s", printer_id, archive.id)
  1854. # Record starting energy from smart plug if available (#941: persisted column)
  1855. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  1856. await ws_manager.send_archive_created(
  1857. {
  1858. "id": archive.id,
  1859. "printer_id": archive.printer_id,
  1860. "filename": archive.filename,
  1861. "print_name": archive.print_name,
  1862. "status": archive.status,
  1863. }
  1864. )
  1865. # MQTT relay - publish archive created
  1866. try:
  1867. await mqtt_relay.on_archive_created(
  1868. archive_id=archive.id,
  1869. print_name=archive.print_name,
  1870. printer_name=printer.name,
  1871. status=archive.status,
  1872. )
  1873. except Exception:
  1874. pass # Don't fail if MQTT fails
  1875. # Send notification with archive data (new archive created)
  1876. if not notification_sent:
  1877. archive_data = {
  1878. "print_time_seconds": archive.print_time_seconds,
  1879. "created_by_id": archive.created_by_id,
  1880. }
  1881. await _send_print_start_notification(printer_id, data, archive_data, logger)
  1882. # Extract printable objects for skip object functionality
  1883. try:
  1884. from backend.app.services.archive import extract_printable_objects_from_3mf
  1885. with open(temp_path, "rb") as f:
  1886. threemf_data = f.read()
  1887. # Extract with positions for UI overlay
  1888. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  1889. threemf_data, include_positions=True
  1890. )
  1891. if printable_objects:
  1892. # Store objects in printer state
  1893. client = printer_manager.get_client(printer_id)
  1894. if client:
  1895. client.state.printable_objects = printable_objects
  1896. client.state.printable_objects_bbox_all = bbox_all
  1897. client.state.skipped_objects = [] # Reset skipped objects for new print
  1898. logger.info(
  1899. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  1900. )
  1901. except Exception as e:
  1902. logger.debug("Failed to extract printable objects: %s", e)
  1903. # Store Spoolman tracking data for per-filament usage reporting
  1904. try:
  1905. await _store_spoolman_print_data(
  1906. printer_id,
  1907. archive.id,
  1908. archive.file_path,
  1909. db,
  1910. printer_manager,
  1911. ams_mapping=_get_start_ams_mapping(data, archive.id),
  1912. )
  1913. except Exception as e:
  1914. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  1915. # Capture timelapse file baseline for snapshot-diff on completion
  1916. try:
  1917. baseline_files, _ = await _list_timelapse_videos(printer)
  1918. _timelapse_baselines[printer_id] = {f.get("name", "") for f in baseline_files}
  1919. logger.info(
  1920. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  1921. len(_timelapse_baselines[printer_id]),
  1922. printer_id,
  1923. )
  1924. except Exception as e:
  1925. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  1926. finally:
  1927. # Keep temp_path around until print completes so the cover endpoint
  1928. # can reuse it (#972). Cache eviction in on_print_complete deletes
  1929. # the file. If the cache entry was evicted early (file vanished),
  1930. # clean up any stragglers here to avoid leaking disk on retries.
  1931. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  1932. if temp_path and temp_path.exists() and cached_now != temp_path:
  1933. temp_path.unlink()
  1934. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  1935. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  1936. """List video files from printer's timelapse directory.
  1937. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  1938. Returns (video_files, found_path) where video_files is a list of file dicts
  1939. and found_path is the directory where they were found, or ([], None).
  1940. """
  1941. from backend.app.services.bambu_ftp import list_files_async
  1942. logger = logging.getLogger(__name__)
  1943. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  1944. try:
  1945. found_files = await list_files_async(
  1946. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  1947. )
  1948. if found_files:
  1949. video_files = [
  1950. f
  1951. for f in found_files
  1952. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  1953. ]
  1954. if video_files:
  1955. return video_files, timelapse_path
  1956. except Exception as e:
  1957. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  1958. continue
  1959. return [], None
  1960. async def _scan_for_timelapse_with_retries(archive_id: int, baseline_names: set[str] | None = None):
  1961. """
  1962. Scan for timelapse with retries using a snapshot-diff approach.
  1963. Instead of picking the "most recent by mtime" (unreliable when the printer
  1964. clock is wrong in LAN-only mode), we snapshot existing MP4 filenames BEFORE
  1965. waiting, then look for any NEW filename that appears after each delay.
  1966. If baseline_names is provided (captured at print start), it is used directly.
  1967. Otherwise falls back to taking a baseline at completion time (best-effort
  1968. for prints started before app restart).
  1969. Falls back to name-matching (print name contained in MP4 filename) if no
  1970. new file appears after all retries.
  1971. """
  1972. from pathlib import Path
  1973. logger = logging.getLogger(__name__)
  1974. # --- Phase 1: Take baseline snapshot of existing timelapse files ---
  1975. try:
  1976. async with async_session() as db:
  1977. from backend.app.models.printer import Printer
  1978. service = ArchiveService(db)
  1979. archive = await service.get_archive(archive_id)
  1980. if not archive:
  1981. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  1982. return
  1983. if archive.timelapse_path:
  1984. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  1985. return
  1986. if not archive.printer_id:
  1987. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  1988. return
  1989. if baseline_names is not None:
  1990. # Use pre-captured baseline from print start (no race condition)
  1991. logger.info(
  1992. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  1993. len(baseline_names),
  1994. archive_id,
  1995. )
  1996. else:
  1997. # Fallback: take baseline now (e.g. app restarted mid-print)
  1998. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1999. printer = result.scalar_one_or_none()
  2000. if not printer:
  2001. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  2002. return
  2003. baseline_files, _ = await _list_timelapse_videos(printer)
  2004. baseline_names = {f.get("name", "") for f in baseline_files}
  2005. logger.info(
  2006. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  2007. len(baseline_names),
  2008. archive_id,
  2009. )
  2010. # Derive base_name for name-matching fallback
  2011. base_name = Path(archive.filename).stem if archive.filename else ""
  2012. if base_name.endswith(".gcode"):
  2013. base_name = base_name[:-6]
  2014. except Exception as e:
  2015. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  2016. return
  2017. # --- Phase 2: Retry loop — look for NEW files that weren't in baseline ---
  2018. retry_delays = [5, 10, 20, 30]
  2019. for attempt, delay in enumerate(retry_delays, 1):
  2020. logger.info(
  2021. "[TIMELAPSE] Attempt %s/%s: waiting %ss before scanning for archive %s",
  2022. attempt,
  2023. len(retry_delays),
  2024. delay,
  2025. archive_id,
  2026. )
  2027. await asyncio.sleep(delay)
  2028. try:
  2029. async with async_session() as db:
  2030. from backend.app.models.printer import Printer
  2031. from backend.app.services.bambu_ftp import download_file_bytes_async
  2032. service = ArchiveService(db)
  2033. archive = await service.get_archive(archive_id)
  2034. if not archive:
  2035. logger.warning("[TIMELAPSE] Archive %s not found, stopping retries", archive_id)
  2036. return
  2037. if archive.timelapse_path:
  2038. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping retries", archive_id)
  2039. return
  2040. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  2041. printer = result.scalar_one_or_none()
  2042. if not printer:
  2043. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping retries", archive_id)
  2044. return
  2045. video_files, found_path = await _list_timelapse_videos(printer)
  2046. if not video_files:
  2047. logger.info("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  2048. continue
  2049. logger.info("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  2050. for f in video_files[:5]:
  2051. logger.info("[TIMELAPSE] - %s", f.get("name"))
  2052. # Find files that are NEW (not in baseline snapshot)
  2053. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  2054. if new_files:
  2055. # Pick the first new file (there should typically be exactly one)
  2056. target = new_files[0]
  2057. file_name = target.get("name")
  2058. remote_path = target.get("path") or f"/timelapse/{file_name}"
  2059. logger.info(
  2060. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  2061. attempt,
  2062. file_name,
  2063. archive_id,
  2064. )
  2065. timelapse_data = await download_file_bytes_async(
  2066. printer.ip_address, printer.access_code, remote_path, printer_model=printer.model
  2067. )
  2068. if timelapse_data:
  2069. success = await service.attach_timelapse(archive_id, timelapse_data, file_name)
  2070. if success:
  2071. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  2072. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  2073. return
  2074. else:
  2075. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  2076. else:
  2077. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  2078. else:
  2079. logger.info("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  2080. except Exception as e:
  2081. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  2082. # --- Phase 3: Fallback — try name matching against all files ---
  2083. if base_name:
  2084. logger.info("[TIMELAPSE] Retries exhausted, trying name-match fallback for '%s'", base_name)
  2085. try:
  2086. async with async_session() as db:
  2087. from backend.app.models.printer import Printer
  2088. from backend.app.services.bambu_ftp import download_file_bytes_async
  2089. service = ArchiveService(db)
  2090. archive = await service.get_archive(archive_id)
  2091. if not archive or archive.timelapse_path:
  2092. return
  2093. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  2094. printer = result.scalar_one_or_none()
  2095. if not printer:
  2096. return
  2097. video_files, found_path = await _list_timelapse_videos(printer)
  2098. for f in video_files:
  2099. fname = f.get("name", "")
  2100. if base_name.lower() in fname.lower():
  2101. remote_path = f.get("path") or f"/timelapse/{fname}"
  2102. logger.info("[TIMELAPSE] Name-match fallback: '%s' matches '%s'", base_name, fname)
  2103. timelapse_data = await download_file_bytes_async(
  2104. printer.ip_address, printer.access_code, remote_path, printer_model=printer.model
  2105. )
  2106. if timelapse_data:
  2107. success = await service.attach_timelapse(archive_id, timelapse_data, fname)
  2108. if success:
  2109. logger.info(
  2110. "[TIMELAPSE] Name-match fallback attached timelapse to archive %s", archive_id
  2111. )
  2112. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  2113. return
  2114. break # Only try the first name match
  2115. except Exception as e:
  2116. logger.warning("[TIMELAPSE] Name-match fallback failed: %s", e)
  2117. logger.warning("[TIMELAPSE] All attempts exhausted for archive %s, giving up", archive_id)
  2118. async def on_print_complete(printer_id: int, data: dict):
  2119. """Handle print completion - update the archive status."""
  2120. import time
  2121. logger = logging.getLogger(__name__)
  2122. start_time = time.time()
  2123. def log_timing(section: str):
  2124. elapsed = time.time() - start_time
  2125. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  2126. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  2127. # Drop the 3MF download cache for this printer (#972). The print is over,
  2128. # nothing else legitimately needs the bytes; keeping them would only risk
  2129. # handing a stale file to the next print if it reuses the same name.
  2130. clear_3mf_cache(printer_id)
  2131. try:
  2132. ws_data = {
  2133. "status": data.get("status"),
  2134. "filename": data.get("filename"),
  2135. "subtask_name": data.get("subtask_name"),
  2136. "timelapse_was_active": data.get("timelapse_was_active"),
  2137. }
  2138. await ws_manager.send_print_complete(printer_id, ws_data)
  2139. log_timing("WebSocket send_print_complete")
  2140. except Exception as e:
  2141. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  2142. # Capture user info before clearing (needed for print log entry)
  2143. _print_user_info = printer_manager.get_current_print_user(printer_id)
  2144. # Clear current print user tracking (Issue #206)
  2145. printer_manager.clear_current_print_user(printer_id)
  2146. # If the user explicitly stopped this print from the queue UI the printer will
  2147. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  2148. # correct "print stopped" notification/email is sent instead of a failure alert.
  2149. _raw_status = data.get("status", "completed")
  2150. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  2151. logger.info(
  2152. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  2153. _raw_status,
  2154. printer_id,
  2155. )
  2156. data = {**data, "status": "cancelled"}
  2157. _user_stopped_printers.discard(printer_id)
  2158. # Raise the plate-clear gate for queued dispatch (#961). Only for completed/failed —
  2159. # user-cancelled prints don't require a plate-clear ack (nothing printed on the bed).
  2160. # Persisted to DB so the gate survives Auto Off power cycles and Bambuddy restarts.
  2161. _final_status = data.get("status", "completed")
  2162. if _final_status in ("completed", "failed"):
  2163. printer_manager.set_awaiting_plate_clear(printer_id, True)
  2164. # MQTT relay - publish print complete
  2165. try:
  2166. printer_info = printer_manager.get_printer(printer_id)
  2167. if printer_info:
  2168. await mqtt_relay.on_print_complete(
  2169. printer_id,
  2170. printer_info.name,
  2171. printer_info.serial_number,
  2172. data.get("filename", ""),
  2173. data.get("subtask_name", ""),
  2174. data.get("status", "completed"),
  2175. )
  2176. except Exception:
  2177. pass # Don't fail print complete callback if MQTT fails
  2178. filename = data.get("filename", "")
  2179. subtask_name = data.get("subtask_name", "")
  2180. if not filename and not subtask_name:
  2181. logger.warning("Print complete without filename or subtask_name")
  2182. return
  2183. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  2184. # Build list of possible keys to try (matching how they were registered in on_print_start)
  2185. possible_keys = []
  2186. # Try subtask_name variations first (most reliable for matching)
  2187. if subtask_name:
  2188. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  2189. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  2190. possible_keys.append((printer_id, subtask_name))
  2191. # Try filename variations
  2192. if filename:
  2193. # Extract just the filename if it's a path
  2194. fname = filename.split("/")[-1] if "/" in filename else filename
  2195. if fname.endswith(".3mf"):
  2196. possible_keys.append((printer_id, fname))
  2197. elif fname.endswith(".gcode"):
  2198. base_name = fname.rsplit(".", 1)[0]
  2199. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  2200. possible_keys.append((printer_id, f"{base_name}.3mf"))
  2201. possible_keys.append((printer_id, fname))
  2202. else:
  2203. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  2204. possible_keys.append((printer_id, f"{fname}.3mf"))
  2205. possible_keys.append((printer_id, fname))
  2206. # Also try full path versions
  2207. if filename.endswith(".3mf"):
  2208. possible_keys.append((printer_id, filename))
  2209. elif filename.endswith(".gcode"):
  2210. base_name = filename.rsplit(".", 1)[0]
  2211. possible_keys.append((printer_id, f"{base_name}.3mf"))
  2212. possible_keys.append((printer_id, filename))
  2213. else:
  2214. possible_keys.append((printer_id, f"{filename}.3mf"))
  2215. possible_keys.append((printer_id, filename))
  2216. # Find the archive for this print
  2217. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  2218. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  2219. archive_id = None
  2220. for key in possible_keys:
  2221. archive_id = _active_prints.pop(key, None)
  2222. if archive_id:
  2223. logger.info("Found archive %s with key %s", archive_id, key)
  2224. # Also clean up any other keys pointing to this archive
  2225. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  2226. for k in keys_to_remove:
  2227. _active_prints.pop(k, None)
  2228. break
  2229. if not archive_id:
  2230. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  2231. async with async_session() as db:
  2232. from backend.app.models.archive import PrintArchive
  2233. # Try matching by subtask_name (stored as print_name) first
  2234. if subtask_name:
  2235. result = await db.execute(
  2236. select(PrintArchive)
  2237. .where(PrintArchive.printer_id == printer_id)
  2238. .where(PrintArchive.status == "printing")
  2239. .where(
  2240. or_(
  2241. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  2242. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  2243. )
  2244. )
  2245. .order_by(PrintArchive.created_at.desc())
  2246. .limit(1)
  2247. )
  2248. archive = result.scalar_one_or_none()
  2249. if archive:
  2250. archive_id = archive.id
  2251. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  2252. # Also try by filename
  2253. if not archive_id and filename:
  2254. result = await db.execute(
  2255. select(PrintArchive)
  2256. .where(PrintArchive.printer_id == printer_id)
  2257. .where(PrintArchive.filename == filename)
  2258. .where(PrintArchive.status == "printing")
  2259. .order_by(PrintArchive.created_at.desc())
  2260. .limit(1)
  2261. )
  2262. archive = result.scalar_one_or_none()
  2263. if archive:
  2264. archive_id = archive.id
  2265. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374)
  2266. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S)
  2267. # auto-start files found in root on power cycle, causing ghost prints.
  2268. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  2269. try:
  2270. if subtask_name:
  2271. async with async_session() as db:
  2272. from backend.app.models.printer import Printer
  2273. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2274. printer = result.scalar_one_or_none()
  2275. if printer:
  2276. from backend.app.services.bambu_ftp import delete_file_async
  2277. # Try both .3mf and .gcode extensions — the printer may have either
  2278. for ext in (".3mf", ".gcode"):
  2279. remote_path = f"/{subtask_name}{ext}"
  2280. # Retry up to 3 times — the printer may still lock the filesystem briefly after a print ends
  2281. for attempt in range(1, 4):
  2282. try:
  2283. delete_result = await delete_file_async(
  2284. printer.ip_address,
  2285. printer.access_code,
  2286. remote_path,
  2287. printer_model=printer.model,
  2288. )
  2289. if delete_result:
  2290. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  2291. break
  2292. except Exception as e:
  2293. delete_result = False
  2294. logger.warning(
  2295. "SD card cleanup attempt %d/3 raised for %s: %s",
  2296. attempt,
  2297. remote_path,
  2298. e,
  2299. )
  2300. if not delete_result and attempt < 3:
  2301. await asyncio.sleep(2)
  2302. elif not delete_result:
  2303. logger.warning(
  2304. "SD card cleanup failed after 3 attempts for %s (file may linger on SD card)",
  2305. remote_path,
  2306. )
  2307. except Exception as e:
  2308. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  2309. log_timing("SD card cleanup")
  2310. # Update queue item status early — must run before the archive_id early-return
  2311. # so queue items don't get stuck in "printing" when archive lookup fails.
  2312. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  2313. queue_item_id = None
  2314. queue_status = None
  2315. queue_auto_off = False
  2316. try:
  2317. from backend.app.core.database import run_with_retry
  2318. from backend.app.models.print_queue import PrintQueueItem
  2319. async def _update_queue_status(db):
  2320. nonlocal queue_item_id, queue_status, queue_auto_off
  2321. result = await db.execute(
  2322. select(PrintQueueItem)
  2323. .where(PrintQueueItem.printer_id == printer_id)
  2324. .where(PrintQueueItem.status == "printing")
  2325. )
  2326. printing_items = list(result.scalars().all())
  2327. if len(printing_items) > 1:
  2328. logger.warning(
  2329. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  2330. printer_id,
  2331. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  2332. )
  2333. item = printing_items[0] if printing_items else None
  2334. if item:
  2335. queue_status = data.get("status", "completed")
  2336. # MQTT sends "aborted" for cancelled prints; normalise to
  2337. # "cancelled" so it matches the queue schema Literal.
  2338. if queue_status == "aborted":
  2339. queue_status = "cancelled"
  2340. item.status = queue_status
  2341. item.completed_at = datetime.now(timezone.utc)
  2342. # Bump usage counters on the source library file so admins can
  2343. # sort by "last printed" and (eventually) auto-purge stale
  2344. # files — #1008.
  2345. await _bump_library_file_usage_if_completed(db, item, queue_status)
  2346. await db.commit()
  2347. queue_item_id = item.id
  2348. queue_auto_off = item.auto_off_after
  2349. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  2350. await run_with_retry(_update_queue_status, label="queue status update")
  2351. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  2352. # their own sessions and have their own error handling — no retry needed.
  2353. if queue_item_id is not None:
  2354. # MQTT relay - publish queue job completed
  2355. try:
  2356. printer_info = printer_manager.get_printer(printer_id)
  2357. await mqtt_relay.on_queue_job_completed(
  2358. job_id=queue_item_id,
  2359. filename=filename or subtask_name,
  2360. printer_id=printer_id,
  2361. printer_name=printer_info.name if printer_info else "Unknown",
  2362. status=queue_status,
  2363. )
  2364. except Exception:
  2365. pass # Don't fail if MQTT fails
  2366. # Check if queue is now empty and send notification
  2367. try:
  2368. from sqlalchemy import func as sa_func
  2369. async with async_session() as db:
  2370. count_result = await db.execute(
  2371. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  2372. )
  2373. pending_count = count_result.scalar() or 0
  2374. if pending_count == 0:
  2375. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  2376. completed_result = await db.execute(
  2377. select(sa_func.count(PrintQueueItem.id)).where(
  2378. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  2379. PrintQueueItem.completed_at >= today_start,
  2380. )
  2381. )
  2382. completed_count = completed_result.scalar() or 1
  2383. await notification_service.on_queue_completed(
  2384. completed_count=completed_count,
  2385. db=db,
  2386. )
  2387. except Exception:
  2388. pass # Don't fail if notification fails
  2389. # Handle auto_off_after - power off printer if requested (after cooldown)
  2390. if queue_auto_off:
  2391. async with async_session() as db:
  2392. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  2393. plugs = list(result.scalars().all())
  2394. enabled_plugs = [p for p in plugs if p.enabled]
  2395. if enabled_plugs:
  2396. logger.info("Auto-off requested for printer %s, waiting for cooldown...", printer_id)
  2397. async def cooldown_and_poweroff(pid: int, plug_ids: list[int]):
  2398. # Wait for nozzle to cool down
  2399. await printer_manager.wait_for_cooldown(pid, target_temp=50.0, timeout=600)
  2400. # Re-fetch plugs in new session and turn off each one
  2401. async with async_session() as new_db:
  2402. for plug_id in plug_ids:
  2403. try:
  2404. result = await new_db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  2405. p = result.scalar_one_or_none()
  2406. if p and p.enabled:
  2407. service = await smart_plug_manager.get_service_for_plug(p, new_db)
  2408. success = await service.turn_off(p)
  2409. if success:
  2410. logger.info("Powered off printer %s via smart plug '%s'", pid, p.name)
  2411. else:
  2412. logger.warning("Failed to power off plug '%s' for printer %s", p.name, pid)
  2413. except Exception as e:
  2414. logger.warning("Failed to power off plug %s for printer %s: %s", plug_id, pid, e)
  2415. asyncio.create_task(cooldown_and_poweroff(printer_id, [p.id for p in enabled_plugs]))
  2416. except Exception as e:
  2417. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  2418. log_timing("Queue item update")
  2419. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  2420. # Must run before archive_id early-return so it fires for all prints (including
  2421. # prints started from BambuStudio/touchscreen that have no archive).
  2422. if data.get("status") == "completed":
  2423. try:
  2424. from backend.app.api.routes.settings import get_setting
  2425. async with async_session() as db:
  2426. threshold_str = await get_setting(db, "bed_cooled_threshold")
  2427. threshold = float(threshold_str) if threshold_str else 35.0
  2428. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  2429. async with async_session() as db:
  2430. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  2431. if providers:
  2432. _bed_cool_waiters[printer_id] = {
  2433. "threshold": threshold,
  2434. "filename": filename or subtask_name or "",
  2435. "registered_at": time.time(),
  2436. }
  2437. logger.info(
  2438. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  2439. printer_id,
  2440. threshold,
  2441. )
  2442. else:
  2443. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  2444. except Exception as e:
  2445. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  2446. # --- Track filament consumption (must run before archive_id early-return so usage
  2447. # is recorded even when auto-archive is disabled) ---
  2448. usage_results: list[dict] = []
  2449. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  2450. stored_ams_mapping = data.get("ams_mapping")
  2451. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  2452. if not stored_ams_mapping and archive_id:
  2453. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  2454. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  2455. try:
  2456. async with async_session() as db:
  2457. from backend.app.api.routes.settings import get_setting
  2458. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2459. if not _spoolman_on or _spoolman_on.lower() != "true":
  2460. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  2461. async with async_session() as db:
  2462. usage_results = await usage_on_print_complete(
  2463. printer_id,
  2464. data,
  2465. printer_manager,
  2466. db,
  2467. archive_id=archive_id,
  2468. ams_mapping=stored_ams_mapping,
  2469. )
  2470. if usage_results:
  2471. await ws_manager.broadcast(
  2472. {
  2473. "type": "spool_usage_logged",
  2474. "printer_id": printer_id,
  2475. "usage": usage_results,
  2476. }
  2477. )
  2478. log_timing("Usage tracker")
  2479. except Exception as e:
  2480. logger.warning("Usage tracker on_print_complete failed: %s", e)
  2481. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  2482. if archive_id:
  2483. if data.get("status") == "completed":
  2484. try:
  2485. await _report_spoolman_usage(printer_id, archive_id)
  2486. log_timing("Spoolman usage report")
  2487. except Exception as e:
  2488. logger.warning("Spoolman usage reporting failed: %s", e)
  2489. else:
  2490. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  2491. try:
  2492. async with async_session() as db:
  2493. await _cleanup_spoolman_tracking(
  2494. printer_id,
  2495. archive_id,
  2496. db,
  2497. last_layer_num=data.get("last_layer_num"),
  2498. last_progress=data.get("last_progress"),
  2499. )
  2500. except Exception as e:
  2501. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  2502. log_timing("Filament usage tracking")
  2503. if not archive_id:
  2504. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  2505. # Still send print-complete/failed/stopped notifications even without an archive.
  2506. # Try to enrich with queue/library-file data so user-specific emails work too.
  2507. async def _notify_no_archive():
  2508. try:
  2509. async with async_session() as db:
  2510. from backend.app.models.library import LibraryFile
  2511. from backend.app.models.print_queue import PrintQueueItem
  2512. from backend.app.models.printer import Printer
  2513. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2514. printer_obj = result.scalar_one_or_none()
  2515. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  2516. # Try to find the most-recent queue item for this printer so we can
  2517. # recover created_by_id and estimated print time.
  2518. # NOTE: By the time this task runs the queue item status has already
  2519. # been updated to a terminal state (completed/failed/cancelled), so
  2520. # we look for recently-completed items (within the last 5 minutes).
  2521. no_archive_data: dict | None = None
  2522. try:
  2523. cutoff = datetime.now(timezone.utc) - timedelta(minutes=5)
  2524. q_result = await db.execute(
  2525. select(PrintQueueItem)
  2526. .where(PrintQueueItem.printer_id == printer_id)
  2527. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled"]))
  2528. .where(PrintQueueItem.completed_at >= cutoff)
  2529. .order_by(PrintQueueItem.completed_at.desc())
  2530. .limit(1)
  2531. )
  2532. queue_item = q_result.scalar_one_or_none()
  2533. if queue_item:
  2534. no_archive_data = {"created_by_id": queue_item.created_by_id}
  2535. # Pull estimated time from library file when available
  2536. if queue_item.library_file_id:
  2537. lib_result = await db.execute(
  2538. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  2539. )
  2540. lib_file = lib_result.scalar_one_or_none()
  2541. if lib_file and lib_file.print_time_seconds:
  2542. no_archive_data["print_time_seconds"] = lib_file.print_time_seconds
  2543. except Exception as lookup_err:
  2544. logger.debug(
  2545. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  2546. )
  2547. # Enrich with usage tracker results (captured in enclosing scope)
  2548. if usage_results:
  2549. if no_archive_data is None:
  2550. no_archive_data = {}
  2551. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  2552. if total_from_usage > 0:
  2553. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  2554. no_archive_data["usage_results"] = usage_results
  2555. # Try MQTT remaining_time for print duration when no queue/library data
  2556. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  2557. mqtt_remaining = data.get("remaining_time")
  2558. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  2559. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  2560. ps = data.get("status", "completed")
  2561. logger.info(
  2562. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  2563. )
  2564. await notification_service.on_print_complete(
  2565. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  2566. )
  2567. # Send user-specific email if we have a created_by_id
  2568. if no_archive_data and no_archive_data.get("created_by_id"):
  2569. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  2570. await _dispatch_user_print_email(
  2571. ps,
  2572. no_archive_data["created_by_id"],
  2573. p_name,
  2574. raw_filename,
  2575. db,
  2576. )
  2577. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  2578. except Exception as e:
  2579. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  2580. task = asyncio.create_task(_notify_no_archive())
  2581. task.add_done_callback(lambda _t: None)
  2582. return
  2583. log_timing("Archive lookup")
  2584. # Update archive status
  2585. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  2586. try:
  2587. async with async_session() as db:
  2588. service = ArchiveService(db)
  2589. status = data.get("status", "completed")
  2590. # Auto-detect failure reason
  2591. failure_reason = None
  2592. if status == "aborted":
  2593. failure_reason = "User cancelled"
  2594. logger.info("[ARCHIVE] Print was aborted by user, setting failure_reason='User cancelled'")
  2595. elif status == "failed":
  2596. # Try to determine failure reason from HMS errors
  2597. hms_errors = data.get("hms_errors", [])
  2598. if hms_errors:
  2599. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  2600. # Map known HMS error modules to failure reasons
  2601. # Module 0x07 = Filament, 0x0C = MC (Motion Controller), etc.
  2602. for err in hms_errors:
  2603. module = err.get("module", 0)
  2604. if module == 0x07: # Filament module
  2605. failure_reason = "Filament runout"
  2606. break
  2607. elif module == 0x0C: # Motion controller
  2608. failure_reason = "Layer shift"
  2609. break
  2610. elif module == 0x05: # Nozzle/extruder
  2611. failure_reason = "Clogged nozzle"
  2612. break
  2613. if failure_reason:
  2614. logger.info("[ARCHIVE] Detected failure_reason from HMS: %s", failure_reason)
  2615. else:
  2616. logger.info("[ARCHIVE] No HMS errors available to determine failure reason")
  2617. await service.update_archive_status(
  2618. archive_id,
  2619. status=status,
  2620. completed_at=datetime.now(timezone.utc) if status in ("completed", "failed", "aborted") else None,
  2621. failure_reason=failure_reason,
  2622. )
  2623. logger.info(
  2624. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  2625. )
  2626. await ws_manager.send_archive_updated(
  2627. {
  2628. "id": archive_id,
  2629. "status": status,
  2630. }
  2631. )
  2632. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  2633. # MQTT relay - publish archive updated
  2634. try:
  2635. await mqtt_relay.on_archive_updated(
  2636. archive_id=archive_id,
  2637. print_name=filename or subtask_name,
  2638. status=status,
  2639. )
  2640. except Exception:
  2641. pass # Don't fail if MQTT fails
  2642. except Exception as e:
  2643. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  2644. # Continue with other operations even if archive update fails
  2645. log_timing("Archive status update")
  2646. # Write independent print log entry (separate table, never touches archives)
  2647. try:
  2648. async with async_session() as db:
  2649. from backend.app.models.archive import PrintArchive
  2650. from backend.app.services.print_log import write_log_entry
  2651. archive = await db.get(PrintArchive, archive_id)
  2652. if archive:
  2653. # Back-fill created_by_id on reprint (#730): reprint reuses the
  2654. # source archive row rather than creating a new one, so an
  2655. # archive that was auto-created from a printer-initiated
  2656. # print (created_by_id=NULL) would otherwise stay unattributed
  2657. # forever. When we have a print-session user AND the archive
  2658. # has no attribution yet, credit the current user. Never
  2659. # overwrite an existing attribution — the original uploader
  2660. # keeps ownership.
  2661. _print_user_id = _print_user_info.get("user_id") if _print_user_info else None
  2662. if archive.created_by_id is None and _print_user_id is not None:
  2663. archive.created_by_id = _print_user_id
  2664. p_info = printer_manager.get_printer(printer_id)
  2665. await write_log_entry(
  2666. db,
  2667. status=data.get("status", "completed"),
  2668. print_name=archive.print_name,
  2669. printer_name=p_info.name if p_info else None,
  2670. printer_id=printer_id,
  2671. started_at=archive.started_at,
  2672. completed_at=archive.completed_at,
  2673. filament_type=archive.filament_type,
  2674. filament_color=archive.filament_color,
  2675. filament_used_grams=archive.filament_used_grams,
  2676. thumbnail_path=archive.thumbnail_path,
  2677. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  2678. )
  2679. await db.commit()
  2680. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  2681. except Exception as e:
  2682. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  2683. log_timing("Print log entry")
  2684. # Run slow operations as background tasks to avoid blocking the event loop
  2685. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  2686. async def _background_energy_calculation():
  2687. """Calculate and save energy usage in background.
  2688. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  2689. backend restart no longer loses per-print energy data).
  2690. """
  2691. try:
  2692. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  2693. async with async_session() as db:
  2694. from backend.app.models.archive import PrintArchive
  2695. archive = await db.get(PrintArchive, archive_id)
  2696. if archive is None:
  2697. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  2698. return
  2699. starting_kwh = archive.energy_start_kwh
  2700. if starting_kwh is None:
  2701. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  2702. return
  2703. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  2704. plug = plug_result.scalar_one_or_none()
  2705. if plug is None:
  2706. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  2707. return
  2708. energy = await _get_plug_energy(plug, db)
  2709. logger.info("[ENERGY-BG] Energy response: %s", energy)
  2710. if not energy or energy.get("total") is None:
  2711. logger.warning("[ENERGY-BG] No 'total' in energy response")
  2712. return
  2713. energy_used = round(energy["total"] - starting_kwh, 4)
  2714. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  2715. if energy_used < 0:
  2716. logger.warning(
  2717. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  2718. archive_id,
  2719. starting_kwh,
  2720. energy["total"],
  2721. )
  2722. return
  2723. from backend.app.api.routes.settings import get_setting
  2724. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  2725. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  2726. archive.energy_kwh = energy_used
  2727. archive.energy_cost = round(energy_used * cost_per_kwh, 3)
  2728. await db.commit()
  2729. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, archive.energy_cost)
  2730. except Exception as e:
  2731. logger.warning("[ENERGY-BG] Failed: %s", e)
  2732. async def _background_finish_photo() -> str | None:
  2733. """Capture finish photo in background. Returns photo filename if captured."""
  2734. try:
  2735. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  2736. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  2737. async with async_session() as db:
  2738. from backend.app.api.routes.settings import get_setting
  2739. capture_enabled = await get_setting(db, "capture_finish_photo")
  2740. if capture_enabled is None or capture_enabled.lower() == "true":
  2741. from backend.app.models.printer import Printer
  2742. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2743. printer = result.scalar_one_or_none()
  2744. if printer and archive_id:
  2745. from backend.app.models.archive import PrintArchive
  2746. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2747. archive = result.scalar_one_or_none()
  2748. if archive:
  2749. import uuid
  2750. from datetime import datetime
  2751. from pathlib import Path
  2752. if archive.file_path:
  2753. archive_dir = app_settings.base_dir / Path(archive.file_path).parent
  2754. else:
  2755. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  2756. archive_dir = app_settings.archive_dir / str(archive.id)
  2757. photo_filename = None
  2758. # Check for external camera first
  2759. if printer.external_camera_enabled and printer.external_camera_url:
  2760. logger.info("[PHOTO-BG] Using external camera")
  2761. from backend.app.services.external_camera import capture_frame
  2762. frame_data = await capture_frame(
  2763. printer.external_camera_url, printer.external_camera_type or "mjpeg"
  2764. )
  2765. if frame_data:
  2766. photos_dir = archive_dir / "photos"
  2767. photos_dir.mkdir(parents=True, exist_ok=True)
  2768. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  2769. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  2770. photo_path = photos_dir / photo_filename
  2771. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  2772. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  2773. else:
  2774. # Check if camera stream is active - use buffered frame to avoid freeze
  2775. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  2776. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  2777. active_chamber_for_printer = [
  2778. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  2779. ]
  2780. buffered_frame = get_buffered_frame(printer_id)
  2781. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  2782. # Use frame from active stream
  2783. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  2784. photos_dir = archive_dir / "photos"
  2785. photos_dir.mkdir(parents=True, exist_ok=True)
  2786. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  2787. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  2788. photo_path = photos_dir / photo_filename
  2789. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  2790. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  2791. else:
  2792. # No active stream - capture new frame
  2793. from backend.app.services.camera import capture_finish_photo
  2794. photo_filename = await capture_finish_photo(
  2795. printer_id=printer_id,
  2796. ip_address=printer.ip_address,
  2797. access_code=printer.access_code,
  2798. model=printer.model,
  2799. archive_dir=archive_dir,
  2800. )
  2801. if photo_filename:
  2802. photos = archive.photos or []
  2803. photos.append(photo_filename)
  2804. archive.photos = photos
  2805. await db.commit()
  2806. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  2807. return photo_filename
  2808. return None
  2809. except Exception as e:
  2810. logger.warning("[PHOTO-BG] Failed: %s", e)
  2811. return None
  2812. asyncio.create_task(_background_energy_calculation())
  2813. # Photo capture task - result will be used by notifications
  2814. photo_task = asyncio.create_task(_background_finish_photo())
  2815. log_timing("Background tasks scheduled (energy, photo)")
  2816. # Also run smart plug, notifications, and maintenance as background tasks
  2817. print_status = data.get("status", "completed")
  2818. async def _background_smart_plug():
  2819. """Handle smart plug automation in background."""
  2820. try:
  2821. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  2822. async with async_session() as db:
  2823. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  2824. logger.info("[AUTO-OFF-BG] Completed")
  2825. except Exception as e:
  2826. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  2827. async def _background_notifications(finish_photo_filename: str | None = None):
  2828. """Send print complete notifications in background."""
  2829. try:
  2830. logger.info(
  2831. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  2832. )
  2833. async with async_session() as db:
  2834. from backend.app.models.archive import PrintArchive
  2835. from backend.app.models.printer import Printer
  2836. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2837. printer = result.scalar_one_or_none()
  2838. printer_name = printer.name if printer else f"Printer {printer_id}"
  2839. archive_data = None
  2840. if archive_id:
  2841. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2842. archive = archive_result.scalar_one_or_none()
  2843. if archive:
  2844. archive_data = {
  2845. "print_time_seconds": archive.print_time_seconds,
  2846. "actual_filament_grams": archive.filament_used_grams,
  2847. "failure_reason": archive.failure_reason,
  2848. "created_by_id": archive.created_by_id,
  2849. }
  2850. # Scale filament usage for partial prints
  2851. if print_status != "completed" and archive.filament_used_grams:
  2852. progress = data.get("progress") or 0
  2853. scale = max(0.0, min(progress / 100.0, 1.0))
  2854. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  2855. archive_data["progress"] = progress
  2856. # Pass per-slot data from archive.extra_data
  2857. if archive.extra_data and archive.extra_data.get("filament_slots"):
  2858. slots = archive.extra_data["filament_slots"]
  2859. if print_status != "completed":
  2860. scale = max(0.0, min((data.get("progress") or 0) / 100.0, 1.0))
  2861. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  2862. archive_data["filament_slots"] = slots
  2863. # Enrich filament_grams from usage_results when archive has no 3MF data
  2864. if not archive_data.get("actual_filament_grams") and usage_results:
  2865. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  2866. if total_from_usage > 0:
  2867. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  2868. # Pass usage tracker results for AMS slot info in notifications
  2869. if usage_results:
  2870. archive_data["usage_results"] = usage_results
  2871. # Add finish photo URL and image bytes if available
  2872. if finish_photo_filename:
  2873. from backend.app.api.routes.settings import get_setting
  2874. external_url = await get_setting(db, "external_url")
  2875. if external_url:
  2876. external_url = external_url.rstrip("/")
  2877. archive_data["finish_photo_url"] = (
  2878. f"{external_url}/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  2879. )
  2880. else:
  2881. # Fallback to relative URL (won't work for external services)
  2882. archive_data["finish_photo_url"] = (
  2883. f"/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  2884. )
  2885. # Read finish photo bytes for image attachment (e.g. Pushover)
  2886. try:
  2887. from pathlib import Path
  2888. photo_path = (
  2889. app_settings.base_dir
  2890. / Path(archive.file_path).parent
  2891. / "photos"
  2892. / finish_photo_filename
  2893. )
  2894. if photo_path.exists():
  2895. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  2896. if len(photo_bytes) <= 2_500_000:
  2897. archive_data["image_data"] = photo_bytes
  2898. logger.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  2899. else:
  2900. logger.warning(
  2901. f"[NOTIFY-BG] Finish photo too large for attachment: "
  2902. f"{len(photo_bytes)} bytes"
  2903. )
  2904. except Exception as e:
  2905. logger.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  2906. await notification_service.on_print_complete(
  2907. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  2908. )
  2909. # Send user-specific email notification
  2910. if archive_data:
  2911. created_by_id = archive_data.get("created_by_id")
  2912. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  2913. await _dispatch_user_print_email(
  2914. print_status,
  2915. created_by_id,
  2916. printer_name,
  2917. raw_filename,
  2918. db,
  2919. )
  2920. logger.info("[NOTIFY-BG] Completed")
  2921. except Exception as e:
  2922. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  2923. async def _background_maintenance_check():
  2924. """Check for maintenance due in background."""
  2925. if print_status != "completed":
  2926. return
  2927. try:
  2928. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  2929. async with async_session() as db:
  2930. from backend.app.models.printer import Printer
  2931. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2932. printer = result.scalar_one_or_none()
  2933. printer_name = printer.name if printer else f"Printer {printer_id}"
  2934. await ensure_default_types(db)
  2935. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  2936. items_needing_attention = [
  2937. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  2938. for item in overview.maintenance_items
  2939. if item.enabled and (item.is_due or item.is_warning)
  2940. ]
  2941. if items_needing_attention:
  2942. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  2943. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  2944. # MQTT relay - publish maintenance alerts
  2945. for item in items_needing_attention:
  2946. try:
  2947. await mqtt_relay.on_maintenance_alert(
  2948. printer_id=printer_id,
  2949. printer_name=printer_name,
  2950. maintenance_type=item["name"],
  2951. current_value=0, # Not easily available here
  2952. threshold=0, # Not easily available here
  2953. )
  2954. except Exception:
  2955. pass # Don't fail if MQTT fails
  2956. else:
  2957. logger.info("[MAINT-BG] Completed (no items need attention)")
  2958. except Exception as e:
  2959. logger.warning("[MAINT-BG] Failed: %s", e)
  2960. asyncio.create_task(_background_smart_plug())
  2961. asyncio.create_task(_background_maintenance_check())
  2962. # Notification task waits for photo capture to complete first (with timeout)
  2963. async def _photo_then_notify():
  2964. """Wait for photo capture, then send notification with photo URL."""
  2965. finish_photo = None
  2966. try:
  2967. finish_photo = await asyncio.wait_for(photo_task, timeout=45)
  2968. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  2969. except TimeoutError:
  2970. logger.warning("[PHOTO-NOTIFY] Photo capture timed out after 45s, sending notification without photo")
  2971. except Exception as e:
  2972. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  2973. try:
  2974. await _background_notifications(finish_photo)
  2975. except Exception as e:
  2976. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  2977. asyncio.create_task(_photo_then_notify())
  2978. # Stitch external camera layer timelapse if session was active
  2979. print_status = data.get("status", "completed")
  2980. async def _background_layer_timelapse():
  2981. """Stitch layer timelapse and attach to archive."""
  2982. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  2983. try:
  2984. if print_status == "completed":
  2985. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  2986. timelapse_path = await tl_complete(printer_id)
  2987. if timelapse_path and archive_id:
  2988. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  2989. async with async_session() as db:
  2990. service = ArchiveService(db)
  2991. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  2992. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  2993. # Clean up the temp file
  2994. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  2995. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  2996. elif timelapse_path:
  2997. # Timelapse created but no archive - just clean up
  2998. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  2999. else:
  3000. # Print failed or cancelled - cancel timelapse session
  3001. cancel_session(printer_id)
  3002. logger.info(
  3003. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  3004. )
  3005. except Exception as e:
  3006. logger.warning("[LAYER-TL] Failed: %s", e)
  3007. # Try to cancel session on error
  3008. try:
  3009. cancel_session(printer_id)
  3010. except Exception:
  3011. pass # Best-effort timelapse session cancellation on error
  3012. asyncio.create_task(_background_layer_timelapse())
  3013. log_timing("All background tasks scheduled")
  3014. # Auto-scan for timelapse if recording was active during the print
  3015. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  3016. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  3017. # Schedule timelapse scan as background task with retries
  3018. # The printer needs time to encode the video after print completion
  3019. baseline = _timelapse_baselines.pop(printer_id, None)
  3020. asyncio.create_task(_scan_for_timelapse_with_retries(archive_id, baseline))
  3021. log_timing("Timelapse scan scheduled")
  3022. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  3023. # AMS sensor history recording
  3024. _ams_history_task: asyncio.Task | None = None
  3025. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  3026. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  3027. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  3028. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  3029. _ams_alarm_cooldown: dict[str, datetime] = {}
  3030. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  3031. async def record_ams_history():
  3032. """Background task to record AMS humidity and temperature data."""
  3033. logger = logging.getLogger(__name__)
  3034. # Wait a short time for MQTT connections to establish on startup
  3035. await asyncio.sleep(10)
  3036. while True:
  3037. try:
  3038. from backend.app.models.ams_history import AMSSensorHistory
  3039. from backend.app.models.printer import Printer
  3040. from backend.app.models.settings import Settings
  3041. async with async_session() as db:
  3042. # Get all active printers
  3043. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  3044. printers = result.scalars().all()
  3045. # Get alarm thresholds from settings
  3046. humidity_threshold = 60.0 # Default: fair threshold
  3047. temp_threshold = 35.0 # Default: fair threshold
  3048. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  3049. setting = result.scalar_one_or_none()
  3050. if setting:
  3051. try:
  3052. humidity_threshold = float(setting.value)
  3053. except (ValueError, TypeError):
  3054. pass # Keep default threshold if stored value is invalid
  3055. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  3056. setting = result.scalar_one_or_none()
  3057. if setting:
  3058. try:
  3059. temp_threshold = float(setting.value)
  3060. except (ValueError, TypeError):
  3061. pass # Keep default threshold if stored value is invalid
  3062. recorded_count = 0
  3063. for printer in printers:
  3064. # Get current state from printer manager
  3065. state = printer_manager.get_status(printer.id)
  3066. if not state or not state.connected or not state.raw_data:
  3067. continue # Skip disconnected printers - don't use stale data
  3068. raw_data = state.raw_data
  3069. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  3070. continue
  3071. # Record data for each AMS unit
  3072. for ams_data in raw_data["ams"]:
  3073. ams_id = int(ams_data.get("id", 0))
  3074. # Get humidity (prefer humidity_raw)
  3075. humidity_raw = ams_data.get("humidity_raw")
  3076. humidity_idx = ams_data.get("humidity")
  3077. humidity = None
  3078. if humidity_raw is not None:
  3079. try:
  3080. humidity = float(humidity_raw)
  3081. except (ValueError, TypeError):
  3082. pass # Skip unparseable humidity; will try fallback
  3083. if humidity is None and humidity_idx is not None:
  3084. try:
  3085. humidity = float(humidity_idx)
  3086. except (ValueError, TypeError):
  3087. pass # Skip unparseable humidity index value
  3088. # Get temperature
  3089. temperature = None
  3090. temp_str = ams_data.get("temp")
  3091. if temp_str is not None:
  3092. try:
  3093. temperature = float(temp_str)
  3094. except (ValueError, TypeError):
  3095. pass # Skip unparseable temperature value
  3096. # Skip if no data
  3097. if humidity is None and temperature is None:
  3098. continue
  3099. # Record the data point
  3100. history = AMSSensorHistory(
  3101. printer_id=printer.id,
  3102. ams_id=ams_id,
  3103. humidity=humidity,
  3104. humidity_raw=float(humidity_raw) if humidity_raw else None,
  3105. temperature=temperature,
  3106. )
  3107. db.add(history)
  3108. recorded_count += 1
  3109. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  3110. is_ams_ht = ams_id >= 128
  3111. if is_ams_ht:
  3112. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  3113. else:
  3114. ams_label = f"AMS-{chr(65 + ams_id)}"
  3115. # Check humidity alarm (only if above threshold)
  3116. if humidity is not None and humidity > humidity_threshold:
  3117. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  3118. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  3119. now = datetime.now(timezone.utc)
  3120. if (
  3121. last_alarm is None
  3122. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  3123. ):
  3124. _ams_alarm_cooldown[cooldown_key] = now
  3125. logger.info(
  3126. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {humidity_threshold}%"
  3127. )
  3128. try:
  3129. # Call different notification method based on AMS type
  3130. if is_ams_ht:
  3131. await notification_service.on_ams_ht_humidity_high(
  3132. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  3133. )
  3134. else:
  3135. await notification_service.on_ams_humidity_high(
  3136. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  3137. )
  3138. except Exception as e:
  3139. logger.warning("Failed to send humidity alarm: %s", e)
  3140. # Check temperature alarm (only if above threshold)
  3141. if temperature is not None and temperature > temp_threshold:
  3142. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  3143. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  3144. now = datetime.now(timezone.utc)
  3145. if (
  3146. last_alarm is None
  3147. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  3148. ):
  3149. _ams_alarm_cooldown[cooldown_key] = now
  3150. logger.info(
  3151. f"Sending temperature alarm for {printer.name} {ams_label}: {temperature}°C > {temp_threshold}°C"
  3152. )
  3153. try:
  3154. # Call different notification method based on AMS type
  3155. if is_ams_ht:
  3156. await notification_service.on_ams_ht_temperature_high(
  3157. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  3158. )
  3159. else:
  3160. await notification_service.on_ams_temperature_high(
  3161. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  3162. )
  3163. except Exception as e:
  3164. logger.warning("Failed to send temperature alarm: %s", e)
  3165. await db.commit()
  3166. if recorded_count > 0:
  3167. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  3168. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  3169. global _ams_cleanup_counter
  3170. _ams_cleanup_counter += 1
  3171. if _ams_cleanup_counter >= 288:
  3172. _ams_cleanup_counter = 0
  3173. # Get retention days from settings
  3174. from backend.app.models.settings import Settings
  3175. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  3176. setting = result.scalar_one_or_none()
  3177. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  3178. cutoff = datetime.utcnow() - timedelta(days=retention_days)
  3179. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  3180. await db.commit()
  3181. if result.rowcount > 0:
  3182. logger.info(
  3183. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  3184. )
  3185. # Wait until next recording interval
  3186. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  3187. except asyncio.CancelledError:
  3188. break
  3189. except Exception as e:
  3190. logger.warning("AMS history recording failed: %s", e)
  3191. await asyncio.sleep(60) # Wait a bit before retrying
  3192. def start_ams_history_recording():
  3193. """Start the AMS history recording background task."""
  3194. global _ams_history_task
  3195. if _ams_history_task is None:
  3196. _ams_history_task = asyncio.create_task(record_ams_history())
  3197. logging.getLogger(__name__).info("AMS history recording started")
  3198. def stop_ams_history_recording():
  3199. """Stop the AMS history recording background task."""
  3200. global _ams_history_task
  3201. if _ams_history_task:
  3202. _ams_history_task.cancel()
  3203. _ams_history_task = None
  3204. logging.getLogger(__name__).info("AMS history recording stopped")
  3205. # Printer runtime tracking
  3206. _runtime_tracking_task: asyncio.Task | None = None
  3207. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  3208. async def track_printer_runtime():
  3209. """Background task to track printer active runtime (RUNNING/PAUSE states)."""
  3210. logger = logging.getLogger(__name__)
  3211. # Wait for MQTT connections to establish on startup
  3212. await asyncio.sleep(15)
  3213. while True:
  3214. try:
  3215. from backend.app.models.printer import Printer
  3216. # Fetch printer IDs in a short-lived read-only session
  3217. async with async_session() as db:
  3218. result = await db.execute(
  3219. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  3220. Printer.is_active.is_(True)
  3221. )
  3222. )
  3223. printer_rows = result.all()
  3224. now = datetime.now(timezone.utc)
  3225. updated_count = 0
  3226. # Update each printer in its own short session to minimise write-lock
  3227. # hold time and avoid blocking critical commits like queue status
  3228. # updates (#897).
  3229. for pid, pname, runtime_secs, last_update in printer_rows:
  3230. state = printer_manager.get_status(pid)
  3231. if not state:
  3232. logger.debug("[%s] Runtime tracking: no state available", pname)
  3233. continue
  3234. if not state.connected:
  3235. logger.debug("[%s] Runtime tracking: not connected", pname)
  3236. continue
  3237. needs_commit = False
  3238. new_runtime = runtime_secs
  3239. new_last_update = last_update
  3240. if state.state in ("RUNNING", "PAUSE"):
  3241. if last_update:
  3242. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  3243. elapsed = (now - lu).total_seconds()
  3244. if elapsed > 0:
  3245. new_runtime = runtime_secs + int(elapsed)
  3246. updated_count += 1
  3247. needs_commit = True
  3248. logger.debug(
  3249. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  3250. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  3251. )
  3252. else:
  3253. needs_commit = True
  3254. logger.debug("[%s] Runtime tracking: first active detection", pname)
  3255. new_last_update = now
  3256. else:
  3257. if last_update is not None:
  3258. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  3259. new_last_update = None
  3260. needs_commit = True
  3261. if needs_commit:
  3262. try:
  3263. async with async_session() as db:
  3264. result = await db.execute(select(Printer).where(Printer.id == pid))
  3265. printer = result.scalar_one_or_none()
  3266. if printer:
  3267. printer.runtime_seconds = new_runtime
  3268. printer.last_runtime_update = new_last_update
  3269. await db.commit()
  3270. except Exception as e:
  3271. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  3272. if updated_count > 0:
  3273. logger.debug("Updated runtime for %s printer(s)", updated_count)
  3274. except asyncio.CancelledError:
  3275. logger.info("Runtime tracking cancelled")
  3276. break
  3277. except Exception as e:
  3278. logger.warning("Runtime tracking failed: %s", e)
  3279. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  3280. def start_runtime_tracking():
  3281. """Start the printer runtime tracking background task."""
  3282. global _runtime_tracking_task
  3283. if _runtime_tracking_task is None:
  3284. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  3285. logging.getLogger(__name__).info("Printer runtime tracking started")
  3286. def stop_runtime_tracking():
  3287. """Stop the printer runtime tracking background task."""
  3288. global _runtime_tracking_task
  3289. if _runtime_tracking_task:
  3290. _runtime_tracking_task.cancel()
  3291. _runtime_tracking_task = None
  3292. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  3293. # SpoolBuddy device watchdog
  3294. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  3295. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  3296. async def _spoolbuddy_watchdog_loop():
  3297. """Periodic check for SpoolBuddy devices that have gone offline."""
  3298. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  3299. while True:
  3300. try:
  3301. await spoolbuddy_watchdog()
  3302. except asyncio.CancelledError:
  3303. break
  3304. except Exception as e:
  3305. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  3306. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  3307. def start_spoolbuddy_watchdog():
  3308. global _spoolbuddy_watchdog_task
  3309. if _spoolbuddy_watchdog_task is None:
  3310. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  3311. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  3312. def stop_spoolbuddy_watchdog():
  3313. global _spoolbuddy_watchdog_task
  3314. if _spoolbuddy_watchdog_task:
  3315. _spoolbuddy_watchdog_task.cancel()
  3316. _spoolbuddy_watchdog_task = None
  3317. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  3318. # Camera stream orphan cleanup
  3319. _camera_cleanup_task: asyncio.Task | None = None
  3320. CAMERA_CLEANUP_INTERVAL = 60
  3321. async def _camera_cleanup_loop():
  3322. """Periodically clean up orphaned ffmpeg processes."""
  3323. from backend.app.api.routes.camera import cleanup_orphaned_streams
  3324. while True:
  3325. try:
  3326. await cleanup_orphaned_streams()
  3327. except asyncio.CancelledError:
  3328. break
  3329. except Exception as e:
  3330. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  3331. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  3332. def start_camera_cleanup():
  3333. global _camera_cleanup_task
  3334. if _camera_cleanup_task is None:
  3335. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  3336. logging.getLogger(__name__).info("Camera stream cleanup started")
  3337. def stop_camera_cleanup():
  3338. global _camera_cleanup_task
  3339. if _camera_cleanup_task:
  3340. _camera_cleanup_task.cancel()
  3341. _camera_cleanup_task = None
  3342. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  3343. # ---------------------------------------------------------------------------
  3344. # Expected-print TTL eviction
  3345. # ---------------------------------------------------------------------------
  3346. def _evict_stale_expected_prints() -> None:
  3347. """Remove entries from _expected_prints / _expected_print_creators that are
  3348. older than _EXPECTED_PRINT_TTL_SECONDS.
  3349. This prevents unbounded growth when a print is registered (via
  3350. register_expected_print) but on_print_start never fires — e.g. because the
  3351. printer disconnects, the app restarts, or the print is started directly from
  3352. the printer panel without going through the queue.
  3353. """
  3354. # Use monotonic time so the TTL is unaffected by system clock adjustments
  3355. # (e.g. NTP sync, DST changes).
  3356. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  3357. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  3358. if not stale_keys:
  3359. return
  3360. evicted_archive_ids: set[int] = set()
  3361. for key in stale_keys:
  3362. archive_id = _expected_prints.pop(key, None)
  3363. if archive_id is not None:
  3364. evicted_archive_ids.add(archive_id)
  3365. _expected_print_creators.pop(key, None)
  3366. _expected_print_registered_at.pop(key, None)
  3367. # Also clean up _print_ams_mappings for archive_ids that have no remaining
  3368. # live keys in _expected_prints (i.e. all variants were just evicted).
  3369. live_archive_ids = set(_expected_prints.values())
  3370. for archive_id in evicted_archive_ids:
  3371. if archive_id not in live_archive_ids:
  3372. _print_ams_mappings.pop(archive_id, None)
  3373. logging.getLogger(__name__).info(
  3374. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  3375. )
  3376. async def _expected_prints_cleanup_loop() -> None:
  3377. """Background task: periodically evict stale expected-print entries."""
  3378. while True:
  3379. try:
  3380. _evict_stale_expected_prints()
  3381. except asyncio.CancelledError:
  3382. raise
  3383. except Exception as e:
  3384. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  3385. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  3386. def start_expected_prints_cleanup() -> None:
  3387. global _expected_prints_cleanup_task
  3388. if _expected_prints_cleanup_task is None:
  3389. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  3390. logging.getLogger(__name__).info("Expected prints cleanup started")
  3391. def stop_expected_prints_cleanup() -> None:
  3392. global _expected_prints_cleanup_task
  3393. if _expected_prints_cleanup_task:
  3394. _expected_prints_cleanup_task.cancel()
  3395. _expected_prints_cleanup_task = None
  3396. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  3397. # ---------------------------------------------------------------------------
  3398. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  3399. # ---------------------------------------------------------------------------
  3400. _auth_cleanup_task: asyncio.Task | None = None
  3401. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  3402. async def _run_auth_cleanup() -> None:
  3403. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  3404. from backend.app.core.database import async_session
  3405. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  3406. from backend.app.models.user_totp import UserTOTP
  3407. now = datetime.now(timezone.utc)
  3408. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  3409. try:
  3410. async with async_session() as db:
  3411. stale_cutoff = now - timedelta(hours=1)
  3412. result = await db.execute(
  3413. select(UserTOTP).where(
  3414. UserTOTP.is_enabled.is_(False),
  3415. UserTOTP.created_at < stale_cutoff,
  3416. )
  3417. )
  3418. stale_records = result.scalars().all()
  3419. if stale_records:
  3420. for rec in stale_records:
  3421. await db.delete(rec)
  3422. await db.commit()
  3423. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  3424. except Exception as e:
  3425. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  3426. # Remove expired revoked-JTI entries (they are no longer needed once the
  3427. # original token's exp has passed — the token would be rejected by JWT
  3428. # signature verification regardless).
  3429. try:
  3430. async with async_session() as db:
  3431. await db.execute(
  3432. delete(AuthEphemeralToken).where(
  3433. AuthEphemeralToken.token_type == "revoked_jti",
  3434. AuthEphemeralToken.expires_at < now,
  3435. )
  3436. )
  3437. await db.commit()
  3438. except Exception as e:
  3439. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  3440. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  3441. # Events outside this window can never affect rate-limit decisions — they only
  3442. # consume DB space. Use the same window constant as the rate limiter so the
  3443. # two are always in sync.
  3444. try:
  3445. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  3446. async with async_session() as db:
  3447. await db.execute(
  3448. delete(AuthRateLimitEvent).where(
  3449. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  3450. )
  3451. )
  3452. await db.commit()
  3453. except Exception as e:
  3454. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  3455. async def _auth_cleanup_loop() -> None:
  3456. """Periodic background task: run auth cleanup every hour."""
  3457. while True:
  3458. try:
  3459. await _run_auth_cleanup()
  3460. except asyncio.CancelledError:
  3461. break
  3462. except Exception as e:
  3463. logging.warning("Auth cleanup loop error: %s", e)
  3464. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  3465. def start_auth_cleanup() -> None:
  3466. global _auth_cleanup_task
  3467. if _auth_cleanup_task is None:
  3468. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  3469. logging.getLogger(__name__).info("Auth periodic cleanup started")
  3470. def stop_auth_cleanup() -> None:
  3471. global _auth_cleanup_task
  3472. if _auth_cleanup_task:
  3473. _auth_cleanup_task.cancel()
  3474. _auth_cleanup_task = None
  3475. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  3476. @asynccontextmanager
  3477. async def lifespan(app: FastAPI):
  3478. # Startup
  3479. await init_db()
  3480. # Register an app-scoped httpx client for Bambu Cloud services so
  3481. # per-request BambuCloudService instances reuse the same connection pool
  3482. # (important for routes like /cloud/filament-info that chain many
  3483. # get_setting_detail calls). The shared client stores no region/token
  3484. # state, so the per-request ownership pattern that fixed the region-bleed
  3485. # bug is preserved.
  3486. import httpx as _httpx
  3487. from backend.app.services.bambu_cloud import set_shared_http_client
  3488. from backend.app.services.makerworld import (
  3489. set_shared_http_client as set_shared_makerworld_http_client,
  3490. )
  3491. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  3492. set_shared_http_client(_shared_cloud_http_client)
  3493. # Reuse the same connection pool for MakerWorld — different host, same
  3494. # keep-alive pool saves a TLS handshake per request.
  3495. set_shared_makerworld_http_client(_shared_cloud_http_client)
  3496. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  3497. # This can happen when a print was cancelled mid-print on versions before this fix.
  3498. try:
  3499. async with async_session() as db:
  3500. from backend.app.models.print_queue import PrintQueueItem
  3501. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  3502. aborted_items = result.scalars().all()
  3503. if aborted_items:
  3504. for item in aborted_items:
  3505. item.status = "cancelled"
  3506. await db.commit()
  3507. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  3508. except Exception as e:
  3509. logging.warning("Failed to fix aborted queue items: %s", e)
  3510. # Restore debug logging state from previous session
  3511. await init_debug_logging()
  3512. # Set up printer manager callbacks
  3513. loop = asyncio.get_event_loop()
  3514. printer_manager.set_event_loop(loop)
  3515. printer_manager.set_status_change_callback(on_printer_status_change)
  3516. printer_manager.set_print_start_callback(on_print_start)
  3517. printer_manager.set_print_complete_callback(on_print_complete)
  3518. printer_manager.set_ams_change_callback(on_ams_change)
  3519. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  3520. await printer_manager.load_awaiting_plate_clear_from_db()
  3521. # Layer change callback for external camera timelapse
  3522. async def on_layer_change(printer_id: int, layer_num: int):
  3523. """Capture timelapse frame on layer change + first layer notification."""
  3524. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  3525. await tl_layer_change(printer_id, layer_num)
  3526. # First layer complete notification (layer_num >= 2 means layer 1 is done)
  3527. if 2 <= layer_num <= 5 and not _first_layer_notified.get(printer_id, False):
  3528. _first_layer_notified[printer_id] = True
  3529. try:
  3530. async with async_session() as db:
  3531. from backend.app.models.printer import Printer
  3532. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3533. printer = result.scalar_one_or_none()
  3534. if not printer:
  3535. return
  3536. printer_name = printer.name
  3537. client = printer_manager.get_client(printer_id)
  3538. state = client.state if client else None
  3539. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  3540. total_layers = state.total_layers if state else 0
  3541. image_data = await _capture_snapshot_for_notification(
  3542. printer_id, printer, logging.getLogger(__name__)
  3543. )
  3544. await notification_service.on_first_layer_complete(
  3545. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  3546. )
  3547. except Exception as e:
  3548. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  3549. printer_manager.set_layer_change_callback(on_layer_change)
  3550. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  3551. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  3552. waiter = _bed_cool_waiters.get(printer_id)
  3553. if not waiter:
  3554. return
  3555. threshold = waiter["threshold"]
  3556. if bed_temp > threshold:
  3557. return
  3558. # Bed is at or below threshold — fire notification and remove waiter
  3559. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  3560. if not waiter_info:
  3561. return # Another callback already handled it
  3562. bed_cool_logger = logging.getLogger(__name__)
  3563. bed_cool_logger.info(
  3564. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  3565. bed_temp,
  3566. printer_id,
  3567. threshold,
  3568. )
  3569. try:
  3570. printer_info = printer_manager.get_printer(printer_id)
  3571. p_name = printer_info.name if printer_info else "Unknown"
  3572. async with async_session() as db:
  3573. await notification_service.on_bed_cooled(
  3574. printer_id=printer_id,
  3575. printer_name=p_name,
  3576. bed_temp=bed_temp,
  3577. threshold=threshold,
  3578. filename=waiter_info["filename"],
  3579. db=db,
  3580. )
  3581. except Exception as e:
  3582. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  3583. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  3584. # Initialize MQTT relay from settings
  3585. async with async_session() as db:
  3586. from backend.app.api.routes.settings import get_setting
  3587. mqtt_settings = {
  3588. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  3589. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  3590. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  3591. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  3592. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  3593. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  3594. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  3595. }
  3596. await mqtt_relay.configure(mqtt_settings)
  3597. # Restore MQTT smart plug subscriptions
  3598. if mqtt_settings.get("mqtt_enabled"):
  3599. from backend.app.models.smart_plug import SmartPlug
  3600. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  3601. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  3602. mqtt_plugs = result.scalars().all()
  3603. restored = 0
  3604. for plug in mqtt_plugs:
  3605. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  3606. restored += 1
  3607. if restored:
  3608. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  3609. # Connect to all active printers
  3610. async with async_session() as db:
  3611. await init_printer_connections(db)
  3612. # Auto-connect to Spoolman if enabled
  3613. async with async_session() as db:
  3614. from backend.app.api.routes.settings import get_setting
  3615. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  3616. spoolman_url = await get_setting(db, "spoolman_url")
  3617. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  3618. try:
  3619. client = await init_spoolman_client(spoolman_url)
  3620. if await client.health_check():
  3621. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  3622. # Ensure the 'tag' extra field exists for RFID/UUID storage
  3623. await client.ensure_tag_extra_field()
  3624. else:
  3625. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  3626. except Exception as e:
  3627. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  3628. # Start the print scheduler
  3629. asyncio.create_task(print_scheduler.run())
  3630. # Start background dispatch worker for send/start operations
  3631. await background_dispatch.start()
  3632. # Start the smart plug scheduler for time-based on/off
  3633. smart_plug_manager.start_scheduler()
  3634. # Resume any pending auto-offs that were interrupted by restart
  3635. await smart_plug_manager.resume_pending_auto_offs()
  3636. # Start the notification digest scheduler
  3637. notification_service.start_digest_scheduler()
  3638. # Start the GitHub backup scheduler
  3639. await github_backup_service.start_scheduler()
  3640. # Start the local backup scheduler
  3641. await local_backup_service.start_scheduler()
  3642. await obico_detection_service.start()
  3643. # Start the library trash sweeper (#1008)
  3644. await library_trash_service.start_scheduler()
  3645. # Start the archive auto-purge sweeper (#1008 follow-up)
  3646. await archive_purge_service.start_scheduler()
  3647. # Start AMS history recording
  3648. start_ams_history_recording()
  3649. # Start printer runtime tracking
  3650. start_runtime_tracking()
  3651. # Start SpoolBuddy device watchdog
  3652. start_spoolbuddy_watchdog()
  3653. # Start camera stream orphan cleanup
  3654. start_camera_cleanup()
  3655. # Start expected-print TTL eviction (prevents memory leak when prints are
  3656. # registered but on_print_start never fires)
  3657. start_expected_prints_cleanup()
  3658. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  3659. start_auth_cleanup()
  3660. # Initialize virtual printer manager and sync from DB
  3661. from backend.app.services.virtual_printer import virtual_printer_manager
  3662. virtual_printer_manager.set_session_factory(async_session)
  3663. try:
  3664. await virtual_printer_manager.sync_from_db()
  3665. logging.info("Virtual printer manager synced from database")
  3666. except Exception as e:
  3667. logging.warning("Failed to sync virtual printers: %s", e)
  3668. yield
  3669. # Shutdown
  3670. print_scheduler.stop()
  3671. await background_dispatch.stop()
  3672. smart_plug_manager.stop_scheduler()
  3673. notification_service.stop_digest_scheduler()
  3674. github_backup_service.stop_scheduler()
  3675. local_backup_service.stop_scheduler()
  3676. library_trash_service.stop_scheduler()
  3677. archive_purge_service.stop_scheduler()
  3678. obico_detection_service.stop()
  3679. stop_ams_history_recording()
  3680. stop_runtime_tracking()
  3681. stop_spoolbuddy_watchdog()
  3682. stop_camera_cleanup()
  3683. stop_expected_prints_cleanup()
  3684. stop_auth_cleanup()
  3685. printer_manager.disconnect_all()
  3686. await close_spoolman_client()
  3687. # Stop all virtual printer services
  3688. await virtual_printer_manager.stop_all()
  3689. await mqtt_smart_plug_service.disconnect(timeout=2)
  3690. await mqtt_relay.disconnect(timeout=2)
  3691. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  3692. set_shared_http_client(None)
  3693. set_shared_makerworld_http_client(None)
  3694. await _shared_cloud_http_client.aclose()
  3695. # Checkpoint WAL (SQLite only) and close all database connections
  3696. from backend.app.core.db_dialect import is_sqlite
  3697. if is_sqlite():
  3698. try:
  3699. async with engine.begin() as conn:
  3700. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  3701. logging.info("WAL checkpoint completed")
  3702. except Exception as e:
  3703. logging.warning("WAL checkpoint failed: %s", e)
  3704. await engine.dispose()
  3705. app = FastAPI(
  3706. title=app_settings.app_name,
  3707. description="Archive and manage Bambu Lab 3MF files",
  3708. version=APP_VERSION,
  3709. lifespan=lifespan,
  3710. )
  3711. # =============================================================================
  3712. # Authentication Middleware - Secures ALL API routes by default
  3713. # =============================================================================
  3714. # Public routes that don't require authentication even when auth is enabled
  3715. PUBLIC_API_ROUTES = {
  3716. # Auth routes needed before/during login
  3717. "/api/v1/auth/status",
  3718. "/api/v1/auth/login",
  3719. "/api/v1/auth/setup", # Needed for initial setup and recovery
  3720. # Advanced auth status needed for login page
  3721. "/api/v1/auth/advanced-auth/status",
  3722. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  3723. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  3724. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  3725. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  3726. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  3727. # OIDC routes that must be reachable without a JWT
  3728. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  3729. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  3730. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  3731. # Version check for updates (no sensitive data)
  3732. "/api/v1/updates/version",
  3733. # Metrics endpoint handles its own prometheus_token authentication
  3734. "/api/v1/metrics",
  3735. }
  3736. # Route prefixes that are public (for routes with dynamic segments)
  3737. PUBLIC_API_PREFIXES = [
  3738. # WebSocket connections handle their own auth
  3739. "/api/v1/ws",
  3740. # OIDC authorize redirects — include provider_id in path
  3741. "/api/v1/auth/oidc/authorize/",
  3742. ]
  3743. # Route patterns that are public (read-only display data)
  3744. # These are checked with "in path" - needed because browsers load images/videos
  3745. # via <img src> and <video src> which don't include Authorization headers
  3746. PUBLIC_API_PATTERNS = [
  3747. # Thumbnails
  3748. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  3749. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  3750. # Images and media
  3751. "/photos/", # /archives/{id}/photos/{filename}
  3752. "/project-image/", # /archives/{id}/project-image/{path}
  3753. "/qrcode", # /archives/{id}/qrcode
  3754. "/timelapse", # /archives/{id}/timelapse (video)
  3755. "/cover", # /printers/{id}/cover
  3756. "/icon", # /external-links/{id}/icon
  3757. # Camera (streams loaded via <img> tag)
  3758. "/camera/stream", # /printers/{id}/camera/stream
  3759. "/camera/snapshot", # /printers/{id}/camera/snapshot
  3760. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  3761. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  3762. # download token in the URL path instead.
  3763. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  3764. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  3765. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  3766. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  3767. ]
  3768. @app.middleware("http")
  3769. async def security_headers_middleware(request, call_next):
  3770. """Add standard HTTP security headers to every response."""
  3771. response = await call_next(request)
  3772. response.headers["X-Content-Type-Options"] = "nosniff"
  3773. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  3774. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  3775. # Content-Security-Policy for the React SPA.
  3776. # Notes:
  3777. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  3778. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  3779. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  3780. # - media-src blob:: timelapse video player uses Blob URLs.
  3781. # - font-src data:: some icon fonts are embedded as data URIs.
  3782. if request.url.path.startswith("/gcode-viewer"):
  3783. # The gcode viewer is embedded in an iframe served by this same origin,
  3784. # so frame-ancestors must allow 'self'. prettygcode.js also uses eval()
  3785. # internally, so script-src needs 'unsafe-eval'.
  3786. response.headers["Content-Security-Policy"] = (
  3787. "default-src 'self'; "
  3788. "script-src 'self' 'unsafe-eval'; "
  3789. "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
  3790. "img-src 'self' data: blob:; "
  3791. "media-src 'self' blob:; "
  3792. "connect-src 'self' ws: wss:; "
  3793. "font-src 'self' data: https://fonts.gstatic.com; "
  3794. "object-src 'none'; "
  3795. "base-uri 'self'; "
  3796. "frame-src 'self' http: https:; "
  3797. "frame-ancestors 'self';"
  3798. )
  3799. else:
  3800. response.headers["Content-Security-Policy"] = (
  3801. "default-src 'self'; "
  3802. "script-src 'self'; "
  3803. "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
  3804. "img-src 'self' data: blob:; "
  3805. "media-src 'self' blob:; "
  3806. "connect-src 'self' ws: wss:; "
  3807. "font-src 'self' data: https://fonts.gstatic.com; "
  3808. "object-src 'none'; "
  3809. "base-uri 'self'; "
  3810. "frame-src 'self' http: https:; "
  3811. "frame-ancestors 'none';"
  3812. )
  3813. if request.url.scheme == "https":
  3814. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  3815. return response
  3816. @app.middleware("http")
  3817. async def auth_middleware(request, call_next):
  3818. """Enforce authentication on all API routes when auth is enabled.
  3819. This middleware provides defense-in-depth by checking auth at the API gateway level,
  3820. regardless of whether individual routes have auth dependencies.
  3821. """
  3822. from starlette.responses import JSONResponse
  3823. path = request.url.path
  3824. # Only apply to API routes
  3825. if not path.startswith("/api/"):
  3826. return await call_next(request)
  3827. # Allow public routes
  3828. if path in PUBLIC_API_ROUTES:
  3829. return await call_next(request)
  3830. # Allow public prefixes
  3831. for prefix in PUBLIC_API_PREFIXES:
  3832. if path.startswith(prefix):
  3833. return await call_next(request)
  3834. # Allow public patterns (read-only display data like thumbnails)
  3835. for pattern in PUBLIC_API_PATTERNS:
  3836. if pattern in path:
  3837. return await call_next(request)
  3838. # Check if auth is enabled
  3839. try:
  3840. async with async_session() as db:
  3841. from backend.app.core.auth import is_auth_enabled
  3842. auth_enabled = await is_auth_enabled(db)
  3843. if not auth_enabled:
  3844. # Auth disabled, allow all requests
  3845. return await call_next(request)
  3846. except Exception:
  3847. # If we can't check auth status, allow request (fail open for DB issues)
  3848. return await call_next(request)
  3849. # Auth is enabled - require valid token
  3850. auth_header = request.headers.get("Authorization")
  3851. x_api_key = request.headers.get("X-API-Key")
  3852. # Check for API key auth first
  3853. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  3854. # API key authentication - let the request through to be validated by route handler
  3855. # API keys are validated per-route since they have different permission levels
  3856. return await call_next(request)
  3857. # Check for JWT auth
  3858. if not auth_header or not auth_header.startswith("Bearer "):
  3859. return JSONResponse(
  3860. status_code=401,
  3861. content={"detail": "Authentication required"},
  3862. headers={"WWW-Authenticate": "Bearer"},
  3863. )
  3864. # Validate JWT token
  3865. import jwt
  3866. try:
  3867. from backend.app.core.auth import (
  3868. ALGORITHM,
  3869. SECRET_KEY,
  3870. _is_token_fresh,
  3871. get_user_by_username,
  3872. is_jti_revoked,
  3873. )
  3874. token = auth_header.replace("Bearer ", "")
  3875. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  3876. username = payload.get("sub")
  3877. if not username:
  3878. raise ValueError("No username in token")
  3879. jti = payload.get("jti")
  3880. if not jti:
  3881. raise ValueError("No jti in token")
  3882. iat = payload.get("iat")
  3883. # Reject revoked tokens (defense-in-depth gateway check)
  3884. if await is_jti_revoked(jti):
  3885. return JSONResponse(
  3886. status_code=401,
  3887. content={"detail": "Token has been revoked"},
  3888. headers={"WWW-Authenticate": "Bearer"},
  3889. )
  3890. # Verify user exists, is active, and token is still fresh (L-R8-A)
  3891. async with async_session() as db:
  3892. user = await get_user_by_username(db, username)
  3893. if not user or not user.is_active:
  3894. return JSONResponse(
  3895. status_code=401,
  3896. content={"detail": "User not found or inactive"},
  3897. headers={"WWW-Authenticate": "Bearer"},
  3898. )
  3899. if not _is_token_fresh(iat, user):
  3900. return JSONResponse(
  3901. status_code=401,
  3902. content={"detail": "Token no longer valid"},
  3903. headers={"WWW-Authenticate": "Bearer"},
  3904. )
  3905. except jwt.ExpiredSignatureError:
  3906. return JSONResponse(
  3907. status_code=401,
  3908. content={"detail": "Token has expired"},
  3909. headers={"WWW-Authenticate": "Bearer"},
  3910. )
  3911. except (jwt.InvalidTokenError, ValueError, Exception):
  3912. return JSONResponse(
  3913. status_code=401,
  3914. content={"detail": "Invalid token"},
  3915. headers={"WWW-Authenticate": "Bearer"},
  3916. )
  3917. return await call_next(request)
  3918. # API routes
  3919. app.include_router(auth.router, prefix=app_settings.api_prefix)
  3920. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  3921. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  3922. app.include_router(users.router, prefix=app_settings.api_prefix)
  3923. app.include_router(groups.router, prefix=app_settings.api_prefix)
  3924. app.include_router(printers.router, prefix=app_settings.api_prefix)
  3925. app.include_router(archives.router, prefix=app_settings.api_prefix)
  3926. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  3927. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  3928. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  3929. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  3930. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  3931. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  3932. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  3933. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  3934. app.include_router(background_dispatch_routes.router, prefix=app_settings.api_prefix)
  3935. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  3936. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  3937. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  3938. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  3939. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  3940. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  3941. app.include_router(updates.router, prefix=app_settings.api_prefix)
  3942. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  3943. app.include_router(camera.router, prefix=app_settings.api_prefix)
  3944. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  3945. app.include_router(projects.router, prefix=app_settings.api_prefix)
  3946. app.include_router(library.router, prefix=app_settings.api_prefix)
  3947. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  3948. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  3949. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  3950. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  3951. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  3952. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  3953. app.include_router(system.router, prefix=app_settings.api_prefix)
  3954. app.include_router(support.router, prefix=app_settings.api_prefix)
  3955. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  3956. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  3957. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  3958. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  3959. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  3960. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  3961. app.include_router(obico.router, prefix=app_settings.api_prefix)
  3962. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  3963. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  3964. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  3965. # Serve static files (React build)
  3966. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  3967. app.mount(
  3968. "/assets",
  3969. StaticFiles(directory=app_settings.static_dir / "assets"),
  3970. name="assets",
  3971. )
  3972. if (app_settings.static_dir / "img").exists():
  3973. app.mount(
  3974. "/img",
  3975. StaticFiles(directory=app_settings.static_dir / "img"),
  3976. name="img",
  3977. )
  3978. if (app_settings.static_dir / "icons").exists():
  3979. app.mount(
  3980. "/icons",
  3981. StaticFiles(directory=app_settings.static_dir / "icons"),
  3982. name="icons",
  3983. )
  3984. @app.get("/")
  3985. async def serve_frontend():
  3986. """Serve the React frontend."""
  3987. index_file = app_settings.static_dir / "index.html"
  3988. if index_file.exists():
  3989. return FileResponse(index_file)
  3990. return {
  3991. "message": "Bambuddy API",
  3992. "docs": "/docs",
  3993. "frontend": "Build and place React app in /static directory",
  3994. }
  3995. @app.get("/health")
  3996. async def health_check():
  3997. """Health check endpoint."""
  3998. return {"status": "healthy"}
  3999. @app.get("/manifest.json")
  4000. async def serve_manifest():
  4001. """Serve PWA manifest."""
  4002. manifest_file = app_settings.static_dir / "manifest.json"
  4003. if manifest_file.exists():
  4004. return FileResponse(manifest_file, media_type="application/manifest+json")
  4005. return {"error": "Manifest not found"}
  4006. @app.get("/sw.js")
  4007. async def serve_service_worker():
  4008. """Serve service worker."""
  4009. sw_file = app_settings.static_dir / "sw.js"
  4010. if sw_file.exists():
  4011. return FileResponse(
  4012. sw_file,
  4013. media_type="application/javascript",
  4014. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  4015. )
  4016. return {"error": "Service worker not found"}
  4017. @app.get("/sw-register.js")
  4018. async def serve_sw_register():
  4019. """Serve the service-worker registration bootstrap script.
  4020. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  4021. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  4022. """
  4023. reg_file = app_settings.static_dir / "sw-register.js"
  4024. if reg_file.exists():
  4025. return FileResponse(reg_file, media_type="application/javascript")
  4026. return {"error": "sw-register.js not found"}
  4027. # ── GCode viewer static files ────────────────────────────────────────────────
  4028. # Served via explicit routes so ordering is guaranteed (app.mount() loses
  4029. # to the /{full_path:path} catch-all in some Starlette versions).
  4030. _gcode_viewer_dir = (app_settings.static_dir.parent / "gcode_viewer").resolve()
  4031. def _gcode_viewer_response(rel: str) -> FileResponse:
  4032. from fastapi import HTTPException as _HTTPException
  4033. safe = (_gcode_viewer_dir / rel).resolve()
  4034. if not safe.is_relative_to(_gcode_viewer_dir):
  4035. raise _HTTPException(status_code=403)
  4036. if safe.is_file():
  4037. mt, _ = _mimetypes.guess_type(str(safe))
  4038. return FileResponse(str(safe), media_type=mt or "application/octet-stream")
  4039. raise _HTTPException(status_code=404)
  4040. @app.get("/gcode-viewer/")
  4041. async def serve_gcode_viewer_index() -> FileResponse:
  4042. """Raw PrettyGCode viewer for the iframe. The bare ``/gcode-viewer``
  4043. (no trailing slash) intentionally falls through to the SPA catch-all so a
  4044. full-page reload re-enters the React layout instead of serving the iframe
  4045. contents standalone."""
  4046. return _gcode_viewer_response("index.html")
  4047. @app.get("/gcode-viewer/{file_path:path}")
  4048. async def serve_gcode_viewer_file(file_path: str) -> FileResponse:
  4049. return _gcode_viewer_response(file_path)
  4050. # Catch-all route for React Router (must be last)
  4051. @app.get("/{full_path:path}")
  4052. async def serve_spa(full_path: str):
  4053. """Serve React app for client-side routing."""
  4054. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  4055. if full_path.startswith("api/"):
  4056. from fastapi import HTTPException
  4057. raise HTTPException(status_code=404, detail="Not found")
  4058. index_file = app_settings.static_dir / "index.html"
  4059. if index_file.exists():
  4060. return FileResponse(index_file)
  4061. return {"error": "Frontend not built"}