main.py 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772
  1. import asyncio
  2. import logging
  3. from contextlib import asynccontextmanager
  4. from datetime import 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. camera,
  49. cloud,
  50. discovery,
  51. external_links,
  52. filaments,
  53. kprofiles,
  54. maintenance,
  55. notification_templates,
  56. notifications,
  57. pending_uploads,
  58. print_queue,
  59. printers,
  60. projects,
  61. settings as settings_routes,
  62. smart_plugs,
  63. spoolman,
  64. system,
  65. updates,
  66. webhook,
  67. websocket,
  68. )
  69. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  70. from backend.app.core.database import async_session, init_db
  71. from backend.app.core.websocket import ws_manager
  72. from backend.app.models.smart_plug import SmartPlug
  73. from backend.app.services.archive import ArchiveService
  74. from backend.app.services.bambu_ftp import download_file_async
  75. from backend.app.services.bambu_mqtt import PrinterState
  76. from backend.app.services.notification_service import notification_service
  77. from backend.app.services.print_scheduler import scheduler as print_scheduler
  78. from backend.app.services.printer_manager import (
  79. init_printer_connections,
  80. printer_manager,
  81. printer_state_to_dict,
  82. )
  83. from backend.app.services.smart_plug_manager import smart_plug_manager
  84. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  85. from backend.app.services.tasmota import tasmota_service
  86. from backend.app.services.telemetry import start_telemetry_loop
  87. # Track active prints: {(printer_id, filename): archive_id}
  88. _active_prints: dict[tuple[int, str], int] = {}
  89. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  90. # {(printer_id, filename): archive_id}
  91. _expected_prints: dict[tuple[int, str], int] = {}
  92. # Track starting energy for prints: {archive_id: starting_kwh}
  93. _print_energy_start: dict[int, float] = {}
  94. def register_expected_print(printer_id: int, filename: str, archive_id: int):
  95. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  96. # Store with multiple filename variations to catch different naming patterns
  97. _expected_prints[(printer_id, filename)] = archive_id
  98. # Also store without .3mf extension if present
  99. if filename.endswith(".3mf"):
  100. base = filename[:-4]
  101. _expected_prints[(printer_id, base)] = archive_id
  102. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  103. logging.getLogger(__name__).info(
  104. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}"
  105. )
  106. _last_status_broadcast: dict[int, str] = {}
  107. _nozzle_count_updated: set[int] = set() # Track printers where we've updated nozzle_count
  108. async def _report_spoolman_usage(printer_id: int, archive_id: int, logger):
  109. """Report filament usage to Spoolman after print completion.
  110. This finds the spool by RFID tag_uid from current AMS state and reports
  111. the filament_used_grams from the archive metadata.
  112. """
  113. async with async_session() as db:
  114. from backend.app.api.routes.settings import get_setting
  115. from backend.app.models.archive import PrintArchive
  116. # Check if Spoolman is enabled
  117. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  118. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  119. return
  120. # Get Spoolman URL
  121. spoolman_url = await get_setting(db, "spoolman_url")
  122. if not spoolman_url:
  123. return
  124. # Get or create Spoolman client
  125. client = await get_spoolman_client()
  126. if not client:
  127. client = await init_spoolman_client(spoolman_url)
  128. # Check if Spoolman is reachable
  129. if not await client.health_check():
  130. logger.warning("Spoolman not reachable for usage reporting")
  131. return
  132. # Get archive to find filament usage
  133. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  134. archive = result.scalar_one_or_none()
  135. if not archive or not archive.filament_used_grams:
  136. logger.debug(f"No filament usage data for archive {archive_id}")
  137. return
  138. filament_used = archive.filament_used_grams
  139. logger.info(f"[SPOOLMAN] Archive {archive_id} used {filament_used}g of filament")
  140. # Get current AMS state from printer to find the active spool
  141. state = printer_manager.get_status(printer_id)
  142. if not state or not state.raw_data:
  143. logger.debug("No printer state available for usage reporting")
  144. return
  145. ams_data = state.raw_data.get("ams")
  146. if not ams_data:
  147. logger.debug("No AMS data available for usage reporting")
  148. return
  149. # Find spools with RFID tags in Spoolman and report usage
  150. # For now, we report usage to the first spool found with a matching tag
  151. # TODO: In future, track which specific trays were used during the print
  152. spools_updated = 0
  153. for ams_unit in ams_data:
  154. trays = ams_unit.get("tray", [])
  155. for tray_data in trays:
  156. tag_uid = tray_data.get("tag_uid")
  157. if not tag_uid:
  158. continue
  159. # Find spool in Spoolman by tag
  160. spool = await client.find_spool_by_tag(tag_uid)
  161. if spool:
  162. # Report usage to Spoolman
  163. result = await client.use_spool(spool["id"], filament_used)
  164. if result:
  165. logger.info(
  166. f"[SPOOLMAN] Reported {filament_used}g usage to spool {spool['id']} (tag: {tag_uid})"
  167. )
  168. spools_updated += 1
  169. # Only report to one spool for single-material prints
  170. # Multi-material prints would need more sophisticated tracking
  171. return
  172. if spools_updated == 0:
  173. logger.debug(f"No matching Spoolman spools found for printer {printer_id}")
  174. async def on_printer_status_change(printer_id: int, state: PrinterState):
  175. """Handle printer status changes - broadcast via WebSocket."""
  176. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  177. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  178. temps = state.temperatures or {}
  179. nozzle_temp = round(temps.get("nozzle", 0))
  180. bed_temp = round(temps.get("bed", 0))
  181. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  182. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  183. # Auto-detect dual-nozzle printers from MQTT temperature data
  184. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  185. _nozzle_count_updated.add(printer_id)
  186. # Update nozzle_count in database
  187. async with async_session() as db:
  188. from backend.app.models.printer import Printer
  189. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  190. printer = result.scalar_one_or_none()
  191. if printer and printer.nozzle_count != 2:
  192. printer.nozzle_count = 2
  193. await db.commit()
  194. logging.getLogger(__name__).info(
  195. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  196. )
  197. # Include target temps for heating phase detection
  198. bed_target = round(temps.get("bed_target", 0))
  199. nozzle_target = round(temps.get("nozzle_target", 0))
  200. status_key = (
  201. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  202. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  203. f"{state.stg_cur}:{bed_target}:{nozzle_target}"
  204. )
  205. if _last_status_broadcast.get(printer_id) == status_key:
  206. return # No change, skip broadcast
  207. _last_status_broadcast[printer_id] = status_key
  208. await ws_manager.send_printer_status(
  209. printer_id,
  210. printer_state_to_dict(state, printer_id),
  211. )
  212. async def on_ams_change(printer_id: int, ams_data: list):
  213. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  214. import logging
  215. logger = logging.getLogger(__name__)
  216. try:
  217. async with async_session() as db:
  218. from backend.app.api.routes.settings import get_setting
  219. from backend.app.models.printer import Printer
  220. # Check if Spoolman is enabled
  221. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  222. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  223. return
  224. # Check sync mode
  225. sync_mode = await get_setting(db, "spoolman_sync_mode")
  226. if sync_mode and sync_mode != "auto":
  227. return # Only sync on auto mode
  228. # Get Spoolman URL
  229. spoolman_url = await get_setting(db, "spoolman_url")
  230. if not spoolman_url:
  231. return
  232. # Get or create Spoolman client
  233. client = await get_spoolman_client()
  234. if not client:
  235. client = await init_spoolman_client(spoolman_url)
  236. # Check if Spoolman is reachable
  237. if not await client.health_check():
  238. logger.warning(f"Spoolman not reachable at {spoolman_url}")
  239. return
  240. # Get printer name for location
  241. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  242. printer = result.scalar_one_or_none()
  243. printer_name = printer.name if printer else f"Printer {printer_id}"
  244. # Sync each AMS tray
  245. synced = 0
  246. for ams_unit in ams_data:
  247. ams_id = int(ams_unit.get("id", 0))
  248. trays = ams_unit.get("tray", [])
  249. for tray_data in trays:
  250. tray = client.parse_ams_tray(ams_id, tray_data)
  251. if not tray:
  252. continue # Empty tray
  253. try:
  254. result = await client.sync_ams_tray(tray, printer_name)
  255. if result:
  256. synced += 1
  257. except Exception as e:
  258. logger.error(f"Error syncing AMS {ams_id} tray {tray.tray_id}: {e}")
  259. if synced > 0:
  260. logger.info(f"Auto-synced {synced} AMS trays to Spoolman for printer {printer_id}")
  261. except Exception as e:
  262. import logging
  263. logging.getLogger(__name__).warning(f"Spoolman AMS sync failed: {e}")
  264. async def _send_print_start_notification(
  265. printer_id: int,
  266. data: dict,
  267. archive_data: dict | None = None,
  268. logger=None,
  269. ):
  270. """Helper to send print start notification with optional archive data."""
  271. if logger is None:
  272. import logging
  273. logger = logging.getLogger(__name__)
  274. try:
  275. async with async_session() as db:
  276. from backend.app.models.printer import Printer
  277. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  278. printer = result.scalar_one_or_none()
  279. printer_name = printer.name if printer else f"Printer {printer_id}"
  280. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  281. except Exception as e:
  282. logger.warning(f"Notification on_print_start failed: {e}")
  283. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  284. """Extract printable objects from an archive's 3MF file and store in printer state."""
  285. try:
  286. from backend.app.services.archive import extract_printable_objects_from_3mf
  287. file_path = app_settings.base_dir / archive.file_path
  288. if file_path.exists() and str(file_path).endswith(".3mf"):
  289. with open(file_path, "rb") as f:
  290. threemf_data = f.read()
  291. # Extract with positions for UI overlay
  292. printable_objects = extract_printable_objects_from_3mf(threemf_data, include_positions=True)
  293. if printable_objects:
  294. client = printer_manager.get_client(printer_id)
  295. if client:
  296. client.state.printable_objects = printable_objects
  297. client.state.skipped_objects = []
  298. logger.info(f"Loaded {len(printable_objects)} printable objects for printer {printer_id}")
  299. except Exception as e:
  300. logger.debug(f"Failed to extract printable objects from archive: {e}")
  301. async def on_print_start(printer_id: int, data: dict):
  302. """Handle print start - archive the 3MF file immediately."""
  303. import logging
  304. logger = logging.getLogger(__name__)
  305. logger.info(f"[CALLBACK] on_print_start called for printer {printer_id}, data keys: {list(data.keys())}")
  306. await ws_manager.send_print_start(printer_id, data)
  307. # Track if notification was sent (to avoid sending twice)
  308. notification_sent = False
  309. # Smart plug automation: turn on plug when print starts
  310. try:
  311. async with async_session() as db:
  312. await smart_plug_manager.on_print_start(printer_id, db)
  313. except Exception as e:
  314. logger.warning(f"Smart plug on_print_start failed: {e}")
  315. async with async_session() as db:
  316. from backend.app.models.printer import Printer
  317. from backend.app.services.bambu_ftp import list_files_async
  318. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  319. printer = result.scalar_one_or_none()
  320. if not printer or not printer.auto_archive:
  321. # Send notification without archive data (auto-archive disabled)
  322. logger.info(
  323. f"[CALLBACK] Skipping archive - printer: {printer is not None}, auto_archive: {printer.auto_archive if printer else 'N/A'}"
  324. )
  325. if not notification_sent:
  326. await _send_print_start_notification(printer_id, data, logger=logger)
  327. return
  328. # Get the filename and subtask_name
  329. filename = data.get("filename", "")
  330. subtask_name = data.get("subtask_name", "")
  331. logger.info(f"[CALLBACK] Print start detected - filename: {filename}, subtask: {subtask_name}")
  332. if not filename and not subtask_name:
  333. # Send notification without archive data (no filename)
  334. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  335. if not notification_sent:
  336. await _send_print_start_notification(printer_id, data, logger=logger)
  337. return
  338. # Check if this is an expected print from reprint/scheduled
  339. # Build list of possible keys to check
  340. expected_keys = []
  341. if subtask_name:
  342. expected_keys.append((printer_id, subtask_name))
  343. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  344. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  345. if filename:
  346. fname = filename.split("/")[-1] if "/" in filename else filename
  347. expected_keys.append((printer_id, fname))
  348. # Strip extensions to match
  349. base = fname.replace(".gcode", "").replace(".3mf", "")
  350. expected_keys.append((printer_id, base))
  351. expected_keys.append((printer_id, f"{base}.3mf"))
  352. expected_archive_id = None
  353. for key in expected_keys:
  354. expected_archive_id = _expected_prints.pop(key, None)
  355. if expected_archive_id:
  356. # Clean up other possible keys for this print
  357. for other_key in expected_keys:
  358. _expected_prints.pop(other_key, None)
  359. break
  360. if expected_archive_id:
  361. # This is a reprint/scheduled print - use existing archive, don't create new one
  362. logger.info(f"Using expected archive {expected_archive_id} for print (skipping duplicate)")
  363. from datetime import datetime
  364. from backend.app.models.archive import PrintArchive
  365. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  366. archive = result.scalar_one_or_none()
  367. if archive:
  368. # Update archive status to printing
  369. archive.status = "printing"
  370. archive.started_at = datetime.now()
  371. await db.commit()
  372. # Track as active print
  373. _active_prints[(printer_id, archive.filename)] = archive.id
  374. if subtask_name:
  375. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  376. # Set up energy tracking
  377. try:
  378. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  379. plug = plug_result.scalar_one_or_none()
  380. logger.info(
  381. f"[ENERGY] Print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}"
  382. )
  383. if plug:
  384. energy = await tasmota_service.get_energy(plug)
  385. logger.info(f"[ENERGY] Energy response from plug: {energy}")
  386. if energy and energy.get("total") is not None:
  387. _print_energy_start[archive.id] = energy["total"]
  388. logger.info(
  389. f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh"
  390. )
  391. else:
  392. logger.warning(f"[ENERGY] No 'total' in energy response for archive {archive.id}")
  393. else:
  394. logger.info(f"[ENERGY] No smart plug found for printer {printer_id}")
  395. except Exception as e:
  396. logger.warning(f"Failed to record starting energy: {e}")
  397. await ws_manager.send_archive_updated(
  398. {
  399. "id": archive.id,
  400. "status": "printing",
  401. }
  402. )
  403. # Send notification with archive data (reprint/scheduled)
  404. if not notification_sent:
  405. archive_data = {"print_time_seconds": archive.print_time_seconds}
  406. await _send_print_start_notification(printer_id, data, archive_data, logger)
  407. # Extract printable objects from the archived 3MF file
  408. _load_objects_from_archive(archive, printer_id, logger)
  409. return # Skip creating a new archive
  410. # Check if there's already a "printing" archive for this printer/file
  411. # This prevents duplicates when backend restarts during an active print
  412. from backend.app.models.archive import PrintArchive
  413. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  414. existing = await db.execute(
  415. select(PrintArchive)
  416. .where(PrintArchive.printer_id == printer_id)
  417. .where(PrintArchive.status == "printing")
  418. .where(PrintArchive.print_name.ilike(f"%{check_name}%"))
  419. .order_by(PrintArchive.created_at.desc())
  420. .limit(1)
  421. )
  422. existing_archive = existing.scalar_one_or_none()
  423. if existing_archive:
  424. logger.info(f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}")
  425. # Track this as the active print
  426. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  427. # Also set up energy tracking if not already tracked
  428. if existing_archive.id not in _print_energy_start:
  429. try:
  430. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  431. plug = plug_result.scalar_one_or_none()
  432. if plug:
  433. energy = await tasmota_service.get_energy(plug)
  434. if energy and energy.get("total") is not None:
  435. _print_energy_start[existing_archive.id] = energy["total"]
  436. logger.info(
  437. f"Recorded starting energy for existing archive {existing_archive.id}: {energy['total']} kWh"
  438. )
  439. except Exception as e:
  440. logger.warning(f"Failed to record starting energy for existing archive: {e}")
  441. # Send notification with archive data (existing archive)
  442. if not notification_sent:
  443. archive_data = {"print_time_seconds": existing_archive.print_time_seconds}
  444. await _send_print_start_notification(printer_id, data, archive_data, logger)
  445. # Extract printable objects from the archived 3MF file
  446. _load_objects_from_archive(existing_archive, printer_id, logger)
  447. return
  448. # Build list of possible 3MF filenames to try
  449. possible_names = []
  450. # Bambu printers typically store files as "Name.gcode.3mf"
  451. # The subtask_name is usually the best source for the filename
  452. if subtask_name:
  453. # Try common Bambu naming patterns
  454. possible_names.append(f"{subtask_name}.gcode.3mf")
  455. possible_names.append(f"{subtask_name}.3mf")
  456. # Try original filename with .3mf extension
  457. if filename:
  458. # Extract just the filename part, not the full path
  459. fname = filename.split("/")[-1] if "/" in filename else filename
  460. if fname.endswith(".3mf"):
  461. possible_names.append(fname)
  462. elif fname.endswith(".gcode"):
  463. base = fname.rsplit(".", 1)[0]
  464. possible_names.append(f"{base}.gcode.3mf")
  465. possible_names.append(f"{base}.3mf")
  466. else:
  467. possible_names.append(f"{fname}.gcode.3mf")
  468. possible_names.append(f"{fname}.3mf")
  469. # Remove duplicates while preserving order
  470. seen = set()
  471. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  472. logger.info(f"Trying filenames: {possible_names}")
  473. # Try to find and download the 3MF file
  474. temp_path = None
  475. downloaded_filename = None
  476. for try_filename in possible_names:
  477. if not try_filename.endswith(".3mf"):
  478. continue
  479. remote_paths = [
  480. f"/cache/{try_filename}",
  481. f"/model/{try_filename}",
  482. f"/{try_filename}",
  483. ]
  484. temp_path = app_settings.archive_dir / "temp" / try_filename
  485. temp_path.parent.mkdir(parents=True, exist_ok=True)
  486. for remote_path in remote_paths:
  487. logger.debug(f"Trying FTP download: {remote_path}")
  488. try:
  489. if await download_file_async(
  490. printer.ip_address,
  491. printer.access_code,
  492. remote_path,
  493. temp_path,
  494. ):
  495. downloaded_filename = try_filename
  496. logger.info(f"Downloaded: {remote_path}")
  497. break
  498. except Exception as e:
  499. logger.debug(f"FTP download failed for {remote_path}: {e}")
  500. if downloaded_filename:
  501. break
  502. # If still not found, try listing /cache to find matching file
  503. if not downloaded_filename and (filename or subtask_name):
  504. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  505. try:
  506. cache_files = await list_files_async(printer.ip_address, printer.access_code, "/cache")
  507. for f in cache_files:
  508. if f.get("is_directory"):
  509. continue
  510. fname = f.get("name", "")
  511. if fname.endswith(".3mf") and search_term in fname.lower():
  512. temp_path = app_settings.archive_dir / "temp" / fname
  513. temp_path.parent.mkdir(parents=True, exist_ok=True)
  514. if await download_file_async(
  515. printer.ip_address,
  516. printer.access_code,
  517. f"/cache/{fname}",
  518. temp_path,
  519. ):
  520. downloaded_filename = fname
  521. logger.info(f"Found and downloaded from cache: {fname}")
  522. break
  523. except Exception as e:
  524. logger.warning(f"Failed to list cache: {e}")
  525. if not downloaded_filename or not temp_path:
  526. logger.warning(f"Could not find 3MF file for print: {filename or subtask_name}")
  527. # Send notification without archive data (file not found)
  528. if not notification_sent:
  529. await _send_print_start_notification(printer_id, data, logger=logger)
  530. return
  531. try:
  532. # Archive the file with status "printing"
  533. service = ArchiveService(db)
  534. archive = await service.archive_print(
  535. printer_id=printer_id,
  536. source_file=temp_path,
  537. print_data={**data, "status": "printing"},
  538. )
  539. if archive:
  540. # Track this active print (use both original filename and downloaded filename)
  541. _active_prints[(printer_id, downloaded_filename)] = archive.id
  542. if filename and filename != downloaded_filename:
  543. _active_prints[(printer_id, filename)] = archive.id
  544. if subtask_name:
  545. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  546. logger.info(f"Created archive {archive.id} for {downloaded_filename}")
  547. # Record starting energy from smart plug if available
  548. try:
  549. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  550. plug = plug_result.scalar_one_or_none()
  551. logger.info(
  552. f"[ENERGY] Auto-archive print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}"
  553. )
  554. if plug:
  555. energy = await tasmota_service.get_energy(plug)
  556. logger.info(f"[ENERGY] Auto-archive energy response: {energy}")
  557. if energy and energy.get("total") is not None:
  558. _print_energy_start[archive.id] = energy["total"]
  559. logger.info(
  560. f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh"
  561. )
  562. else:
  563. logger.warning(f"[ENERGY] No 'total' in energy response for archive {archive.id}")
  564. else:
  565. logger.info(f"[ENERGY] No smart plug found for printer {printer_id}")
  566. except Exception as e:
  567. logger.warning(f"Failed to record starting energy: {e}")
  568. await ws_manager.send_archive_created(
  569. {
  570. "id": archive.id,
  571. "printer_id": archive.printer_id,
  572. "filename": archive.filename,
  573. "print_name": archive.print_name,
  574. "status": archive.status,
  575. }
  576. )
  577. # Send notification with archive data (new archive created)
  578. if not notification_sent:
  579. archive_data = {"print_time_seconds": archive.print_time_seconds}
  580. await _send_print_start_notification(printer_id, data, archive_data, logger)
  581. notification_sent = True
  582. # Extract printable objects for skip object functionality
  583. try:
  584. from backend.app.services.archive import extract_printable_objects_from_3mf
  585. with open(temp_path, "rb") as f:
  586. threemf_data = f.read()
  587. # Extract with positions for UI overlay
  588. printable_objects = extract_printable_objects_from_3mf(threemf_data, include_positions=True)
  589. if printable_objects:
  590. # Store objects in printer state
  591. client = printer_manager.get_client(printer_id)
  592. if client:
  593. client.state.printable_objects = printable_objects
  594. client.state.skipped_objects = [] # Reset skipped objects for new print
  595. logger.info(f"Loaded {len(printable_objects)} printable objects for printer {printer_id}")
  596. except Exception as e:
  597. logger.debug(f"Failed to extract printable objects: {e}")
  598. finally:
  599. if temp_path and temp_path.exists():
  600. temp_path.unlink()
  601. async def _scan_for_timelapse_with_retries(archive_id: int):
  602. """
  603. Scan for timelapse with retries.
  604. The printer encodes the timelapse quickly after print completion.
  605. We just need a short delay then grab the most recent file.
  606. Since we KNOW timelapse was active (from MQTT ipcam data), the most recent
  607. file in /timelapse is our target. Retries handle FTP connection issues.
  608. """
  609. import logging
  610. logger = logging.getLogger(__name__)
  611. # Short delays - printer usually finishes encoding within seconds
  612. retry_delays = [5, 10, 20]
  613. for attempt, delay in enumerate(retry_delays, 1):
  614. logger.info(
  615. f"[TIMELAPSE] Attempt {attempt}/{len(retry_delays)}: waiting {delay}s before scanning for archive {archive_id}"
  616. )
  617. await asyncio.sleep(delay)
  618. try:
  619. async with async_session() as db:
  620. from backend.app.models.printer import Printer
  621. from backend.app.services.bambu_ftp import download_file_bytes_async, list_files_async
  622. # Get archive (ArchiveService from module-level import)
  623. service = ArchiveService(db)
  624. archive = await service.get_archive(archive_id)
  625. if not archive:
  626. logger.warning(f"[TIMELAPSE] Archive {archive_id} not found, stopping retries")
  627. return
  628. if archive.timelapse_path:
  629. logger.info(f"[TIMELAPSE] Archive {archive_id} already has timelapse attached, stopping retries")
  630. return
  631. if not archive.printer_id:
  632. logger.warning(f"[TIMELAPSE] Archive {archive_id} has no printer, stopping retries")
  633. return
  634. # Get printer
  635. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  636. printer = result.scalar_one_or_none()
  637. if not printer:
  638. logger.warning(f"[TIMELAPSE] Printer not found for archive {archive_id}, stopping retries")
  639. return
  640. # Scan timelapse directory on printer
  641. # H2D may store in different locations than X1C
  642. files = []
  643. found_path = None
  644. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  645. try:
  646. found_files = await list_files_async(printer.ip_address, printer.access_code, timelapse_path)
  647. if found_files:
  648. files = found_files
  649. found_path = timelapse_path
  650. logger.info(f"[TIMELAPSE] Attempt {attempt}: Found {len(files)} files in {timelapse_path}")
  651. break
  652. except Exception as e:
  653. logger.debug(f"[TIMELAPSE] Path {timelapse_path} failed: {e}")
  654. continue
  655. if not files:
  656. logger.info(f"[TIMELAPSE] Attempt {attempt}: No timelapse files found on printer, will retry")
  657. continue
  658. mp4_files = [f for f in files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  659. # Log ALL mp4 files found for debugging
  660. logger.info(f"[TIMELAPSE] Attempt {attempt}: Found {len(mp4_files)} MP4 files in {found_path}")
  661. for f in mp4_files[:5]: # Log first 5
  662. logger.info(f"[TIMELAPSE] - {f.get('name')}, mtime={f.get('mtime')}")
  663. if not mp4_files:
  664. logger.info(f"[TIMELAPSE] Attempt {attempt}: No MP4 files found, will retry")
  665. continue
  666. # Sort by mtime descending to get most recent file
  667. mp4_files_with_mtime = [f for f in mp4_files if f.get("mtime")]
  668. if not mp4_files_with_mtime:
  669. logger.info(f"[TIMELAPSE] Attempt {attempt}: No MP4 files with mtime found, will retry")
  670. continue
  671. mp4_files_with_mtime.sort(key=lambda x: x.get("mtime"), reverse=True)
  672. most_recent = mp4_files_with_mtime[0]
  673. file_name = most_recent.get("name")
  674. logger.info(f"[TIMELAPSE] Attempt {attempt}: Most recent file: {file_name}")
  675. # Since we KNOW timelapse was active (from MQTT), just grab the most recent file
  676. remote_path = most_recent.get("path") or f"/timelapse/{file_name}"
  677. logger.info(f"[TIMELAPSE] Downloading {file_name} for archive {archive_id}")
  678. timelapse_data = await download_file_bytes_async(printer.ip_address, printer.access_code, remote_path)
  679. if timelapse_data:
  680. success = await service.attach_timelapse(archive_id, timelapse_data, file_name)
  681. if success:
  682. logger.info(f"[TIMELAPSE] Successfully attached timelapse to archive {archive_id}")
  683. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  684. return # Success!
  685. else:
  686. logger.warning(f"[TIMELAPSE] Failed to attach timelapse to archive {archive_id}")
  687. else:
  688. logger.warning(f"[TIMELAPSE] Attempt {attempt}: Failed to download, will retry")
  689. except Exception as e:
  690. logger.warning(f"[TIMELAPSE] Attempt {attempt} failed with error: {e}")
  691. logger.warning(f"[TIMELAPSE] All {len(retry_delays)} attempts exhausted for archive {archive_id}, giving up")
  692. async def on_print_complete(printer_id: int, data: dict):
  693. """Handle print completion - update the archive status."""
  694. import logging
  695. import time
  696. logger = logging.getLogger(__name__)
  697. start_time = time.time()
  698. def log_timing(section: str):
  699. elapsed = time.time() - start_time
  700. logger.info(f"[TIMING] {section}: {elapsed:.3f}s elapsed")
  701. logger.info(f"[CALLBACK] on_print_complete started for printer {printer_id}")
  702. try:
  703. ws_data = {
  704. "status": data.get("status"),
  705. "filename": data.get("filename"),
  706. "subtask_name": data.get("subtask_name"),
  707. "timelapse_was_active": data.get("timelapse_was_active"),
  708. }
  709. await ws_manager.send_print_complete(printer_id, ws_data)
  710. log_timing("WebSocket send_print_complete")
  711. except Exception as e:
  712. logger.warning(f"[CALLBACK] WebSocket send_print_complete failed: {e}")
  713. filename = data.get("filename", "")
  714. subtask_name = data.get("subtask_name", "")
  715. if not filename and not subtask_name:
  716. logger.warning("Print complete without filename or subtask_name")
  717. return
  718. logger.info(f"Print complete - filename: {filename}, subtask: {subtask_name}, status: {data.get('status')}")
  719. # Build list of possible keys to try (matching how they were registered in on_print_start)
  720. possible_keys = []
  721. # Try subtask_name variations first (most reliable for matching)
  722. if subtask_name:
  723. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  724. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  725. possible_keys.append((printer_id, subtask_name))
  726. # Try filename variations
  727. if filename:
  728. # Extract just the filename if it's a path
  729. fname = filename.split("/")[-1] if "/" in filename else filename
  730. if fname.endswith(".3mf"):
  731. possible_keys.append((printer_id, fname))
  732. elif fname.endswith(".gcode"):
  733. base_name = fname.rsplit(".", 1)[0]
  734. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  735. possible_keys.append((printer_id, f"{base_name}.3mf"))
  736. possible_keys.append((printer_id, fname))
  737. else:
  738. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  739. possible_keys.append((printer_id, f"{fname}.3mf"))
  740. possible_keys.append((printer_id, fname))
  741. # Also try full path versions
  742. if filename.endswith(".3mf"):
  743. possible_keys.append((printer_id, filename))
  744. elif filename.endswith(".gcode"):
  745. base_name = filename.rsplit(".", 1)[0]
  746. possible_keys.append((printer_id, f"{base_name}.3mf"))
  747. possible_keys.append((printer_id, filename))
  748. else:
  749. possible_keys.append((printer_id, f"{filename}.3mf"))
  750. possible_keys.append((printer_id, filename))
  751. # Find the archive for this print
  752. logger.info(f"Looking for archive in _active_prints, keys to try: {possible_keys[:5]}...")
  753. logger.info(f"Current _active_prints: {list(_active_prints.keys())}")
  754. archive_id = None
  755. for key in possible_keys:
  756. archive_id = _active_prints.pop(key, None)
  757. if archive_id:
  758. logger.info(f"Found archive {archive_id} with key {key}")
  759. # Also clean up any other keys pointing to this archive
  760. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  761. for k in keys_to_remove:
  762. _active_prints.pop(k, None)
  763. break
  764. if not archive_id:
  765. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  766. async with async_session() as db:
  767. from backend.app.models.archive import PrintArchive
  768. # Try matching by subtask_name (stored as print_name) first
  769. if subtask_name:
  770. result = await db.execute(
  771. select(PrintArchive)
  772. .where(PrintArchive.printer_id == printer_id)
  773. .where(PrintArchive.status == "printing")
  774. .where(
  775. or_(
  776. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  777. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  778. )
  779. )
  780. .order_by(PrintArchive.created_at.desc())
  781. .limit(1)
  782. )
  783. archive = result.scalar_one_or_none()
  784. if archive:
  785. archive_id = archive.id
  786. logger.info(f"Found archive {archive_id} by subtask_name match: {subtask_name}")
  787. # Also try by filename
  788. if not archive_id and filename:
  789. result = await db.execute(
  790. select(PrintArchive)
  791. .where(PrintArchive.printer_id == printer_id)
  792. .where(PrintArchive.filename == filename)
  793. .where(PrintArchive.status == "printing")
  794. .order_by(PrintArchive.created_at.desc())
  795. .limit(1)
  796. )
  797. archive = result.scalar_one_or_none()
  798. if archive:
  799. archive_id = archive.id
  800. if not archive_id:
  801. logger.warning(f"Could not find archive for print complete: filename={filename}, subtask={subtask_name}")
  802. return
  803. log_timing("Archive lookup")
  804. # Update archive status
  805. logger.info(f"[ARCHIVE] Updating archive {archive_id} status...")
  806. try:
  807. async with async_session() as db:
  808. service = ArchiveService(db)
  809. status = data.get("status", "completed")
  810. # Auto-detect failure reason
  811. failure_reason = None
  812. if status == "aborted":
  813. failure_reason = "User cancelled"
  814. logger.info("[ARCHIVE] Print was aborted by user, setting failure_reason='User cancelled'")
  815. elif status == "failed":
  816. # Try to determine failure reason from HMS errors
  817. hms_errors = data.get("hms_errors", [])
  818. if hms_errors:
  819. logger.info(f"[ARCHIVE] HMS errors at failure: {hms_errors}")
  820. # Map known HMS error modules to failure reasons
  821. # Module 0x07 = Filament, 0x0C = MC (Motion Controller), etc.
  822. for err in hms_errors:
  823. module = err.get("module", 0)
  824. if module == 0x07: # Filament module
  825. failure_reason = "Filament runout"
  826. break
  827. elif module == 0x0C: # Motion controller
  828. failure_reason = "Layer shift"
  829. break
  830. elif module == 0x05: # Nozzle/extruder
  831. failure_reason = "Clogged nozzle"
  832. break
  833. if failure_reason:
  834. logger.info(f"[ARCHIVE] Detected failure_reason from HMS: {failure_reason}")
  835. else:
  836. logger.info("[ARCHIVE] No HMS errors available to determine failure reason")
  837. await service.update_archive_status(
  838. archive_id,
  839. status=status,
  840. completed_at=datetime.now() if status in ("completed", "failed", "aborted") else None,
  841. failure_reason=failure_reason,
  842. )
  843. logger.info(f"[ARCHIVE] Archive {archive_id} status updated to {status}, failure_reason={failure_reason}")
  844. await ws_manager.send_archive_updated(
  845. {
  846. "id": archive_id,
  847. "status": status,
  848. }
  849. )
  850. logger.info(f"[ARCHIVE] WebSocket notification sent for archive {archive_id}")
  851. except Exception as e:
  852. logger.error(f"[ARCHIVE] Failed to update archive {archive_id} status: {e}", exc_info=True)
  853. # Continue with other operations even if archive update fails
  854. log_timing("Archive status update")
  855. # Report filament usage to Spoolman if print completed successfully
  856. if data.get("status") == "completed":
  857. try:
  858. await _report_spoolman_usage(printer_id, archive_id, logger)
  859. log_timing("Spoolman usage report")
  860. except Exception as e:
  861. logger.warning(f"Spoolman usage reporting failed: {e}")
  862. # Run slow operations as background tasks to avoid blocking the event loop
  863. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  864. starting_kwh = _print_energy_start.pop(archive_id, None)
  865. async def _background_energy_calculation():
  866. """Calculate and save energy usage in background."""
  867. try:
  868. logger.info(f"[ENERGY-BG] Starting energy calculation for archive {archive_id}")
  869. async with async_session() as db:
  870. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  871. plug = plug_result.scalar_one_or_none()
  872. if plug:
  873. energy = await tasmota_service.get_energy(plug)
  874. logger.info(f"[ENERGY-BG] Energy response: {energy}")
  875. energy_used = None
  876. if starting_kwh is not None and energy and energy.get("total") is not None:
  877. ending_kwh = energy["total"]
  878. energy_used = round(ending_kwh - starting_kwh, 4)
  879. logger.info(f"[ENERGY-BG] Per-print energy: {energy_used} kWh")
  880. if energy_used is not None and energy_used >= 0:
  881. from backend.app.api.routes.settings import get_setting
  882. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  883. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  884. energy_cost = round(energy_used * cost_per_kwh, 2)
  885. from backend.app.models.archive import PrintArchive
  886. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  887. archive = result.scalar_one_or_none()
  888. if archive:
  889. archive.energy_kwh = energy_used
  890. archive.energy_cost = energy_cost
  891. await db.commit()
  892. logger.info(f"[ENERGY-BG] Saved: {energy_used} kWh, cost={energy_cost}")
  893. else:
  894. logger.info(f"[ENERGY-BG] No smart plug for printer {printer_id}")
  895. except Exception as e:
  896. logger.warning(f"[ENERGY-BG] Failed: {e}")
  897. async def _background_finish_photo():
  898. """Capture finish photo in background."""
  899. try:
  900. logger.info(f"[PHOTO-BG] Starting finish photo capture for archive {archive_id}")
  901. from backend.app.api.routes.camera import _active_streams, get_buffered_frame
  902. async with async_session() as db:
  903. from backend.app.api.routes.settings import get_setting
  904. capture_enabled = await get_setting(db, "capture_finish_photo")
  905. if capture_enabled is None or capture_enabled.lower() == "true":
  906. from backend.app.models.printer import Printer
  907. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  908. printer = result.scalar_one_or_none()
  909. if printer and archive_id:
  910. from backend.app.models.archive import PrintArchive
  911. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  912. archive = result.scalar_one_or_none()
  913. if archive:
  914. import uuid
  915. from datetime import datetime
  916. from pathlib import Path
  917. archive_dir = app_settings.base_dir / Path(archive.file_path).parent
  918. photo_filename = None
  919. # Check if camera stream is active - use buffered frame to avoid freeze
  920. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  921. buffered_frame = get_buffered_frame(printer_id)
  922. if active_for_printer and buffered_frame:
  923. # Use frame from active stream
  924. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  925. photos_dir = archive_dir / "photos"
  926. photos_dir.mkdir(parents=True, exist_ok=True)
  927. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  928. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  929. photo_path = photos_dir / photo_filename
  930. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  931. logger.info(f"[PHOTO-BG] Saved buffered frame: {photo_filename}")
  932. else:
  933. # No active stream - capture new frame
  934. from backend.app.services.camera import capture_finish_photo
  935. photo_filename = await capture_finish_photo(
  936. printer_id=printer_id,
  937. ip_address=printer.ip_address,
  938. access_code=printer.access_code,
  939. model=printer.model,
  940. archive_dir=archive_dir,
  941. )
  942. if photo_filename:
  943. photos = archive.photos or []
  944. photos.append(photo_filename)
  945. archive.photos = photos
  946. await db.commit()
  947. logger.info(f"[PHOTO-BG] Saved: {photo_filename}")
  948. except Exception as e:
  949. logger.warning(f"[PHOTO-BG] Failed: {e}")
  950. asyncio.create_task(_background_energy_calculation())
  951. asyncio.create_task(_background_finish_photo()) # Skips if camera stream active
  952. log_timing("Background tasks scheduled (energy, photo)")
  953. # Also run smart plug, notifications, and maintenance as background tasks
  954. print_status = data.get("status", "completed")
  955. async def _background_smart_plug():
  956. """Handle smart plug automation in background."""
  957. try:
  958. logger.info(f"[AUTO-OFF-BG] Starting smart plug automation for printer {printer_id}")
  959. async with async_session() as db:
  960. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  961. logger.info("[AUTO-OFF-BG] Completed")
  962. except Exception as e:
  963. logger.warning(f"[AUTO-OFF-BG] Failed: {e}")
  964. async def _background_notifications():
  965. """Send print complete notifications in background."""
  966. try:
  967. logger.info(f"[NOTIFY-BG] Starting notifications for printer {printer_id}")
  968. async with async_session() as db:
  969. from backend.app.models.archive import PrintArchive
  970. from backend.app.models.printer import Printer
  971. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  972. printer = result.scalar_one_or_none()
  973. printer_name = printer.name if printer else f"Printer {printer_id}"
  974. archive_data = None
  975. if archive_id:
  976. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  977. archive = archive_result.scalar_one_or_none()
  978. if archive:
  979. archive_data = {
  980. "print_time_seconds": archive.print_time_seconds,
  981. "actual_filament_grams": archive.filament_used_grams,
  982. "failure_reason": archive.failure_reason,
  983. }
  984. await notification_service.on_print_complete(
  985. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  986. )
  987. logger.info("[NOTIFY-BG] Completed")
  988. except Exception as e:
  989. logger.warning(f"[NOTIFY-BG] Failed: {e}")
  990. async def _background_maintenance_check():
  991. """Check for maintenance due in background."""
  992. if print_status != "completed":
  993. return
  994. try:
  995. logger.info(f"[MAINT-BG] Starting maintenance check for printer {printer_id}")
  996. async with async_session() as db:
  997. from backend.app.models.printer import Printer
  998. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  999. printer = result.scalar_one_or_none()
  1000. printer_name = printer.name if printer else f"Printer {printer_id}"
  1001. await ensure_default_types(db)
  1002. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  1003. items_needing_attention = [
  1004. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  1005. for item in overview.maintenance_items
  1006. if item.enabled and (item.is_due or item.is_warning)
  1007. ]
  1008. if items_needing_attention:
  1009. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  1010. logger.info(f"[MAINT-BG] Sent notification: {len(items_needing_attention)} items need attention")
  1011. else:
  1012. logger.info("[MAINT-BG] Completed (no items need attention)")
  1013. except Exception as e:
  1014. logger.warning(f"[MAINT-BG] Failed: {e}")
  1015. asyncio.create_task(_background_smart_plug())
  1016. asyncio.create_task(_background_notifications())
  1017. asyncio.create_task(_background_maintenance_check())
  1018. log_timing("All background tasks scheduled")
  1019. # Auto-scan for timelapse if recording was active during the print
  1020. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  1021. logger.info(f"[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive {archive_id}")
  1022. # Schedule timelapse scan as background task with retries
  1023. # The printer needs time to encode the video after print completion
  1024. asyncio.create_task(_scan_for_timelapse_with_retries(archive_id))
  1025. log_timing("Timelapse scan scheduled")
  1026. # Update queue item if this was a scheduled print
  1027. try:
  1028. async with async_session() as db:
  1029. from backend.app.models.print_queue import PrintQueueItem
  1030. # Note: SmartPlug is already imported at module level (line 56)
  1031. # Do NOT import it here as it would shadow the module-level import
  1032. # and cause "cannot access local variable" errors earlier in this function
  1033. result = await db.execute(
  1034. select(PrintQueueItem)
  1035. .where(PrintQueueItem.printer_id == printer_id)
  1036. .where(PrintQueueItem.status == "printing")
  1037. )
  1038. queue_item = result.scalar_one_or_none()
  1039. if queue_item:
  1040. status = data.get("status", "completed")
  1041. queue_item.status = status
  1042. queue_item.completed_at = datetime.now()
  1043. await db.commit()
  1044. logger.info(f"Updated queue item {queue_item.id} status to {status}")
  1045. # Handle auto_off_after - power off printer if requested (after cooldown)
  1046. if queue_item.auto_off_after:
  1047. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1048. plug = result.scalar_one_or_none()
  1049. if plug and plug.enabled:
  1050. logger.info(f"Auto-off requested for printer {printer_id}, waiting for cooldown...")
  1051. async def cooldown_and_poweroff(pid: int, plug_id: int):
  1052. # Wait for nozzle to cool down
  1053. await printer_manager.wait_for_cooldown(pid, target_temp=50.0, timeout=600)
  1054. # Re-fetch plug in new session
  1055. async with async_session() as new_db:
  1056. result = await new_db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  1057. p = result.scalar_one_or_none()
  1058. if p and p.enabled:
  1059. success = await tasmota_service.turn_off(p)
  1060. if success:
  1061. logger.info(f"Powered off printer {pid} via smart plug '{p.name}'")
  1062. else:
  1063. logger.warning(f"Failed to power off printer {pid} via smart plug")
  1064. asyncio.create_task(cooldown_and_poweroff(printer_id, plug.id))
  1065. except Exception as e:
  1066. import logging
  1067. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  1068. log_timing("Queue item update")
  1069. logger.info(f"[CALLBACK] on_print_complete finished for printer {printer_id}, archive {archive_id}")
  1070. # AMS sensor history recording
  1071. _ams_history_task: asyncio.Task | None = None
  1072. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  1073. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  1074. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  1075. _ams_alarm_cooldown: dict[str, datetime] = {} # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  1076. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  1077. async def record_ams_history():
  1078. """Background task to record AMS humidity and temperature data."""
  1079. import logging
  1080. logger = logging.getLogger(__name__)
  1081. # Wait a short time for MQTT connections to establish on startup
  1082. await asyncio.sleep(10)
  1083. while True:
  1084. try:
  1085. from backend.app.models.ams_history import AMSSensorHistory
  1086. from backend.app.models.printer import Printer
  1087. from backend.app.models.settings import Settings
  1088. async with async_session() as db:
  1089. # Get all active printers
  1090. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1091. printers = result.scalars().all()
  1092. # Get alarm thresholds from settings
  1093. humidity_threshold = 60.0 # Default: fair threshold
  1094. temp_threshold = 35.0 # Default: fair threshold
  1095. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  1096. setting = result.scalar_one_or_none()
  1097. if setting:
  1098. try:
  1099. humidity_threshold = float(setting.value)
  1100. except (ValueError, TypeError):
  1101. pass
  1102. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  1103. setting = result.scalar_one_or_none()
  1104. if setting:
  1105. try:
  1106. temp_threshold = float(setting.value)
  1107. except (ValueError, TypeError):
  1108. pass
  1109. recorded_count = 0
  1110. for printer in printers:
  1111. # Get current state from printer manager
  1112. state = printer_manager.get_status(printer.id)
  1113. if not state or not state.connected or not state.raw_data:
  1114. continue # Skip disconnected printers - don't use stale data
  1115. raw_data = state.raw_data
  1116. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  1117. continue
  1118. # Record data for each AMS unit
  1119. for ams_data in raw_data["ams"]:
  1120. ams_id = int(ams_data.get("id", 0))
  1121. # Get humidity (prefer humidity_raw)
  1122. humidity_raw = ams_data.get("humidity_raw")
  1123. humidity_idx = ams_data.get("humidity")
  1124. humidity = None
  1125. if humidity_raw is not None:
  1126. try:
  1127. humidity = float(humidity_raw)
  1128. except (ValueError, TypeError):
  1129. pass
  1130. if humidity is None and humidity_idx is not None:
  1131. try:
  1132. humidity = float(humidity_idx)
  1133. except (ValueError, TypeError):
  1134. pass
  1135. # Get temperature
  1136. temperature = None
  1137. temp_str = ams_data.get("temp")
  1138. if temp_str is not None:
  1139. try:
  1140. temperature = float(temp_str)
  1141. except (ValueError, TypeError):
  1142. pass
  1143. # Skip if no data
  1144. if humidity is None and temperature is None:
  1145. continue
  1146. # Record the data point
  1147. history = AMSSensorHistory(
  1148. printer_id=printer.id,
  1149. ams_id=ams_id,
  1150. humidity=humidity,
  1151. humidity_raw=float(humidity_raw) if humidity_raw else None,
  1152. temperature=temperature,
  1153. )
  1154. db.add(history)
  1155. recorded_count += 1
  1156. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  1157. is_ams_ht = ams_id >= 128
  1158. if is_ams_ht:
  1159. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  1160. else:
  1161. ams_label = f"AMS-{chr(65 + ams_id)}"
  1162. # Check humidity alarm (only if above threshold)
  1163. if humidity is not None and humidity > humidity_threshold:
  1164. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  1165. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  1166. now = datetime.now()
  1167. if (
  1168. last_alarm is None
  1169. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  1170. ):
  1171. _ams_alarm_cooldown[cooldown_key] = now
  1172. logger.info(
  1173. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {humidity_threshold}%"
  1174. )
  1175. try:
  1176. # Call different notification method based on AMS type
  1177. if is_ams_ht:
  1178. await notification_service.on_ams_ht_humidity_high(
  1179. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  1180. )
  1181. else:
  1182. await notification_service.on_ams_humidity_high(
  1183. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  1184. )
  1185. except Exception as e:
  1186. logger.warning(f"Failed to send humidity alarm: {e}")
  1187. # Check temperature alarm (only if above threshold)
  1188. if temperature is not None and temperature > temp_threshold:
  1189. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  1190. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  1191. now = datetime.now()
  1192. if (
  1193. last_alarm is None
  1194. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  1195. ):
  1196. _ams_alarm_cooldown[cooldown_key] = now
  1197. logger.info(
  1198. f"Sending temperature alarm for {printer.name} {ams_label}: {temperature}°C > {temp_threshold}°C"
  1199. )
  1200. try:
  1201. # Call different notification method based on AMS type
  1202. if is_ams_ht:
  1203. await notification_service.on_ams_ht_temperature_high(
  1204. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  1205. )
  1206. else:
  1207. await notification_service.on_ams_temperature_high(
  1208. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  1209. )
  1210. except Exception as e:
  1211. logger.warning(f"Failed to send temperature alarm: {e}")
  1212. await db.commit()
  1213. if recorded_count > 0:
  1214. logger.info(f"Recorded {recorded_count} AMS sensor history entries")
  1215. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  1216. global _ams_cleanup_counter
  1217. _ams_cleanup_counter += 1
  1218. if _ams_cleanup_counter >= 288:
  1219. _ams_cleanup_counter = 0
  1220. # Get retention days from settings
  1221. from backend.app.models.settings import Settings
  1222. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  1223. setting = result.scalar_one_or_none()
  1224. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  1225. cutoff = datetime.now() - timedelta(days=retention_days)
  1226. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  1227. await db.commit()
  1228. if result.rowcount > 0:
  1229. logger.info(
  1230. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  1231. )
  1232. # Wait until next recording interval
  1233. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  1234. except asyncio.CancelledError:
  1235. break
  1236. except Exception as e:
  1237. logger.warning(f"AMS history recording failed: {e}")
  1238. await asyncio.sleep(60) # Wait a bit before retrying
  1239. def start_ams_history_recording():
  1240. """Start the AMS history recording background task."""
  1241. global _ams_history_task
  1242. if _ams_history_task is None:
  1243. _ams_history_task = asyncio.create_task(record_ams_history())
  1244. logging.getLogger(__name__).info("AMS history recording started")
  1245. def stop_ams_history_recording():
  1246. """Stop the AMS history recording background task."""
  1247. global _ams_history_task
  1248. if _ams_history_task:
  1249. _ams_history_task.cancel()
  1250. _ams_history_task = None
  1251. logging.getLogger(__name__).info("AMS history recording stopped")
  1252. # Printer runtime tracking
  1253. _runtime_tracking_task: asyncio.Task | None = None
  1254. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  1255. async def track_printer_runtime():
  1256. """Background task to track printer active runtime (RUNNING/PAUSE states)."""
  1257. import logging
  1258. logger = logging.getLogger(__name__)
  1259. # Wait for MQTT connections to establish on startup
  1260. await asyncio.sleep(15)
  1261. while True:
  1262. try:
  1263. from backend.app.models.printer import Printer
  1264. async with async_session() as db:
  1265. # Get all active printers
  1266. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1267. printers = result.scalars().all()
  1268. now = datetime.now()
  1269. updated_count = 0
  1270. needs_commit = False
  1271. for printer in printers:
  1272. # Get current state from printer manager
  1273. state = printer_manager.get_status(printer.id)
  1274. if not state or not state.connected:
  1275. continue
  1276. # Check if printer is in an active state (RUNNING or PAUSE)
  1277. if state.state in ("RUNNING", "PAUSE"):
  1278. # Calculate time since last update
  1279. if printer.last_runtime_update:
  1280. elapsed = (now - printer.last_runtime_update).total_seconds()
  1281. # Sanity check: don't add more than 2x the interval (handles server restarts)
  1282. if elapsed > 0 and elapsed < RUNTIME_TRACKING_INTERVAL * 2:
  1283. printer.runtime_seconds += int(elapsed)
  1284. updated_count += 1
  1285. needs_commit = True
  1286. else:
  1287. # First time seeing printer active - need to commit to save timestamp
  1288. needs_commit = True
  1289. printer.last_runtime_update = now
  1290. else:
  1291. # Printer is idle/offline - clear last_runtime_update
  1292. if printer.last_runtime_update is not None:
  1293. printer.last_runtime_update = None
  1294. needs_commit = True
  1295. if needs_commit:
  1296. await db.commit()
  1297. if updated_count > 0:
  1298. logger.debug(f"Updated runtime for {updated_count} printer(s)")
  1299. except asyncio.CancelledError:
  1300. logger.info("Runtime tracking cancelled")
  1301. break
  1302. except Exception as e:
  1303. logger.warning(f"Runtime tracking failed: {e}")
  1304. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  1305. def start_runtime_tracking():
  1306. """Start the printer runtime tracking background task."""
  1307. global _runtime_tracking_task
  1308. if _runtime_tracking_task is None:
  1309. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  1310. logging.getLogger(__name__).info("Printer runtime tracking started")
  1311. def stop_runtime_tracking():
  1312. """Stop the printer runtime tracking background task."""
  1313. global _runtime_tracking_task
  1314. if _runtime_tracking_task:
  1315. _runtime_tracking_task.cancel()
  1316. _runtime_tracking_task = None
  1317. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  1318. @asynccontextmanager
  1319. async def lifespan(app: FastAPI):
  1320. # Startup
  1321. await init_db()
  1322. # Set up printer manager callbacks
  1323. loop = asyncio.get_event_loop()
  1324. printer_manager.set_event_loop(loop)
  1325. printer_manager.set_status_change_callback(on_printer_status_change)
  1326. printer_manager.set_print_start_callback(on_print_start)
  1327. printer_manager.set_print_complete_callback(on_print_complete)
  1328. printer_manager.set_ams_change_callback(on_ams_change)
  1329. # Connect to all active printers
  1330. async with async_session() as db:
  1331. await init_printer_connections(db)
  1332. # Auto-connect to Spoolman if enabled
  1333. async with async_session() as db:
  1334. from backend.app.api.routes.settings import get_setting
  1335. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  1336. spoolman_url = await get_setting(db, "spoolman_url")
  1337. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  1338. try:
  1339. client = await init_spoolman_client(spoolman_url)
  1340. if await client.health_check():
  1341. logging.info(f"Auto-connected to Spoolman at {spoolman_url}")
  1342. else:
  1343. logging.warning(f"Spoolman at {spoolman_url} is not reachable")
  1344. except Exception as e:
  1345. logging.warning(f"Failed to auto-connect to Spoolman: {e}")
  1346. # Start the print scheduler
  1347. asyncio.create_task(print_scheduler.run())
  1348. # Start the smart plug scheduler for time-based on/off
  1349. smart_plug_manager.start_scheduler()
  1350. # Resume any pending auto-offs that were interrupted by restart
  1351. await smart_plug_manager.resume_pending_auto_offs()
  1352. # Start the notification digest scheduler
  1353. notification_service.start_digest_scheduler()
  1354. # Start AMS history recording
  1355. start_ams_history_recording()
  1356. # Start printer runtime tracking
  1357. start_runtime_tracking()
  1358. # Start anonymous telemetry (opt-out via settings)
  1359. asyncio.create_task(start_telemetry_loop(async_session))
  1360. # Initialize virtual printer manager
  1361. from backend.app.services.virtual_printer import virtual_printer_manager
  1362. virtual_printer_manager.set_session_factory(async_session)
  1363. # Auto-start virtual printer if enabled
  1364. async with async_session() as db:
  1365. from backend.app.api.routes.settings import get_setting
  1366. vp_enabled = await get_setting(db, "virtual_printer_enabled")
  1367. if vp_enabled and vp_enabled.lower() == "true":
  1368. vp_access_code = await get_setting(db, "virtual_printer_access_code") or ""
  1369. vp_mode = await get_setting(db, "virtual_printer_mode") or "immediate"
  1370. if vp_access_code:
  1371. try:
  1372. await virtual_printer_manager.configure(
  1373. enabled=True,
  1374. access_code=vp_access_code,
  1375. mode=vp_mode,
  1376. )
  1377. logging.info("Virtual printer started")
  1378. except Exception as e:
  1379. logging.warning(f"Failed to start virtual printer: {e}")
  1380. yield
  1381. # Shutdown
  1382. print_scheduler.stop()
  1383. smart_plug_manager.stop_scheduler()
  1384. notification_service.stop_digest_scheduler()
  1385. stop_ams_history_recording()
  1386. stop_runtime_tracking()
  1387. printer_manager.disconnect_all()
  1388. await close_spoolman_client()
  1389. # Stop virtual printer if running
  1390. if virtual_printer_manager.is_enabled:
  1391. await virtual_printer_manager.configure(enabled=False)
  1392. app = FastAPI(
  1393. title=app_settings.app_name,
  1394. description="Archive and manage Bambu Lab 3MF files",
  1395. version=APP_VERSION,
  1396. lifespan=lifespan,
  1397. )
  1398. # API routes
  1399. app.include_router(printers.router, prefix=app_settings.api_prefix)
  1400. app.include_router(archives.router, prefix=app_settings.api_prefix)
  1401. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  1402. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  1403. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  1404. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  1405. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  1406. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  1407. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  1408. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  1409. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  1410. app.include_router(updates.router, prefix=app_settings.api_prefix)
  1411. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  1412. app.include_router(camera.router, prefix=app_settings.api_prefix)
  1413. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  1414. app.include_router(projects.router, prefix=app_settings.api_prefix)
  1415. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  1416. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  1417. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  1418. app.include_router(system.router, prefix=app_settings.api_prefix)
  1419. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  1420. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  1421. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  1422. # Serve static files (React build)
  1423. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  1424. app.mount(
  1425. "/assets",
  1426. StaticFiles(directory=app_settings.static_dir / "assets"),
  1427. name="assets",
  1428. )
  1429. if (app_settings.static_dir / "img").exists():
  1430. app.mount(
  1431. "/img",
  1432. StaticFiles(directory=app_settings.static_dir / "img"),
  1433. name="img",
  1434. )
  1435. if (app_settings.static_dir / "icons").exists():
  1436. app.mount(
  1437. "/icons",
  1438. StaticFiles(directory=app_settings.static_dir / "icons"),
  1439. name="icons",
  1440. )
  1441. @app.get("/")
  1442. async def serve_frontend():
  1443. """Serve the React frontend."""
  1444. index_file = app_settings.static_dir / "index.html"
  1445. if index_file.exists():
  1446. return FileResponse(index_file)
  1447. return {
  1448. "message": "Bambuddy API",
  1449. "docs": "/docs",
  1450. "frontend": "Build and place React app in /static directory",
  1451. }
  1452. @app.get("/health")
  1453. async def health_check():
  1454. """Health check endpoint."""
  1455. return {"status": "healthy"}
  1456. @app.get("/manifest.json")
  1457. async def serve_manifest():
  1458. """Serve PWA manifest."""
  1459. manifest_file = app_settings.static_dir / "manifest.json"
  1460. if manifest_file.exists():
  1461. return FileResponse(manifest_file, media_type="application/manifest+json")
  1462. return {"error": "Manifest not found"}
  1463. @app.get("/sw.js")
  1464. async def serve_service_worker():
  1465. """Serve service worker."""
  1466. sw_file = app_settings.static_dir / "sw.js"
  1467. if sw_file.exists():
  1468. return FileResponse(sw_file, media_type="application/javascript")
  1469. return {"error": "Service worker not found"}
  1470. # Catch-all route for React Router (must be last)
  1471. @app.get("/{full_path:path}")
  1472. async def serve_spa(full_path: str):
  1473. """Serve React app for client-side routing."""
  1474. # Don't intercept API routes
  1475. if full_path.startswith("api/"):
  1476. return {"error": "Not found"}
  1477. index_file = app_settings.static_dir / "index.html"
  1478. if index_file.exists():
  1479. return FileResponse(index_file)
  1480. return {"error": "Frontend not built"}