camera.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. """Camera capture service for Bambu Lab printers.
  2. Supports two camera protocols:
  3. - RTSP: Used by X1, X1C, X1E, H2C, H2D, H2DPRO, H2S, P2S (port 322)
  4. - Chamber Image: Used by A1, A1MINI, P1P, P1S (port 6000, custom binary protocol)
  5. """
  6. import asyncio
  7. import logging
  8. import shutil
  9. import ssl
  10. import struct
  11. import uuid
  12. from datetime import datetime
  13. from pathlib import Path
  14. logger = logging.getLogger(__name__)
  15. # JPEG markers
  16. JPEG_START = b"\xff\xd8"
  17. JPEG_END = b"\xff\xd9"
  18. # Cache the ffmpeg path after first lookup
  19. _ffmpeg_path: str | None = None
  20. def get_ffmpeg_path() -> str | None:
  21. """Find the ffmpeg executable path.
  22. Uses shutil.which first, then checks common installation locations
  23. for systems where PATH may be limited (e.g., systemd services).
  24. """
  25. global _ffmpeg_path
  26. if _ffmpeg_path is not None:
  27. return _ffmpeg_path
  28. # Try PATH first
  29. ffmpeg_path = shutil.which("ffmpeg")
  30. # If not found via PATH, check common installation locations
  31. if ffmpeg_path is None:
  32. common_paths = [
  33. "/usr/bin/ffmpeg",
  34. "/usr/local/bin/ffmpeg",
  35. "/opt/homebrew/bin/ffmpeg", # macOS Homebrew
  36. "/snap/bin/ffmpeg", # Ubuntu Snap
  37. "C:\\ffmpeg\\bin\\ffmpeg.exe", # Windows common
  38. ]
  39. for path in common_paths:
  40. if Path(path).exists():
  41. ffmpeg_path = path
  42. break
  43. _ffmpeg_path = ffmpeg_path
  44. if ffmpeg_path:
  45. logger.info(f"Found ffmpeg at: {ffmpeg_path}")
  46. else:
  47. logger.warning("ffmpeg not found in PATH or common locations")
  48. return ffmpeg_path
  49. def supports_rtsp(model: str | None) -> bool:
  50. """Check if printer model supports RTSP camera streaming.
  51. RTSP supported: X1, X1C, X1E, H2C, H2D, H2DPRO, H2S, P2S
  52. Chamber image only: A1, A1MINI, P1P, P1S
  53. Note: Model can be either display name (e.g., "P2S") or internal code (e.g., "N7").
  54. Internal codes from MQTT/SSDP:
  55. - BL-P001: X1/X1C
  56. - C13: X1E
  57. - O1D: H2D
  58. - O1C: H2C
  59. - O1S: H2S
  60. - O1E, O2D: H2D Pro
  61. - N7: P2S
  62. """
  63. if model:
  64. model_upper = model.upper()
  65. # Display names: X1, X1C, X1E, H2C, H2D, H2DPRO, H2S, P2S
  66. if model_upper.startswith(("X1", "H2", "P2")):
  67. return True
  68. # Internal codes for RTSP models
  69. if model_upper in ("BL-P001", "C13", "O1D", "O1C", "O1S", "O1E", "O2D", "N7"):
  70. return True
  71. # A1/P1 and unknown models use chamber image protocol
  72. return False
  73. def get_camera_port(model: str | None) -> int:
  74. """Get the camera port based on printer model.
  75. X1/H2/P2 series use RTSP on port 322.
  76. A1/P1 series use chamber image protocol on port 6000.
  77. """
  78. if supports_rtsp(model):
  79. return 322
  80. return 6000
  81. def is_chamber_image_model(model: str | None) -> bool:
  82. """Check if printer uses chamber image protocol instead of RTSP.
  83. A1, A1MINI, P1P, P1S use the chamber image protocol on port 6000.
  84. """
  85. return not supports_rtsp(model)
  86. def build_camera_url(ip_address: str, access_code: str, model: str | None) -> str:
  87. """Build the RTSPS URL for the printer camera (RTSP models only)."""
  88. port = get_camera_port(model)
  89. return f"rtsps://bblp:{access_code}@{ip_address}:{port}/streaming/live/1"
  90. def _create_chamber_auth_payload(access_code: str) -> bytes:
  91. """Create the 80-byte authentication payload for chamber image protocol.
  92. Format:
  93. - Bytes 0-3: 0x40 0x00 0x00 0x00 (magic)
  94. - Bytes 4-7: 0x00 0x30 0x00 0x00 (command)
  95. - Bytes 8-15: zeros (padding)
  96. - Bytes 16-47: username "bblp" (32 bytes, null-padded)
  97. - Bytes 48-79: access code (32 bytes, null-padded)
  98. """
  99. username = b"bblp"
  100. access_code_bytes = access_code.encode("utf-8")
  101. # Build the 80-byte payload
  102. payload = struct.pack(
  103. "<II8s32s32s",
  104. 0x40, # Magic header
  105. 0x3000, # Command
  106. b"\x00" * 8, # Padding
  107. username.ljust(32, b"\x00"), # Username padded to 32 bytes
  108. access_code_bytes.ljust(32, b"\x00"), # Access code padded to 32 bytes
  109. )
  110. return payload
  111. def _create_ssl_context() -> ssl.SSLContext:
  112. """Create an SSL context for chamber image connection.
  113. Bambu printers use self-signed certificates, so we disable verification.
  114. """
  115. ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
  116. ctx.check_hostname = False
  117. ctx.verify_mode = ssl.CERT_NONE
  118. return ctx
  119. async def read_chamber_image_frame(
  120. ip_address: str,
  121. access_code: str,
  122. timeout: float = 10.0,
  123. ) -> bytes | None:
  124. """Read a single JPEG frame from the chamber image protocol.
  125. This is used by A1/P1 printers which don't support RTSP.
  126. Args:
  127. ip_address: Printer IP address
  128. access_code: Printer access code
  129. timeout: Connection timeout in seconds
  130. Returns:
  131. JPEG image data or None if failed
  132. """
  133. port = 6000
  134. ssl_context = _create_ssl_context()
  135. try:
  136. # Connect with SSL
  137. reader, writer = await asyncio.wait_for(
  138. asyncio.open_connection(ip_address, port, ssl=ssl_context),
  139. timeout=timeout,
  140. )
  141. try:
  142. # Send authentication payload
  143. auth_payload = _create_chamber_auth_payload(access_code)
  144. writer.write(auth_payload)
  145. await writer.drain()
  146. # Read the 16-byte header
  147. header = await asyncio.wait_for(reader.readexactly(16), timeout=timeout)
  148. if len(header) < 16:
  149. logger.error("Chamber image: incomplete header received")
  150. return None
  151. # Parse payload size from header (little-endian uint32 at offset 0)
  152. payload_size = struct.unpack("<I", header[0:4])[0]
  153. if payload_size == 0 or payload_size > 10_000_000: # Sanity check: max 10MB
  154. logger.error(f"Chamber image: invalid payload size {payload_size}")
  155. return None
  156. # Read the JPEG data
  157. jpeg_data = await asyncio.wait_for(
  158. reader.readexactly(payload_size),
  159. timeout=timeout,
  160. )
  161. # Validate JPEG markers
  162. if not jpeg_data.startswith(JPEG_START):
  163. logger.error("Chamber image: data is not a valid JPEG (missing start marker)")
  164. return None
  165. if not jpeg_data.endswith(JPEG_END):
  166. logger.warning("Chamber image: JPEG missing end marker, may be truncated")
  167. logger.debug(f"Chamber image: received {len(jpeg_data)} bytes")
  168. return jpeg_data
  169. finally:
  170. writer.close()
  171. try:
  172. await writer.wait_closed()
  173. except Exception:
  174. pass
  175. except TimeoutError:
  176. logger.error(f"Chamber image: connection timeout to {ip_address}:{port}")
  177. return None
  178. except ConnectionRefusedError:
  179. logger.error(f"Chamber image: connection refused by {ip_address}:{port}")
  180. return None
  181. except Exception as e:
  182. logger.exception(f"Chamber image: error connecting to {ip_address}:{port}: {e}")
  183. return None
  184. async def generate_chamber_image_stream(
  185. ip_address: str,
  186. access_code: str,
  187. fps: int = 5,
  188. ) -> asyncio.StreamReader | None:
  189. """Create a persistent connection for streaming chamber images.
  190. Returns a connected reader or None if connection failed.
  191. """
  192. port = 6000
  193. ssl_context = _create_ssl_context()
  194. try:
  195. reader, writer = await asyncio.wait_for(
  196. asyncio.open_connection(ip_address, port, ssl=ssl_context),
  197. timeout=10.0,
  198. )
  199. # Send authentication payload
  200. auth_payload = _create_chamber_auth_payload(access_code)
  201. writer.write(auth_payload)
  202. await writer.drain()
  203. logger.info(f"Chamber image: connected to {ip_address}:{port}")
  204. return reader, writer
  205. except Exception as e:
  206. logger.error(f"Chamber image: failed to connect to {ip_address}:{port}: {e}")
  207. return None
  208. async def read_next_chamber_frame(reader: asyncio.StreamReader, timeout: float = 10.0) -> bytes | None:
  209. """Read the next JPEG frame from an established chamber image connection."""
  210. try:
  211. # Read the 16-byte header
  212. header = await asyncio.wait_for(reader.readexactly(16), timeout=timeout)
  213. # Parse payload size from header (little-endian uint32 at offset 0)
  214. payload_size = struct.unpack("<I", header[0:4])[0]
  215. if payload_size == 0 or payload_size > 10_000_000:
  216. logger.error(f"Chamber image: invalid payload size {payload_size}")
  217. return None
  218. # Read the JPEG data
  219. jpeg_data = await asyncio.wait_for(
  220. reader.readexactly(payload_size),
  221. timeout=timeout,
  222. )
  223. return jpeg_data
  224. except asyncio.IncompleteReadError:
  225. logger.warning("Chamber image: connection closed by printer")
  226. return None
  227. except TimeoutError:
  228. logger.warning("Chamber image: read timeout")
  229. return None
  230. except Exception as e:
  231. logger.error(f"Chamber image: error reading frame: {e}")
  232. return None
  233. async def capture_camera_frame(
  234. ip_address: str,
  235. access_code: str,
  236. model: str | None,
  237. output_path: Path,
  238. timeout: int = 30,
  239. ) -> bool:
  240. """Capture a single frame from the printer's camera stream.
  241. Uses the appropriate protocol based on printer model:
  242. - A1/P1: Chamber image protocol (port 6000)
  243. - X1/H2/P2: RTSP via ffmpeg (port 322)
  244. Args:
  245. ip_address: Printer IP address
  246. access_code: Printer access code
  247. model: Printer model (X1, H2D, P1, A1, etc.)
  248. output_path: Path where to save the captured image
  249. timeout: Timeout in seconds for the capture operation
  250. Returns:
  251. True if capture was successful, False otherwise
  252. """
  253. # Ensure output directory exists
  254. output_path.parent.mkdir(parents=True, exist_ok=True)
  255. # Use chamber image protocol for A1/P1 models
  256. if is_chamber_image_model(model):
  257. logger.info(f"Capturing camera frame from {ip_address} using chamber image protocol (model: {model})")
  258. jpeg_data = await read_chamber_image_frame(ip_address, access_code, timeout=float(timeout))
  259. if jpeg_data:
  260. try:
  261. with open(output_path, "wb") as f:
  262. f.write(jpeg_data)
  263. logger.info(f"Successfully captured camera frame: {output_path}")
  264. return True
  265. except Exception as e:
  266. logger.error(f"Failed to write camera frame: {e}")
  267. return False
  268. return False
  269. # Use RTSP/ffmpeg for X1/H2/P2 models
  270. camera_url = build_camera_url(ip_address, access_code, model)
  271. ffmpeg = get_ffmpeg_path()
  272. if not ffmpeg:
  273. logger.error("ffmpeg not found. Please install ffmpeg to enable camera capture.")
  274. return False
  275. # ffmpeg command to capture a single frame from RTSPS stream
  276. cmd = [
  277. ffmpeg,
  278. "-y", # Overwrite output
  279. "-rtsp_transport",
  280. "tcp",
  281. "-rtsp_flags",
  282. "prefer_tcp",
  283. "-i",
  284. camera_url,
  285. "-frames:v",
  286. "1",
  287. "-update",
  288. "1",
  289. "-q:v",
  290. "2",
  291. str(output_path),
  292. ]
  293. logger.info(f"Capturing camera frame from {ip_address} using RTSP (model: {model})")
  294. try:
  295. process = await asyncio.create_subprocess_exec(
  296. *cmd,
  297. stdout=asyncio.subprocess.PIPE,
  298. stderr=asyncio.subprocess.PIPE,
  299. )
  300. try:
  301. stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
  302. except TimeoutError:
  303. process.kill()
  304. await process.wait()
  305. logger.error(f"Camera capture timed out after {timeout}s")
  306. return False
  307. if process.returncode != 0:
  308. stderr_text = stderr.decode() if stderr else "Unknown error"
  309. logger.error(f"ffmpeg failed with code {process.returncode}: {stderr_text}")
  310. return False
  311. if output_path.exists() and output_path.stat().st_size > 0:
  312. logger.info(f"Successfully captured camera frame: {output_path}")
  313. return True
  314. else:
  315. logger.error("Camera capture produced no output file")
  316. return False
  317. except FileNotFoundError:
  318. logger.error("ffmpeg not found. Please install ffmpeg to enable camera capture.")
  319. return False
  320. except Exception as e:
  321. logger.exception(f"Camera capture failed: {e}")
  322. return False
  323. async def capture_finish_photo(
  324. printer_id: int,
  325. ip_address: str,
  326. access_code: str,
  327. model: str | None,
  328. archive_dir: Path,
  329. ) -> str | None:
  330. """Capture a finish photo and save it to the archive's photos folder.
  331. Args:
  332. printer_id: ID of the printer
  333. ip_address: Printer IP address
  334. access_code: Printer access code
  335. model: Printer model
  336. archive_dir: Directory of the archive (where the 3MF is stored)
  337. Returns:
  338. Filename of the captured photo, or None if capture failed
  339. """
  340. # Create photos subdirectory
  341. photos_dir = archive_dir / "photos"
  342. photos_dir.mkdir(parents=True, exist_ok=True)
  343. # Generate filename with timestamp
  344. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  345. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  346. output_path = photos_dir / filename
  347. success = await capture_camera_frame(
  348. ip_address=ip_address,
  349. access_code=access_code,
  350. model=model,
  351. output_path=output_path,
  352. timeout=30,
  353. )
  354. if success:
  355. logger.info(f"Finish photo saved: {filename}")
  356. return filename
  357. else:
  358. logger.warning(f"Failed to capture finish photo for printer {printer_id}")
  359. return None
  360. async def test_camera_connection(
  361. ip_address: str,
  362. access_code: str,
  363. model: str | None,
  364. ) -> dict:
  365. """Test if the camera stream is accessible.
  366. Returns dict with success status and any error message.
  367. """
  368. import tempfile
  369. with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f:
  370. test_path = Path(f.name)
  371. try:
  372. success = await capture_camera_frame(
  373. ip_address=ip_address,
  374. access_code=access_code,
  375. model=model,
  376. output_path=test_path,
  377. timeout=15,
  378. )
  379. if success:
  380. return {"success": True, "message": "Camera connection successful"}
  381. else:
  382. return {
  383. "success": False,
  384. "error": (
  385. "Failed to capture frame from camera. "
  386. "Ensure the printer is powered on, camera is enabled, and Developer Mode is active. "
  387. "If running in Docker, try 'network_mode: host' in docker-compose.yml."
  388. ),
  389. }
  390. finally:
  391. # Clean up test file
  392. if test_path.exists():
  393. test_path.unlink()