main.py 118 KB

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