main.py 111 KB

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