main.py 118 KB

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