main.py 111 KB

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