main.py 197 KB

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