main.py 115 KB

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