main.py 155 KB

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