printers.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  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. NozzleInfoResponse,
  22. PrintOptionsResponse,
  23. )
  24. from backend.app.services.printer_manager import printer_manager
  25. from backend.app.services.bambu_mqtt import get_stage_name
  26. from backend.app.services.bambu_ftp import (
  27. download_file_try_paths_async,
  28. list_files_async,
  29. delete_file_async,
  30. download_file_bytes_async,
  31. get_storage_info_async,
  32. )
  33. router = APIRouter(prefix="/printers", tags=["printers"])
  34. @router.get("/", response_model=list[PrinterResponse])
  35. async def list_printers(db: AsyncSession = Depends(get_db)):
  36. """List all configured printers."""
  37. result = await db.execute(select(Printer).order_by(Printer.name))
  38. return list(result.scalars().all())
  39. @router.post("/", response_model=PrinterResponse)
  40. async def create_printer(
  41. printer_data: PrinterCreate,
  42. db: AsyncSession = Depends(get_db),
  43. ):
  44. """Add a new printer."""
  45. # Check if serial number already exists
  46. result = await db.execute(
  47. select(Printer).where(Printer.serial_number == printer_data.serial_number)
  48. )
  49. if result.scalar_one_or_none():
  50. raise HTTPException(400, "Printer with this serial number already exists")
  51. printer = Printer(**printer_data.model_dump())
  52. db.add(printer)
  53. await db.commit()
  54. await db.refresh(printer)
  55. # Connect to the printer
  56. if printer.is_active:
  57. await printer_manager.connect_printer(printer)
  58. return printer
  59. @router.get("/{printer_id}", response_model=PrinterResponse)
  60. async def get_printer(printer_id: int, db: AsyncSession = Depends(get_db)):
  61. """Get a specific printer."""
  62. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  63. printer = result.scalar_one_or_none()
  64. if not printer:
  65. raise HTTPException(404, "Printer not found")
  66. return printer
  67. @router.patch("/{printer_id}", response_model=PrinterResponse)
  68. async def update_printer(
  69. printer_id: int,
  70. printer_data: PrinterUpdate,
  71. db: AsyncSession = Depends(get_db),
  72. ):
  73. """Update a printer."""
  74. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  75. printer = result.scalar_one_or_none()
  76. if not printer:
  77. raise HTTPException(404, "Printer not found")
  78. update_data = printer_data.model_dump(exclude_unset=True)
  79. for field, value in update_data.items():
  80. setattr(printer, field, value)
  81. await db.commit()
  82. await db.refresh(printer)
  83. # Reconnect if connection settings changed
  84. if any(k in update_data for k in ["ip_address", "access_code", "is_active"]):
  85. printer_manager.disconnect_printer(printer_id)
  86. if printer.is_active:
  87. await printer_manager.connect_printer(printer)
  88. return printer
  89. @router.delete("/{printer_id}")
  90. async def delete_printer(printer_id: int, db: AsyncSession = Depends(get_db)):
  91. """Delete a printer."""
  92. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  93. printer = result.scalar_one_or_none()
  94. if not printer:
  95. raise HTTPException(404, "Printer not found")
  96. printer_manager.disconnect_printer(printer_id)
  97. await db.delete(printer)
  98. await db.commit()
  99. return {"status": "deleted"}
  100. @router.get("/{printer_id}/status", response_model=PrinterStatus)
  101. async def get_printer_status(printer_id: int, db: AsyncSession = Depends(get_db)):
  102. """Get real-time status of a printer."""
  103. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  104. printer = result.scalar_one_or_none()
  105. if not printer:
  106. raise HTTPException(404, "Printer not found")
  107. state = printer_manager.get_status(printer_id)
  108. if not state:
  109. return PrinterStatus(
  110. id=printer_id,
  111. name=printer.name,
  112. connected=False,
  113. )
  114. # Determine cover URL if there's an active print
  115. cover_url = None
  116. if state.state == "RUNNING" and state.gcode_file:
  117. cover_url = f"/api/v1/printers/{printer_id}/cover"
  118. # Convert HMS errors to response format
  119. hms_errors = [
  120. HMSErrorResponse(code=e.code, module=e.module, severity=e.severity)
  121. for e in (state.hms_errors or [])
  122. ]
  123. # Parse AMS data from raw_data
  124. ams_units = []
  125. vt_tray = None
  126. ams_exists = False
  127. raw_data = state.raw_data or {}
  128. if "ams" in raw_data:
  129. ams_exists = True
  130. for ams_data in raw_data["ams"]:
  131. trays = []
  132. for tray_data in ams_data.get("tray", []):
  133. trays.append(AMSTray(
  134. id=tray_data.get("id", 0),
  135. tray_color=tray_data.get("tray_color"),
  136. tray_type=tray_data.get("tray_type"),
  137. remain=tray_data.get("remain", 0),
  138. k=tray_data.get("k"),
  139. ))
  140. ams_units.append(AMSUnit(
  141. id=ams_data.get("id", 0),
  142. humidity=ams_data.get("humidity"),
  143. temp=ams_data.get("temp"),
  144. tray=trays,
  145. ))
  146. # Virtual tray (external spool holder) - comes from vt_tray in raw_data
  147. if "vt_tray" in raw_data:
  148. vt_data = raw_data["vt_tray"]
  149. vt_tray = AMSTray(
  150. id=254, # Virtual tray ID
  151. tray_color=vt_data.get("tray_color"),
  152. tray_type=vt_data.get("tray_type"),
  153. remain=vt_data.get("remain", 0),
  154. k=vt_data.get("k"),
  155. )
  156. # Convert nozzle info to response format
  157. nozzles = [
  158. NozzleInfoResponse(
  159. nozzle_type=n.nozzle_type,
  160. nozzle_diameter=n.nozzle_diameter,
  161. )
  162. for n in (state.nozzles or [])
  163. ]
  164. # Convert print options to response format
  165. print_options = PrintOptionsResponse(
  166. spaghetti_detector=state.print_options.spaghetti_detector,
  167. print_halt=state.print_options.print_halt,
  168. halt_print_sensitivity=state.print_options.halt_print_sensitivity,
  169. first_layer_inspector=state.print_options.first_layer_inspector,
  170. printing_monitor=state.print_options.printing_monitor,
  171. buildplate_marker_detector=state.print_options.buildplate_marker_detector,
  172. allow_skip_parts=state.print_options.allow_skip_parts,
  173. nozzle_clumping_detector=state.print_options.nozzle_clumping_detector,
  174. nozzle_clumping_sensitivity=state.print_options.nozzle_clumping_sensitivity,
  175. pileup_detector=state.print_options.pileup_detector,
  176. pileup_sensitivity=state.print_options.pileup_sensitivity,
  177. airprint_detector=state.print_options.airprint_detector,
  178. airprint_sensitivity=state.print_options.airprint_sensitivity,
  179. auto_recovery_step_loss=state.print_options.auto_recovery_step_loss,
  180. filament_tangle_detect=state.print_options.filament_tangle_detect,
  181. )
  182. return PrinterStatus(
  183. id=printer_id,
  184. name=printer.name,
  185. connected=state.connected,
  186. state=state.state,
  187. current_print=state.current_print,
  188. subtask_name=state.subtask_name,
  189. gcode_file=state.gcode_file,
  190. progress=state.progress,
  191. remaining_time=state.remaining_time,
  192. layer_num=state.layer_num,
  193. total_layers=state.total_layers,
  194. temperatures=state.temperatures,
  195. cover_url=cover_url,
  196. hms_errors=hms_errors,
  197. ams=ams_units,
  198. ams_exists=ams_exists,
  199. vt_tray=vt_tray,
  200. sdcard=state.sdcard,
  201. store_to_sdcard=state.store_to_sdcard,
  202. timelapse=state.timelapse,
  203. ipcam=state.ipcam,
  204. nozzles=nozzles,
  205. print_options=print_options,
  206. stg_cur=state.stg_cur,
  207. stg_cur_name=get_stage_name(state.stg_cur) if state.stg_cur >= 0 else None,
  208. stg=state.stg,
  209. airduct_mode=state.airduct_mode,
  210. speed_level=state.speed_level,
  211. chamber_light=state.chamber_light,
  212. )
  213. @router.post("/{printer_id}/connect")
  214. async def connect_printer(printer_id: int, db: AsyncSession = Depends(get_db)):
  215. """Manually connect to a printer."""
  216. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  217. printer = result.scalar_one_or_none()
  218. if not printer:
  219. raise HTTPException(404, "Printer not found")
  220. success = await printer_manager.connect_printer(printer)
  221. return {"connected": success}
  222. @router.post("/{printer_id}/disconnect")
  223. async def disconnect_printer(printer_id: int, db: AsyncSession = Depends(get_db)):
  224. """Manually disconnect from a printer."""
  225. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  226. printer = result.scalar_one_or_none()
  227. if not printer:
  228. raise HTTPException(404, "Printer not found")
  229. printer_manager.disconnect_printer(printer_id)
  230. return {"connected": False}
  231. @router.post("/test")
  232. async def test_printer_connection(
  233. ip_address: str,
  234. serial_number: str,
  235. access_code: str,
  236. ):
  237. """Test connection to a printer without saving."""
  238. result = await printer_manager.test_connection(
  239. ip_address=ip_address,
  240. serial_number=serial_number,
  241. access_code=access_code,
  242. )
  243. return result
  244. # Cache for cover images (printer_id -> (gcode_file, image_bytes))
  245. _cover_cache: dict[int, tuple[str, bytes]] = {}
  246. @router.get("/{printer_id}/cover")
  247. async def get_printer_cover(printer_id: int, db: AsyncSession = Depends(get_db)):
  248. """Get the cover image for the current print job."""
  249. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  250. printer = result.scalar_one_or_none()
  251. if not printer:
  252. raise HTTPException(404, "Printer not found")
  253. state = printer_manager.get_status(printer_id)
  254. if not state:
  255. raise HTTPException(404, "Printer not connected")
  256. # Use subtask_name as the 3MF filename (gcode_file is the path inside the 3MF)
  257. subtask_name = state.subtask_name
  258. if not subtask_name:
  259. raise HTTPException(404, f"No subtask_name in printer state (state={state.state})")
  260. # Check cache
  261. if printer_id in _cover_cache:
  262. cached_file, cached_image = _cover_cache[printer_id]
  263. if cached_file == subtask_name:
  264. return Response(content=cached_image, media_type="image/png")
  265. # Build 3MF filename from subtask_name
  266. # Bambu printers store files as "name.gcode.3mf"
  267. filename = subtask_name
  268. if not filename.endswith(".3mf"):
  269. filename = filename + ".gcode.3mf"
  270. # Try to download the 3MF file from printer
  271. temp_path = settings.archive_dir / "temp" / f"cover_{printer_id}_{filename}"
  272. temp_path.parent.mkdir(parents=True, exist_ok=True)
  273. remote_paths = [
  274. f"/{filename}", # Root directory (most common)
  275. f"/cache/{filename}",
  276. f"/model/{filename}",
  277. f"/data/{filename}",
  278. ]
  279. logger.info(f"Trying to download cover for '{filename}' from {printer.ip_address}")
  280. try:
  281. downloaded = await download_file_try_paths_async(
  282. printer.ip_address,
  283. printer.access_code,
  284. remote_paths,
  285. temp_path,
  286. )
  287. except Exception as e:
  288. logger.error(f"FTP download exception: {e}")
  289. raise HTTPException(500, f"FTP download failed: {e}")
  290. if not downloaded:
  291. raise HTTPException(404, f"Could not download 3MF file '{filename}' from printer {printer.ip_address}. Tried: {remote_paths}")
  292. # Verify file actually exists and has content
  293. if not temp_path.exists():
  294. raise HTTPException(500, f"Download reported success but file not found: {temp_path}")
  295. file_size = temp_path.stat().st_size
  296. logger.info(f"Downloaded file size: {file_size} bytes")
  297. if file_size == 0:
  298. temp_path.unlink()
  299. raise HTTPException(500, f"Downloaded file is empty: {filename}")
  300. try:
  301. # Extract thumbnail from 3MF (which is a ZIP file)
  302. try:
  303. zf = zipfile.ZipFile(temp_path, 'r')
  304. except zipfile.BadZipFile as e:
  305. raise HTTPException(500, f"Downloaded file is not a valid 3MF/ZIP: {e}")
  306. except Exception as e:
  307. raise HTTPException(500, f"Failed to open 3MF file: {e}")
  308. try:
  309. # Try common thumbnail paths in 3MF files
  310. thumbnail_paths = [
  311. "Metadata/plate_1.png",
  312. "Metadata/thumbnail.png",
  313. "Metadata/plate_1_small.png",
  314. "Thumbnails/thumbnail.png",
  315. "thumbnail.png",
  316. ]
  317. for thumb_path in thumbnail_paths:
  318. try:
  319. image_data = zf.read(thumb_path)
  320. # Cache the result
  321. _cover_cache[printer_id] = (subtask_name, image_data)
  322. return Response(content=image_data, media_type="image/png")
  323. except KeyError:
  324. continue
  325. # If no specific thumbnail found, try any PNG in Metadata
  326. for name in zf.namelist():
  327. if name.startswith("Metadata/") and name.endswith(".png"):
  328. image_data = zf.read(name)
  329. _cover_cache[printer_id] = (subtask_name, image_data)
  330. return Response(content=image_data, media_type="image/png")
  331. raise HTTPException(404, "No thumbnail found in 3MF file")
  332. finally:
  333. zf.close()
  334. finally:
  335. if temp_path.exists():
  336. temp_path.unlink()
  337. # ============================================
  338. # File Manager Endpoints
  339. # ============================================
  340. @router.get("/{printer_id}/files")
  341. async def list_printer_files(
  342. printer_id: int,
  343. path: str = "/",
  344. db: AsyncSession = Depends(get_db),
  345. ):
  346. """List files on the printer at the specified path."""
  347. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  348. printer = result.scalar_one_or_none()
  349. if not printer:
  350. raise HTTPException(404, "Printer not found")
  351. files = await list_files_async(printer.ip_address, printer.access_code, path)
  352. # Add full path to each file
  353. for f in files:
  354. f["path"] = f"{path.rstrip('/')}/{f['name']}" if path != "/" else f"/{f['name']}"
  355. return {
  356. "path": path,
  357. "files": files,
  358. }
  359. @router.get("/{printer_id}/files/download")
  360. async def download_printer_file(
  361. printer_id: int,
  362. path: str,
  363. db: AsyncSession = Depends(get_db),
  364. ):
  365. """Download a file from the printer."""
  366. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  367. printer = result.scalar_one_or_none()
  368. if not printer:
  369. raise HTTPException(404, "Printer not found")
  370. data = await download_file_bytes_async(printer.ip_address, printer.access_code, path)
  371. if data is None:
  372. raise HTTPException(404, f"File not found: {path}")
  373. # Determine content type based on extension
  374. filename = path.split("/")[-1]
  375. ext = filename.lower().split(".")[-1] if "." in filename else ""
  376. content_types = {
  377. "3mf": "application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  378. "gcode": "text/plain",
  379. "mp4": "video/mp4",
  380. "avi": "video/x-msvideo",
  381. "png": "image/png",
  382. "jpg": "image/jpeg",
  383. "jpeg": "image/jpeg",
  384. "json": "application/json",
  385. "txt": "text/plain",
  386. }
  387. content_type = content_types.get(ext, "application/octet-stream")
  388. return Response(
  389. content=data,
  390. media_type=content_type,
  391. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  392. )
  393. @router.delete("/{printer_id}/files")
  394. async def delete_printer_file(
  395. printer_id: int,
  396. path: str,
  397. db: AsyncSession = Depends(get_db),
  398. ):
  399. """Delete a file from the printer."""
  400. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  401. printer = result.scalar_one_or_none()
  402. if not printer:
  403. raise HTTPException(404, "Printer not found")
  404. success = await delete_file_async(printer.ip_address, printer.access_code, path)
  405. if not success:
  406. raise HTTPException(500, f"Failed to delete file: {path}")
  407. return {"status": "deleted", "path": path}
  408. @router.get("/{printer_id}/storage")
  409. async def get_printer_storage(
  410. printer_id: int,
  411. db: AsyncSession = Depends(get_db),
  412. ):
  413. """Get storage information from the printer."""
  414. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  415. printer = result.scalar_one_or_none()
  416. if not printer:
  417. raise HTTPException(404, "Printer not found")
  418. storage_info = await get_storage_info_async(printer.ip_address, printer.access_code)
  419. return storage_info or {"used_bytes": None, "free_bytes": None}
  420. # ============================================
  421. # MQTT Debug Logging Endpoints
  422. # ============================================
  423. @router.post("/{printer_id}/logging/enable")
  424. async def enable_mqtt_logging(printer_id: int, db: AsyncSession = Depends(get_db)):
  425. """Enable MQTT message logging for a printer."""
  426. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  427. printer = result.scalar_one_or_none()
  428. if not printer:
  429. raise HTTPException(404, "Printer not found")
  430. success = printer_manager.enable_logging(printer_id, True)
  431. if not success:
  432. raise HTTPException(400, "Printer not connected")
  433. return {"logging_enabled": True}
  434. @router.post("/{printer_id}/logging/disable")
  435. async def disable_mqtt_logging(printer_id: int, db: AsyncSession = Depends(get_db)):
  436. """Disable MQTT message logging for a printer."""
  437. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  438. printer = result.scalar_one_or_none()
  439. if not printer:
  440. raise HTTPException(404, "Printer not found")
  441. success = printer_manager.enable_logging(printer_id, False)
  442. if not success:
  443. raise HTTPException(400, "Printer not connected")
  444. return {"logging_enabled": False}
  445. @router.get("/{printer_id}/logging")
  446. async def get_mqtt_logs(printer_id: int, db: AsyncSession = Depends(get_db)):
  447. """Get MQTT message logs for a printer."""
  448. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  449. printer = result.scalar_one_or_none()
  450. if not printer:
  451. raise HTTPException(404, "Printer not found")
  452. logs = printer_manager.get_logs(printer_id)
  453. return {
  454. "logging_enabled": printer_manager.is_logging_enabled(printer_id),
  455. "logs": [
  456. {
  457. "timestamp": log.timestamp,
  458. "topic": log.topic,
  459. "direction": log.direction,
  460. "payload": log.payload,
  461. }
  462. for log in logs
  463. ],
  464. }
  465. @router.delete("/{printer_id}/logging")
  466. async def clear_mqtt_logs(printer_id: int, db: AsyncSession = Depends(get_db)):
  467. """Clear MQTT message logs for a printer."""
  468. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  469. printer = result.scalar_one_or_none()
  470. if not printer:
  471. raise HTTPException(404, "Printer not found")
  472. printer_manager.clear_logs(printer_id)
  473. return {"status": "cleared"}
  474. # ============================================
  475. # Print Options (AI Detection) Endpoints
  476. # ============================================
  477. @router.post("/{printer_id}/print-options")
  478. async def set_print_option(
  479. printer_id: int,
  480. module_name: str,
  481. enabled: bool,
  482. print_halt: bool = True,
  483. sensitivity: str = "medium",
  484. db: AsyncSession = Depends(get_db),
  485. ):
  486. """Set an AI detection / print option on the printer.
  487. Valid module_name values:
  488. - spaghetti_detector: Spaghetti detection
  489. - first_layer_inspector: First layer inspection
  490. - printing_monitor: AI print quality monitoring
  491. - buildplate_marker_detector: Build plate marker detection
  492. - allow_skip_parts: Allow skipping failed parts
  493. """
  494. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  495. printer = result.scalar_one_or_none()
  496. if not printer:
  497. raise HTTPException(404, "Printer not found")
  498. client = printer_manager.get_client(printer_id)
  499. if not client or not client.state.connected:
  500. raise HTTPException(400, "Printer not connected")
  501. # Validate module_name
  502. valid_modules = [
  503. "spaghetti_detector",
  504. "first_layer_inspector",
  505. "printing_monitor",
  506. "buildplate_marker_detector",
  507. "allow_skip_parts",
  508. "pileup_detector",
  509. "clump_detector",
  510. "airprint_detector",
  511. "auto_recovery_step_loss",
  512. ]
  513. if module_name not in valid_modules:
  514. raise HTTPException(400, f"Invalid module_name. Must be one of: {valid_modules}")
  515. # Validate sensitivity
  516. valid_sensitivities = ["low", "medium", "high", "never_halt"]
  517. if sensitivity not in valid_sensitivities:
  518. raise HTTPException(400, f"Invalid sensitivity. Must be one of: {valid_sensitivities}")
  519. success = client.set_xcam_option(
  520. module_name=module_name,
  521. enabled=enabled,
  522. print_halt=print_halt,
  523. sensitivity=sensitivity,
  524. )
  525. if not success:
  526. raise HTTPException(500, "Failed to send command to printer")
  527. return {
  528. "success": True,
  529. "module_name": module_name,
  530. "enabled": enabled,
  531. "print_halt": print_halt,
  532. "sensitivity": sensitivity,
  533. }
  534. # ============================================
  535. # Calibration
  536. # ============================================
  537. @router.post("/{printer_id}/calibration")
  538. async def start_calibration(
  539. printer_id: int,
  540. bed_leveling: bool = False,
  541. vibration: bool = False,
  542. motor_noise: bool = False,
  543. nozzle_offset: bool = False,
  544. high_temp_heatbed: bool = False,
  545. db: AsyncSession = Depends(get_db),
  546. ):
  547. """Start printer calibration with selected options.
  548. At least one option must be selected.
  549. Options:
  550. - bed_leveling: Run bed leveling calibration
  551. - vibration: Run vibration compensation calibration
  552. - motor_noise: Run motor noise cancellation calibration
  553. - nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  554. - high_temp_heatbed: Run high-temperature heatbed calibration
  555. """
  556. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  557. printer = result.scalar_one_or_none()
  558. if not printer:
  559. raise HTTPException(404, "Printer not found")
  560. client = printer_manager.get_client(printer_id)
  561. if not client or not client.state.connected:
  562. raise HTTPException(400, "Printer not connected")
  563. # Check that at least one option is selected
  564. if not any([bed_leveling, vibration, motor_noise, nozzle_offset, high_temp_heatbed]):
  565. raise HTTPException(400, "At least one calibration option must be selected")
  566. success = client.start_calibration(
  567. bed_leveling=bed_leveling,
  568. vibration=vibration,
  569. motor_noise=motor_noise,
  570. nozzle_offset=nozzle_offset,
  571. high_temp_heatbed=high_temp_heatbed,
  572. )
  573. if not success:
  574. raise HTTPException(500, "Failed to send calibration command to printer")
  575. return {
  576. "success": True,
  577. "bed_leveling": bed_leveling,
  578. "vibration": vibration,
  579. "motor_noise": motor_noise,
  580. "nozzle_offset": nozzle_offset,
  581. "high_temp_heatbed": high_temp_heatbed,
  582. }