main.py 111 KB

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