main.py 174 KB

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