printers.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. import io
  2. import logging
  3. import zipfile
  4. from pathlib import Path
  5. from fastapi import APIRouter, Depends, HTTPException
  6. logger = logging.getLogger(__name__)
  7. from fastapi.responses import Response
  8. from sqlalchemy.ext.asyncio import AsyncSession
  9. from sqlalchemy import select
  10. from backend.app.core.database import get_db
  11. from backend.app.core.config import settings
  12. from backend.app.models.printer import Printer
  13. from backend.app.schemas.printer import (
  14. PrinterCreate,
  15. PrinterUpdate,
  16. PrinterResponse,
  17. PrinterStatus,
  18. HMSErrorResponse,
  19. AMSUnit,
  20. AMSTray,
  21. )
  22. from backend.app.services.printer_manager import printer_manager
  23. from backend.app.services.bambu_ftp import (
  24. download_file_try_paths_async,
  25. list_files_async,
  26. delete_file_async,
  27. download_file_bytes_async,
  28. get_storage_info_async,
  29. )
  30. router = APIRouter(prefix="/printers", tags=["printers"])
  31. @router.get("/", response_model=list[PrinterResponse])
  32. async def list_printers(db: AsyncSession = Depends(get_db)):
  33. """List all configured printers."""
  34. result = await db.execute(select(Printer).order_by(Printer.name))
  35. return list(result.scalars().all())
  36. @router.post("/", response_model=PrinterResponse)
  37. async def create_printer(
  38. printer_data: PrinterCreate,
  39. db: AsyncSession = Depends(get_db),
  40. ):
  41. """Add a new printer."""
  42. # Check if serial number already exists
  43. result = await db.execute(
  44. select(Printer).where(Printer.serial_number == printer_data.serial_number)
  45. )
  46. if result.scalar_one_or_none():
  47. raise HTTPException(400, "Printer with this serial number already exists")
  48. printer = Printer(**printer_data.model_dump())
  49. db.add(printer)
  50. await db.commit()
  51. await db.refresh(printer)
  52. # Connect to the printer
  53. if printer.is_active:
  54. await printer_manager.connect_printer(printer)
  55. return printer
  56. @router.get("/{printer_id}", response_model=PrinterResponse)
  57. async def get_printer(printer_id: int, db: AsyncSession = Depends(get_db)):
  58. """Get a specific printer."""
  59. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  60. printer = result.scalar_one_or_none()
  61. if not printer:
  62. raise HTTPException(404, "Printer not found")
  63. return printer
  64. @router.patch("/{printer_id}", response_model=PrinterResponse)
  65. async def update_printer(
  66. printer_id: int,
  67. printer_data: PrinterUpdate,
  68. db: AsyncSession = Depends(get_db),
  69. ):
  70. """Update a printer."""
  71. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  72. printer = result.scalar_one_or_none()
  73. if not printer:
  74. raise HTTPException(404, "Printer not found")
  75. update_data = printer_data.model_dump(exclude_unset=True)
  76. for field, value in update_data.items():
  77. setattr(printer, field, value)
  78. await db.commit()
  79. await db.refresh(printer)
  80. # Reconnect if connection settings changed
  81. if any(k in update_data for k in ["ip_address", "access_code", "is_active"]):
  82. printer_manager.disconnect_printer(printer_id)
  83. if printer.is_active:
  84. await printer_manager.connect_printer(printer)
  85. return printer
  86. @router.delete("/{printer_id}")
  87. async def delete_printer(printer_id: int, db: AsyncSession = Depends(get_db)):
  88. """Delete a printer."""
  89. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  90. printer = result.scalar_one_or_none()
  91. if not printer:
  92. raise HTTPException(404, "Printer not found")
  93. printer_manager.disconnect_printer(printer_id)
  94. await db.delete(printer)
  95. await db.commit()
  96. return {"status": "deleted"}
  97. @router.get("/{printer_id}/status", response_model=PrinterStatus)
  98. async def get_printer_status(printer_id: int, db: AsyncSession = Depends(get_db)):
  99. """Get real-time status of a printer."""
  100. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  101. printer = result.scalar_one_or_none()
  102. if not printer:
  103. raise HTTPException(404, "Printer not found")
  104. state = printer_manager.get_status(printer_id)
  105. if not state:
  106. return PrinterStatus(
  107. id=printer_id,
  108. name=printer.name,
  109. connected=False,
  110. )
  111. # Determine cover URL if there's an active print
  112. cover_url = None
  113. if state.state == "RUNNING" and state.gcode_file:
  114. cover_url = f"/api/v1/printers/{printer_id}/cover"
  115. # Convert HMS errors to response format
  116. hms_errors = [
  117. HMSErrorResponse(code=e.code, module=e.module, severity=e.severity)
  118. for e in (state.hms_errors or [])
  119. ]
  120. # Parse AMS data from raw_data
  121. ams_units = []
  122. vt_tray = None
  123. ams_exists = False
  124. raw_data = state.raw_data or {}
  125. if "ams" in raw_data:
  126. ams_exists = True
  127. for ams_data in raw_data["ams"]:
  128. trays = []
  129. for tray_data in ams_data.get("tray", []):
  130. trays.append(AMSTray(
  131. id=tray_data.get("id", 0),
  132. tray_color=tray_data.get("tray_color"),
  133. tray_type=tray_data.get("tray_type"),
  134. remain=tray_data.get("remain", 0),
  135. k=tray_data.get("k"),
  136. ))
  137. ams_units.append(AMSUnit(
  138. id=ams_data.get("id", 0),
  139. humidity=ams_data.get("humidity"),
  140. temp=ams_data.get("temp"),
  141. tray=trays,
  142. ))
  143. # Virtual tray (external spool holder) - comes from vt_tray in raw_data
  144. if "vt_tray" in raw_data:
  145. vt_data = raw_data["vt_tray"]
  146. vt_tray = AMSTray(
  147. id=254, # Virtual tray ID
  148. tray_color=vt_data.get("tray_color"),
  149. tray_type=vt_data.get("tray_type"),
  150. remain=vt_data.get("remain", 0),
  151. k=vt_data.get("k"),
  152. )
  153. return PrinterStatus(
  154. id=printer_id,
  155. name=printer.name,
  156. connected=state.connected,
  157. state=state.state,
  158. current_print=state.current_print,
  159. subtask_name=state.subtask_name,
  160. gcode_file=state.gcode_file,
  161. progress=state.progress,
  162. remaining_time=state.remaining_time,
  163. layer_num=state.layer_num,
  164. total_layers=state.total_layers,
  165. temperatures=state.temperatures,
  166. cover_url=cover_url,
  167. hms_errors=hms_errors,
  168. ams=ams_units,
  169. ams_exists=ams_exists,
  170. vt_tray=vt_tray,
  171. sdcard=state.sdcard,
  172. timelapse=state.timelapse,
  173. ipcam=state.ipcam,
  174. )
  175. @router.post("/{printer_id}/connect")
  176. async def connect_printer(printer_id: int, db: AsyncSession = Depends(get_db)):
  177. """Manually connect to a printer."""
  178. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  179. printer = result.scalar_one_or_none()
  180. if not printer:
  181. raise HTTPException(404, "Printer not found")
  182. success = await printer_manager.connect_printer(printer)
  183. return {"connected": success}
  184. @router.post("/{printer_id}/disconnect")
  185. async def disconnect_printer(printer_id: int, db: AsyncSession = Depends(get_db)):
  186. """Manually disconnect from a printer."""
  187. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  188. printer = result.scalar_one_or_none()
  189. if not printer:
  190. raise HTTPException(404, "Printer not found")
  191. printer_manager.disconnect_printer(printer_id)
  192. return {"connected": False}
  193. @router.post("/test")
  194. async def test_printer_connection(
  195. ip_address: str,
  196. serial_number: str,
  197. access_code: str,
  198. ):
  199. """Test connection to a printer without saving."""
  200. result = await printer_manager.test_connection(
  201. ip_address=ip_address,
  202. serial_number=serial_number,
  203. access_code=access_code,
  204. )
  205. return result
  206. # Cache for cover images (printer_id -> (gcode_file, image_bytes))
  207. _cover_cache: dict[int, tuple[str, bytes]] = {}
  208. @router.get("/{printer_id}/cover")
  209. async def get_printer_cover(printer_id: int, db: AsyncSession = Depends(get_db)):
  210. """Get the cover image for the current print job."""
  211. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  212. printer = result.scalar_one_or_none()
  213. if not printer:
  214. raise HTTPException(404, "Printer not found")
  215. state = printer_manager.get_status(printer_id)
  216. if not state:
  217. raise HTTPException(404, "Printer not connected")
  218. # Use subtask_name as the 3MF filename (gcode_file is the path inside the 3MF)
  219. subtask_name = state.subtask_name
  220. if not subtask_name:
  221. raise HTTPException(404, f"No subtask_name in printer state (state={state.state})")
  222. # Check cache
  223. if printer_id in _cover_cache:
  224. cached_file, cached_image = _cover_cache[printer_id]
  225. if cached_file == subtask_name:
  226. return Response(content=cached_image, media_type="image/png")
  227. # Build 3MF filename from subtask_name
  228. # Bambu printers store files as "name.gcode.3mf"
  229. filename = subtask_name
  230. if not filename.endswith(".3mf"):
  231. filename = filename + ".gcode.3mf"
  232. # Try to download the 3MF file from printer
  233. temp_path = settings.archive_dir / "temp" / f"cover_{printer_id}_{filename}"
  234. temp_path.parent.mkdir(parents=True, exist_ok=True)
  235. remote_paths = [
  236. f"/{filename}", # Root directory (most common)
  237. f"/cache/{filename}",
  238. f"/model/{filename}",
  239. f"/data/{filename}",
  240. ]
  241. logger.info(f"Trying to download cover for '{filename}' from {printer.ip_address}")
  242. try:
  243. downloaded = await download_file_try_paths_async(
  244. printer.ip_address,
  245. printer.access_code,
  246. remote_paths,
  247. temp_path,
  248. )
  249. except Exception as e:
  250. logger.error(f"FTP download exception: {e}")
  251. raise HTTPException(500, f"FTP download failed: {e}")
  252. if not downloaded:
  253. raise HTTPException(404, f"Could not download 3MF file '{filename}' from printer {printer.ip_address}. Tried: {remote_paths}")
  254. # Verify file actually exists and has content
  255. if not temp_path.exists():
  256. raise HTTPException(500, f"Download reported success but file not found: {temp_path}")
  257. file_size = temp_path.stat().st_size
  258. logger.info(f"Downloaded file size: {file_size} bytes")
  259. if file_size == 0:
  260. temp_path.unlink()
  261. raise HTTPException(500, f"Downloaded file is empty: {filename}")
  262. try:
  263. # Extract thumbnail from 3MF (which is a ZIP file)
  264. try:
  265. zf = zipfile.ZipFile(temp_path, 'r')
  266. except zipfile.BadZipFile as e:
  267. raise HTTPException(500, f"Downloaded file is not a valid 3MF/ZIP: {e}")
  268. except Exception as e:
  269. raise HTTPException(500, f"Failed to open 3MF file: {e}")
  270. try:
  271. # Try common thumbnail paths in 3MF files
  272. thumbnail_paths = [
  273. "Metadata/plate_1.png",
  274. "Metadata/thumbnail.png",
  275. "Metadata/plate_1_small.png",
  276. "Thumbnails/thumbnail.png",
  277. "thumbnail.png",
  278. ]
  279. for thumb_path in thumbnail_paths:
  280. try:
  281. image_data = zf.read(thumb_path)
  282. # Cache the result
  283. _cover_cache[printer_id] = (subtask_name, image_data)
  284. return Response(content=image_data, media_type="image/png")
  285. except KeyError:
  286. continue
  287. # If no specific thumbnail found, try any PNG in Metadata
  288. for name in zf.namelist():
  289. if name.startswith("Metadata/") and name.endswith(".png"):
  290. image_data = zf.read(name)
  291. _cover_cache[printer_id] = (subtask_name, image_data)
  292. return Response(content=image_data, media_type="image/png")
  293. raise HTTPException(404, "No thumbnail found in 3MF file")
  294. finally:
  295. zf.close()
  296. finally:
  297. if temp_path.exists():
  298. temp_path.unlink()
  299. # ============================================
  300. # File Manager Endpoints
  301. # ============================================
  302. @router.get("/{printer_id}/files")
  303. async def list_printer_files(
  304. printer_id: int,
  305. path: str = "/",
  306. db: AsyncSession = Depends(get_db),
  307. ):
  308. """List files on the printer at the specified path."""
  309. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  310. printer = result.scalar_one_or_none()
  311. if not printer:
  312. raise HTTPException(404, "Printer not found")
  313. files = await list_files_async(printer.ip_address, printer.access_code, path)
  314. # Add full path to each file
  315. for f in files:
  316. f["path"] = f"{path.rstrip('/')}/{f['name']}" if path != "/" else f"/{f['name']}"
  317. return {
  318. "path": path,
  319. "files": files,
  320. }
  321. @router.get("/{printer_id}/files/download")
  322. async def download_printer_file(
  323. printer_id: int,
  324. path: str,
  325. db: AsyncSession = Depends(get_db),
  326. ):
  327. """Download a file from the printer."""
  328. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  329. printer = result.scalar_one_or_none()
  330. if not printer:
  331. raise HTTPException(404, "Printer not found")
  332. data = await download_file_bytes_async(printer.ip_address, printer.access_code, path)
  333. if data is None:
  334. raise HTTPException(404, f"File not found: {path}")
  335. # Determine content type based on extension
  336. filename = path.split("/")[-1]
  337. ext = filename.lower().split(".")[-1] if "." in filename else ""
  338. content_types = {
  339. "3mf": "application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  340. "gcode": "text/plain",
  341. "mp4": "video/mp4",
  342. "avi": "video/x-msvideo",
  343. "png": "image/png",
  344. "jpg": "image/jpeg",
  345. "jpeg": "image/jpeg",
  346. "json": "application/json",
  347. "txt": "text/plain",
  348. }
  349. content_type = content_types.get(ext, "application/octet-stream")
  350. return Response(
  351. content=data,
  352. media_type=content_type,
  353. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  354. )
  355. @router.delete("/{printer_id}/files")
  356. async def delete_printer_file(
  357. printer_id: int,
  358. path: str,
  359. db: AsyncSession = Depends(get_db),
  360. ):
  361. """Delete a file from the printer."""
  362. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  363. printer = result.scalar_one_or_none()
  364. if not printer:
  365. raise HTTPException(404, "Printer not found")
  366. success = await delete_file_async(printer.ip_address, printer.access_code, path)
  367. if not success:
  368. raise HTTPException(500, f"Failed to delete file: {path}")
  369. return {"status": "deleted", "path": path}
  370. @router.get("/{printer_id}/storage")
  371. async def get_printer_storage(
  372. printer_id: int,
  373. db: AsyncSession = Depends(get_db),
  374. ):
  375. """Get storage information from the printer."""
  376. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  377. printer = result.scalar_one_or_none()
  378. if not printer:
  379. raise HTTPException(404, "Printer not found")
  380. storage_info = await get_storage_info_async(printer.ip_address, printer.access_code)
  381. return storage_info or {"used_bytes": None, "free_bytes": None}
  382. # ============================================
  383. # MQTT Debug Logging Endpoints
  384. # ============================================
  385. @router.post("/{printer_id}/logging/enable")
  386. async def enable_mqtt_logging(printer_id: int, db: AsyncSession = Depends(get_db)):
  387. """Enable MQTT message logging for a printer."""
  388. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  389. printer = result.scalar_one_or_none()
  390. if not printer:
  391. raise HTTPException(404, "Printer not found")
  392. success = printer_manager.enable_logging(printer_id, True)
  393. if not success:
  394. raise HTTPException(400, "Printer not connected")
  395. return {"logging_enabled": True}
  396. @router.post("/{printer_id}/logging/disable")
  397. async def disable_mqtt_logging(printer_id: int, db: AsyncSession = Depends(get_db)):
  398. """Disable MQTT message logging for a printer."""
  399. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  400. printer = result.scalar_one_or_none()
  401. if not printer:
  402. raise HTTPException(404, "Printer not found")
  403. success = printer_manager.enable_logging(printer_id, False)
  404. if not success:
  405. raise HTTPException(400, "Printer not connected")
  406. return {"logging_enabled": False}
  407. @router.get("/{printer_id}/logging")
  408. async def get_mqtt_logs(printer_id: int, db: AsyncSession = Depends(get_db)):
  409. """Get MQTT message logs for a printer."""
  410. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  411. printer = result.scalar_one_or_none()
  412. if not printer:
  413. raise HTTPException(404, "Printer not found")
  414. logs = printer_manager.get_logs(printer_id)
  415. return {
  416. "logging_enabled": printer_manager.is_logging_enabled(printer_id),
  417. "logs": [
  418. {
  419. "timestamp": log.timestamp,
  420. "topic": log.topic,
  421. "direction": log.direction,
  422. "payload": log.payload,
  423. }
  424. for log in logs
  425. ],
  426. }
  427. @router.delete("/{printer_id}/logging")
  428. async def clear_mqtt_logs(printer_id: int, db: AsyncSession = Depends(get_db)):
  429. """Clear MQTT message logs for a printer."""
  430. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  431. printer = result.scalar_one_or_none()
  432. if not printer:
  433. raise HTTPException(404, "Printer not found")
  434. printer_manager.clear_logs(printer_id)
  435. return {"status": "cleared"}