main.py 137 KB

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