main.py 133 KB

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