main.py 130 KB

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