main.py 133 KB

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