main.py 131 KB

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