main.py 103 KB

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