main.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. import asyncio
  2. import logging
  3. from datetime import datetime
  4. from contextlib import asynccontextmanager
  5. from pathlib import Path
  6. from fastapi import FastAPI
  7. # Configure logging for all modules
  8. logging.basicConfig(
  9. level=logging.INFO,
  10. format='%(asctime)s %(levelname)s [%(name)s] %(message)s'
  11. )
  12. from fastapi.staticfiles import StaticFiles
  13. from fastapi.responses import FileResponse
  14. from backend.app.core.config import settings as app_settings
  15. from backend.app.core.database import init_db, async_session
  16. from backend.app.core.websocket import ws_manager
  17. from backend.app.api.routes import printers, archives, websocket, filaments, cloud, smart_plugs
  18. from backend.app.api.routes import settings as settings_routes
  19. from backend.app.services.printer_manager import (
  20. printer_manager,
  21. printer_state_to_dict,
  22. init_printer_connections,
  23. )
  24. from backend.app.services.bambu_mqtt import PrinterState
  25. from backend.app.services.archive import ArchiveService
  26. from backend.app.services.bambu_ftp import download_file_async
  27. from backend.app.services.smart_plug_manager import smart_plug_manager
  28. from backend.app.services.tasmota import tasmota_service
  29. from backend.app.models.smart_plug import SmartPlug
  30. # Track active prints: {(printer_id, filename): archive_id}
  31. _active_prints: dict[tuple[int, str], int] = {}
  32. # Track starting energy for prints: {archive_id: starting_kwh}
  33. _print_energy_start: dict[int, float] = {}
  34. async def on_printer_status_change(printer_id: int, state: PrinterState):
  35. """Handle printer status changes - broadcast via WebSocket."""
  36. await ws_manager.send_printer_status(
  37. printer_id,
  38. printer_state_to_dict(state, printer_id),
  39. )
  40. async def on_print_start(printer_id: int, data: dict):
  41. """Handle print start - archive the 3MF file immediately."""
  42. import logging
  43. logger = logging.getLogger(__name__)
  44. await ws_manager.send_print_start(printer_id, data)
  45. async with async_session() as db:
  46. from backend.app.models.printer import Printer
  47. from backend.app.services.bambu_ftp import list_files_async
  48. from sqlalchemy import select
  49. result = await db.execute(
  50. select(Printer).where(Printer.id == printer_id)
  51. )
  52. printer = result.scalar_one_or_none()
  53. if not printer or not printer.auto_archive:
  54. return
  55. # Get the filename and subtask_name
  56. filename = data.get("filename", "")
  57. subtask_name = data.get("subtask_name", "")
  58. logger.info(f"Print start detected - filename: {filename}, subtask: {subtask_name}")
  59. if not filename and not subtask_name:
  60. return
  61. # Build list of possible 3MF filenames to try
  62. possible_names = []
  63. # Bambu printers typically store files as "Name.gcode.3mf"
  64. # The subtask_name is usually the best source for the filename
  65. if subtask_name:
  66. # Try common Bambu naming patterns
  67. possible_names.append(f"{subtask_name}.gcode.3mf")
  68. possible_names.append(f"{subtask_name}.3mf")
  69. # Try original filename with .3mf extension
  70. if filename:
  71. # Extract just the filename part, not the full path
  72. fname = filename.split("/")[-1] if "/" in filename else filename
  73. if fname.endswith(".3mf"):
  74. possible_names.append(fname)
  75. elif fname.endswith(".gcode"):
  76. base = fname.rsplit(".", 1)[0]
  77. possible_names.append(f"{base}.gcode.3mf")
  78. possible_names.append(f"{base}.3mf")
  79. else:
  80. possible_names.append(f"{fname}.gcode.3mf")
  81. possible_names.append(f"{fname}.3mf")
  82. # Remove duplicates while preserving order
  83. seen = set()
  84. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  85. logger.info(f"Trying filenames: {possible_names}")
  86. # Try to find and download the 3MF file
  87. temp_path = None
  88. downloaded_filename = None
  89. for try_filename in possible_names:
  90. if not try_filename.endswith(".3mf"):
  91. continue
  92. remote_paths = [
  93. f"/cache/{try_filename}",
  94. f"/model/{try_filename}",
  95. f"/{try_filename}",
  96. ]
  97. temp_path = app_settings.archive_dir / "temp" / try_filename
  98. temp_path.parent.mkdir(parents=True, exist_ok=True)
  99. for remote_path in remote_paths:
  100. logger.debug(f"Trying FTP download: {remote_path}")
  101. try:
  102. if await download_file_async(
  103. printer.ip_address,
  104. printer.access_code,
  105. remote_path,
  106. temp_path,
  107. ):
  108. downloaded_filename = try_filename
  109. logger.info(f"Downloaded: {remote_path}")
  110. break
  111. except Exception as e:
  112. logger.debug(f"FTP download failed for {remote_path}: {e}")
  113. if downloaded_filename:
  114. break
  115. # If still not found, try listing /cache to find matching file
  116. if not downloaded_filename and (filename or subtask_name):
  117. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  118. try:
  119. cache_files = await list_files_async(printer.ip_address, printer.access_code, "/cache")
  120. for f in cache_files:
  121. if f.get("is_directory"):
  122. continue
  123. fname = f.get("name", "")
  124. if fname.endswith(".3mf") and search_term in fname.lower():
  125. temp_path = app_settings.archive_dir / "temp" / fname
  126. temp_path.parent.mkdir(parents=True, exist_ok=True)
  127. if await download_file_async(
  128. printer.ip_address,
  129. printer.access_code,
  130. f"/cache/{fname}",
  131. temp_path,
  132. ):
  133. downloaded_filename = fname
  134. logger.info(f"Found and downloaded from cache: {fname}")
  135. break
  136. except Exception as e:
  137. logger.warning(f"Failed to list cache: {e}")
  138. if not downloaded_filename or not temp_path:
  139. logger.warning(f"Could not find 3MF file for print: {filename or subtask_name}")
  140. return
  141. try:
  142. # Archive the file with status "printing"
  143. service = ArchiveService(db)
  144. archive = await service.archive_print(
  145. printer_id=printer_id,
  146. source_file=temp_path,
  147. print_data={**data, "status": "printing"},
  148. )
  149. if archive:
  150. # Track this active print (use both original filename and downloaded filename)
  151. _active_prints[(printer_id, downloaded_filename)] = archive.id
  152. if filename and filename != downloaded_filename:
  153. _active_prints[(printer_id, filename)] = archive.id
  154. if subtask_name:
  155. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  156. logger.info(f"Created archive {archive.id} for {downloaded_filename}")
  157. # Record starting energy from smart plug if available
  158. try:
  159. plug_result = await db.execute(
  160. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  161. )
  162. plug = plug_result.scalar_one_or_none()
  163. if plug:
  164. energy = await tasmota_service.get_energy(plug)
  165. if energy and energy.get("total") is not None:
  166. _print_energy_start[archive.id] = energy["total"]
  167. logger.info(f"Recorded starting energy for archive {archive.id}: {energy['total']} kWh")
  168. except Exception as e:
  169. logger.warning(f"Failed to record starting energy: {e}")
  170. await ws_manager.send_archive_created({
  171. "id": archive.id,
  172. "printer_id": archive.printer_id,
  173. "filename": archive.filename,
  174. "print_name": archive.print_name,
  175. "status": archive.status,
  176. })
  177. finally:
  178. if temp_path and temp_path.exists():
  179. temp_path.unlink()
  180. # Smart plug automation: turn on plug when print starts
  181. try:
  182. async with async_session() as db:
  183. await smart_plug_manager.on_print_start(printer_id, db)
  184. except Exception as e:
  185. import logging
  186. logging.getLogger(__name__).warning(f"Smart plug on_print_start failed: {e}")
  187. async def on_print_complete(printer_id: int, data: dict):
  188. """Handle print completion - update the archive status."""
  189. import logging
  190. logger = logging.getLogger(__name__)
  191. await ws_manager.send_print_complete(printer_id, data)
  192. filename = data.get("filename", "")
  193. if not filename:
  194. return
  195. logger.info(f"Print complete - filename: {filename}, status: {data.get('status')}")
  196. # Build list of possible keys to try
  197. possible_keys = []
  198. if filename.endswith(".3mf"):
  199. possible_keys.append((printer_id, filename))
  200. elif filename.endswith(".gcode"):
  201. base_name = filename.rsplit(".", 1)[0]
  202. possible_keys.append((printer_id, f"{base_name}.3mf"))
  203. possible_keys.append((printer_id, filename))
  204. else:
  205. possible_keys.append((printer_id, f"{filename}.3mf"))
  206. possible_keys.append((printer_id, filename))
  207. # Find the archive for this print
  208. archive_id = None
  209. for key in possible_keys:
  210. archive_id = _active_prints.pop(key, None)
  211. if archive_id:
  212. # Also clean up any other keys pointing to this archive
  213. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  214. for k in keys_to_remove:
  215. _active_prints.pop(k, None)
  216. break
  217. if not archive_id:
  218. # Try to find by filename if not tracked (for prints started before app)
  219. async with async_session() as db:
  220. from backend.app.models.archive import PrintArchive
  221. from sqlalchemy import select
  222. result = await db.execute(
  223. select(PrintArchive)
  224. .where(PrintArchive.printer_id == printer_id)
  225. .where(PrintArchive.filename == filename)
  226. .where(PrintArchive.status == "printing")
  227. .order_by(PrintArchive.created_at.desc())
  228. .limit(1)
  229. )
  230. archive = result.scalar_one_or_none()
  231. if archive:
  232. archive_id = archive.id
  233. if not archive_id:
  234. return
  235. # Update archive status
  236. async with async_session() as db:
  237. service = ArchiveService(db)
  238. status = data.get("status", "completed")
  239. await service.update_archive_status(
  240. archive_id,
  241. status=status,
  242. completed_at=datetime.now() if status in ("completed", "failed") else None,
  243. )
  244. await ws_manager.send_archive_updated({
  245. "id": archive_id,
  246. "status": status,
  247. })
  248. # Calculate energy used for this print
  249. try:
  250. starting_kwh = _print_energy_start.pop(archive_id, None)
  251. if starting_kwh is not None:
  252. async with async_session() as db:
  253. # Get smart plug for this printer
  254. plug_result = await db.execute(
  255. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  256. )
  257. plug = plug_result.scalar_one_or_none()
  258. if plug:
  259. energy = await tasmota_service.get_energy(plug)
  260. if energy and energy.get("total") is not None:
  261. ending_kwh = energy["total"]
  262. energy_used = round(ending_kwh - starting_kwh, 4)
  263. # Get energy cost per kWh from settings (default to 0.15)
  264. from backend.app.api.routes.settings import get_setting
  265. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  266. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  267. energy_cost = round(energy_used * cost_per_kwh, 2)
  268. # Update archive with energy data
  269. from backend.app.models.archive import PrintArchive
  270. result = await db.execute(
  271. select(PrintArchive).where(PrintArchive.id == archive_id)
  272. )
  273. archive = result.scalar_one_or_none()
  274. if archive:
  275. archive.energy_kwh = energy_used
  276. archive.energy_cost = energy_cost
  277. await db.commit()
  278. logger.info(f"Recorded energy for archive {archive_id}: {energy_used} kWh (${energy_cost})")
  279. except Exception as e:
  280. import logging
  281. logging.getLogger(__name__).warning(f"Failed to calculate energy: {e}")
  282. # Capture finish photo from printer camera
  283. try:
  284. async with async_session() as db:
  285. # Check if finish photo capture is enabled
  286. from backend.app.api.routes.settings import get_setting
  287. capture_enabled = await get_setting(db, "capture_finish_photo")
  288. if capture_enabled is None or capture_enabled.lower() == "true":
  289. # Get printer details
  290. from backend.app.models.printer import Printer
  291. from sqlalchemy import select
  292. result = await db.execute(
  293. select(Printer).where(Printer.id == printer_id)
  294. )
  295. printer = result.scalar_one_or_none()
  296. if printer and archive_id:
  297. # Get archive to find its directory
  298. from backend.app.models.archive import PrintArchive
  299. result = await db.execute(
  300. select(PrintArchive).where(PrintArchive.id == archive_id)
  301. )
  302. archive = result.scalar_one_or_none()
  303. if archive:
  304. from backend.app.services.camera import capture_finish_photo
  305. from pathlib import Path
  306. archive_dir = app_settings.base_dir / Path(archive.file_path).parent
  307. photo_filename = await capture_finish_photo(
  308. printer_id=printer_id,
  309. ip_address=printer.ip_address,
  310. access_code=printer.access_code,
  311. model=printer.model,
  312. archive_dir=archive_dir,
  313. )
  314. if photo_filename:
  315. # Add photo to archive's photos list
  316. photos = archive.photos or []
  317. photos.append(photo_filename)
  318. archive.photos = photos
  319. await db.commit()
  320. logger.info(f"Added finish photo to archive {archive_id}: {photo_filename}")
  321. except Exception as e:
  322. import logging
  323. logging.getLogger(__name__).warning(f"Finish photo capture failed: {e}")
  324. # Smart plug automation: schedule turn off when print completes
  325. try:
  326. async with async_session() as db:
  327. status = data.get("status", "completed")
  328. await smart_plug_manager.on_print_complete(printer_id, status, db)
  329. except Exception as e:
  330. import logging
  331. logging.getLogger(__name__).warning(f"Smart plug on_print_complete failed: {e}")
  332. @asynccontextmanager
  333. async def lifespan(app: FastAPI):
  334. # Startup
  335. await init_db()
  336. # Set up printer manager callbacks
  337. loop = asyncio.get_event_loop()
  338. printer_manager.set_event_loop(loop)
  339. printer_manager.set_status_change_callback(on_printer_status_change)
  340. printer_manager.set_print_start_callback(on_print_start)
  341. printer_manager.set_print_complete_callback(on_print_complete)
  342. # Connect to all active printers
  343. async with async_session() as db:
  344. await init_printer_connections(db)
  345. yield
  346. # Shutdown
  347. printer_manager.disconnect_all()
  348. app = FastAPI(
  349. title=app_settings.app_name,
  350. description="Archive and manage Bambu Lab 3MF files",
  351. version="0.1.2",
  352. lifespan=lifespan,
  353. )
  354. # API routes
  355. app.include_router(printers.router, prefix=app_settings.api_prefix)
  356. app.include_router(archives.router, prefix=app_settings.api_prefix)
  357. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  358. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  359. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  360. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  361. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  362. # Serve static files (React build)
  363. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  364. app.mount(
  365. "/assets",
  366. StaticFiles(directory=app_settings.static_dir / "assets"),
  367. name="assets",
  368. )
  369. if (app_settings.static_dir / "img").exists():
  370. app.mount(
  371. "/img",
  372. StaticFiles(directory=app_settings.static_dir / "img"),
  373. name="img",
  374. )
  375. @app.get("/")
  376. async def serve_frontend():
  377. """Serve the React frontend."""
  378. index_file = app_settings.static_dir / "index.html"
  379. if index_file.exists():
  380. return FileResponse(index_file)
  381. return {
  382. "message": "BambuTrack API",
  383. "docs": "/docs",
  384. "frontend": "Build and place React app in /static directory",
  385. }
  386. @app.get("/health")
  387. async def health_check():
  388. """Health check endpoint."""
  389. return {"status": "healthy"}
  390. # Catch-all route for React Router (must be last)
  391. @app.get("/{full_path:path}")
  392. async def serve_spa(full_path: str):
  393. """Serve React app for client-side routing."""
  394. # Don't intercept API routes
  395. if full_path.startswith("api/"):
  396. return {"error": "Not found"}
  397. index_file = app_settings.static_dir / "index.html"
  398. if index_file.exists():
  399. return FileResponse(index_file)
  400. return {"error": "Frontend not built"}