main.py 116 KB

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