camera.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. """Camera capture service for Bambu Lab printers.
  2. Supports two camera protocols:
  3. - RTSP: Used by X1, X1C, X1E, X2D, 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 os
  9. import shutil
  10. import ssl
  11. import struct
  12. import uuid
  13. from datetime import datetime
  14. from pathlib import Path
  15. logger = logging.getLogger(__name__)
  16. # JPEG markers
  17. JPEG_START = b"\xff\xd8"
  18. JPEG_END = b"\xff\xd9"
  19. # Cache the ffmpeg path after first lookup
  20. _ffmpeg_path: str | None = None
  21. def get_ffmpeg_path() -> str | None:
  22. """Find the ffmpeg executable path.
  23. Uses shutil.which first, then checks common installation locations
  24. for systems where PATH may be limited (e.g., systemd services).
  25. """
  26. global _ffmpeg_path
  27. if _ffmpeg_path is not None:
  28. return _ffmpeg_path
  29. # Try PATH first
  30. ffmpeg_path = shutil.which("ffmpeg")
  31. # If not found via PATH, check common installation locations
  32. if ffmpeg_path is None:
  33. common_paths = [
  34. "/usr/bin/ffmpeg",
  35. "/usr/local/bin/ffmpeg",
  36. "/opt/homebrew/bin/ffmpeg", # macOS Homebrew
  37. "/snap/bin/ffmpeg", # Ubuntu Snap
  38. "C:\\ffmpeg\\bin\\ffmpeg.exe", # Windows common
  39. ]
  40. for path in common_paths:
  41. if Path(path).exists():
  42. ffmpeg_path = path
  43. break
  44. _ffmpeg_path = ffmpeg_path
  45. if ffmpeg_path:
  46. logger.info("Found ffmpeg at: %s", ffmpeg_path)
  47. else:
  48. logger.warning("ffmpeg not found in PATH or common locations")
  49. return ffmpeg_path
  50. def supports_rtsp(model: str | None) -> bool:
  51. """Check if printer model supports RTSP camera streaming.
  52. RTSP supported: X1, X1C, X1E, X2D, H2C, H2D, H2DPRO, H2S, P2S
  53. Chamber image only: A1, A1MINI, P1P, P1S
  54. Note: Model can be either display name (e.g., "P2S") or internal code (e.g., "N7").
  55. Internal codes from MQTT/SSDP:
  56. - BL-P001: X1/X1C
  57. - C13: X1E
  58. - N6: X2D
  59. - O1D: H2D
  60. - O1C, O1C2: H2C
  61. - O1S: H2S
  62. - O1E, O2D: H2D Pro
  63. - N7: P2S
  64. """
  65. if model:
  66. model_upper = model.upper()
  67. # Display names: X1, X1C, X1E, X2D, H2C, H2D, H2DPRO, H2S, P2S
  68. if model_upper.startswith(("X1", "X2", "H2", "P2")):
  69. return True
  70. # Internal codes for RTSP models
  71. if model_upper in ("BL-P001", "C13", "N6", "O1D", "O1C", "O1C2", "O1S", "O1E", "O2D", "N7"):
  72. return True
  73. # A1/P1 and unknown models use chamber image protocol
  74. return False
  75. def get_camera_port(model: str | None) -> int:
  76. """Get the camera port based on printer model.
  77. X1/X2/H2/P2 series use RTSP on port 322.
  78. A1/P1 series use chamber image protocol on port 6000.
  79. """
  80. if supports_rtsp(model):
  81. return 322
  82. return 6000
  83. def rewrite_rtsp_request_url(data: bytes, proxy_url: bytes, real_url: bytes) -> bytes:
  84. """Rewrite RTSP request-line URLs, leaving other lines (e.g. Authorization) intact.
  85. RTSP request lines have the form ``METHOD <url> RTSP/1.0\\r\\n``.
  86. Only those lines are modified so that Digest auth headers (which embed
  87. the original URL and a cryptographic hash) are not broken.
  88. """
  89. rtsp_marker = b" RTSP/1.0"
  90. if rtsp_marker not in data:
  91. return data
  92. lines = data.split(b"\r\n")
  93. for i, line in enumerate(lines):
  94. if line.endswith(rtsp_marker):
  95. lines[i] = line.replace(proxy_url, real_url)
  96. break
  97. return b"\r\n".join(lines)
  98. async def create_tls_proxy(target_host: str, target_port: int) -> tuple[int, "asyncio.Server"]:
  99. """Create a local TCP→TLS proxy for RTSP streams.
  100. Bambu printers use RTSPS (RTSP over TLS) with self-signed certificates.
  101. The Debian ffmpeg package uses GnuTLS, whose hardened defaults reject
  102. certain TLS behaviors (renegotiation, legacy ciphers) that some printer
  103. firmwares (notably P2S) rely on. This causes streams to drop after a
  104. few seconds.
  105. This proxy terminates TLS using Python's ssl module (OpenSSL), which is
  106. more permissive, and exposes a plain TCP port that ffmpeg connects to
  107. with ``rtsp://`` instead of ``rtsps://``.
  108. RTSP embeds URLs in protocol messages (DESCRIBE, SETUP, PLAY). The proxy
  109. rewrites ``127.0.0.1:<proxy_port>`` → ``<target_host>:<target_port>`` in
  110. client→server data so the printer recognises the stream path.
  111. Returns ``(local_port, server)``. Caller must close the server when done.
  112. """
  113. ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
  114. ssl_ctx.check_hostname = False
  115. ssl_ctx.verify_mode = ssl.CERT_NONE
  116. # Filled in after the server socket is created (handler only runs after).
  117. _local_port: list[int] = [0]
  118. async def _handle(client_reader: asyncio.StreamReader, client_writer: asyncio.StreamWriter):
  119. tls_writer = None
  120. try:
  121. tls_reader, tls_writer = await asyncio.wait_for(
  122. asyncio.open_connection(target_host, target_port, ssl=ssl_ctx),
  123. timeout=10.0,
  124. )
  125. # URL patterns for RTSP request-line rewriting.
  126. proxy_url = f"rtsp://127.0.0.1:{_local_port[0]}".encode()
  127. real_url = f"rtsps://{target_host}:{target_port}".encode()
  128. async def _fwd_to_server(src: asyncio.StreamReader, dst: asyncio.StreamWriter):
  129. """Forward client→server, rewriting RTSP request-line URLs only."""
  130. try:
  131. while True:
  132. data = await src.read(65536)
  133. if not data:
  134. break
  135. data = rewrite_rtsp_request_url(data, proxy_url, real_url)
  136. dst.write(data)
  137. await dst.drain()
  138. except (ConnectionError, OSError, asyncio.CancelledError):
  139. pass
  140. finally:
  141. if not dst.is_closing():
  142. try:
  143. dst.close()
  144. except OSError:
  145. pass
  146. async def _fwd_to_client(src: asyncio.StreamReader, dst: asyncio.StreamWriter):
  147. """Forward server→client unchanged."""
  148. try:
  149. while True:
  150. data = await src.read(65536)
  151. if not data:
  152. break
  153. dst.write(data)
  154. await dst.drain()
  155. except (ConnectionError, OSError, asyncio.CancelledError):
  156. pass
  157. finally:
  158. if not dst.is_closing():
  159. try:
  160. dst.close()
  161. except OSError:
  162. pass
  163. await asyncio.gather(
  164. _fwd_to_server(client_reader, tls_writer),
  165. _fwd_to_client(tls_reader, client_writer),
  166. )
  167. except (ConnectionError, OSError, TimeoutError) as e:
  168. logger.debug("TLS proxy connection to %s:%s failed: %s", target_host, target_port, e)
  169. finally:
  170. for w in (client_writer, tls_writer):
  171. if w and not w.is_closing():
  172. try:
  173. w.close()
  174. except OSError:
  175. pass
  176. server = await asyncio.start_server(_handle, "127.0.0.1", 0)
  177. _local_port[0] = server.sockets[0].getsockname()[1]
  178. logger.debug("TLS proxy for %s:%s listening on 127.0.0.1:%s", target_host, target_port, _local_port[0])
  179. return _local_port[0], server
  180. def is_chamber_image_model(model: str | None) -> bool:
  181. """Check if printer uses chamber image protocol instead of RTSP.
  182. A1, A1MINI, P1P, P1S use the chamber image protocol on port 6000.
  183. """
  184. return not supports_rtsp(model)
  185. def build_camera_url(ip_address: str, access_code: str, model: str | None) -> str:
  186. """Build the RTSPS URL for the printer camera (RTSP models only)."""
  187. port = get_camera_port(model)
  188. return f"rtsps://bblp:{access_code}@{ip_address}:{port}/streaming/live/1"
  189. def _create_chamber_auth_payload(access_code: str) -> bytes:
  190. """Create the 80-byte authentication payload for chamber image protocol.
  191. Format:
  192. - Bytes 0-3: 0x40 0x00 0x00 0x00 (magic)
  193. - Bytes 4-7: 0x00 0x30 0x00 0x00 (command)
  194. - Bytes 8-15: zeros (padding)
  195. - Bytes 16-47: username "bblp" (32 bytes, null-padded)
  196. - Bytes 48-79: access code (32 bytes, null-padded)
  197. """
  198. username = b"bblp"
  199. access_code_bytes = access_code.encode("utf-8")
  200. # Build the 80-byte payload
  201. payload = struct.pack(
  202. "<II8s32s32s",
  203. 0x40, # Magic header
  204. 0x3000, # Command
  205. b"\x00" * 8, # Padding
  206. username.ljust(32, b"\x00"), # Username padded to 32 bytes
  207. access_code_bytes.ljust(32, b"\x00"), # Access code padded to 32 bytes
  208. )
  209. return payload
  210. def _create_ssl_context() -> ssl.SSLContext:
  211. """Create an SSL context for chamber image connection.
  212. Bambu printers use self-signed certificates, so we disable verification.
  213. """
  214. ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
  215. ctx.check_hostname = False
  216. ctx.verify_mode = ssl.CERT_NONE
  217. return ctx
  218. async def read_chamber_image_frame(
  219. ip_address: str,
  220. access_code: str,
  221. timeout: float = 10.0,
  222. ) -> bytes | None:
  223. """Read a single JPEG frame from the chamber image protocol.
  224. This is used by A1/P1 printers which don't support RTSP.
  225. Args:
  226. ip_address: Printer IP address
  227. access_code: Printer access code
  228. timeout: Connection timeout in seconds
  229. Returns:
  230. JPEG image data or None if failed
  231. """
  232. port = 6000
  233. ssl_context = _create_ssl_context()
  234. try:
  235. # Connect with SSL
  236. reader, writer = await asyncio.wait_for(
  237. asyncio.open_connection(ip_address, port, ssl=ssl_context),
  238. timeout=timeout,
  239. )
  240. try:
  241. # Send authentication payload
  242. auth_payload = _create_chamber_auth_payload(access_code)
  243. writer.write(auth_payload)
  244. await writer.drain()
  245. # Read the 16-byte header
  246. header = await asyncio.wait_for(reader.readexactly(16), timeout=timeout)
  247. if len(header) < 16:
  248. logger.error("Chamber image: incomplete header received")
  249. return None
  250. # Parse payload size from header (little-endian uint32 at offset 0)
  251. payload_size = struct.unpack("<I", header[0:4])[0]
  252. if payload_size == 0 or payload_size > 10_000_000: # Sanity check: max 10MB
  253. logger.error("Chamber image: invalid payload size %s", payload_size)
  254. return None
  255. # Read the JPEG data
  256. jpeg_data = await asyncio.wait_for(
  257. reader.readexactly(payload_size),
  258. timeout=timeout,
  259. )
  260. # Validate JPEG markers
  261. if not jpeg_data.startswith(JPEG_START):
  262. logger.error("Chamber image: data is not a valid JPEG (missing start marker)")
  263. return None
  264. if not jpeg_data.endswith(JPEG_END):
  265. logger.warning("Chamber image: JPEG missing end marker, may be truncated")
  266. logger.debug("Chamber image: received %s bytes", len(jpeg_data))
  267. return jpeg_data
  268. finally:
  269. writer.close()
  270. try:
  271. await writer.wait_closed()
  272. except OSError:
  273. pass # Socket already closed; cleanup is best-effort
  274. except TimeoutError:
  275. logger.error("Chamber image: connection timeout to %s:%s", ip_address, port)
  276. return None
  277. except ConnectionRefusedError:
  278. logger.error("Chamber image: connection refused by %s:%s", ip_address, port)
  279. return None
  280. except Exception as e:
  281. logger.exception("Chamber image: error connecting to %s:%s: %s", ip_address, port, e)
  282. return None
  283. async def generate_chamber_image_stream(
  284. ip_address: str,
  285. access_code: str,
  286. fps: int = 5,
  287. ) -> asyncio.StreamReader | None:
  288. """Create a persistent connection for streaming chamber images.
  289. Returns a connected reader or None if connection failed.
  290. """
  291. port = 6000
  292. ssl_context = _create_ssl_context()
  293. try:
  294. reader, writer = await asyncio.wait_for(
  295. asyncio.open_connection(ip_address, port, ssl=ssl_context),
  296. timeout=10.0,
  297. )
  298. # Send authentication payload
  299. auth_payload = _create_chamber_auth_payload(access_code)
  300. writer.write(auth_payload)
  301. await writer.drain()
  302. logger.info("Chamber image: connected to %s:%s", ip_address, port)
  303. return reader, writer
  304. except Exception as e:
  305. logger.error("Chamber image: failed to connect to %s:%s: %s", ip_address, port, e)
  306. return None
  307. async def read_next_chamber_frame(reader: asyncio.StreamReader, timeout: float = 10.0) -> bytes | None:
  308. """Read the next JPEG frame from an established chamber image connection."""
  309. try:
  310. # Read the 16-byte header
  311. header = await asyncio.wait_for(reader.readexactly(16), timeout=timeout)
  312. # Parse payload size from header (little-endian uint32 at offset 0)
  313. payload_size = struct.unpack("<I", header[0:4])[0]
  314. if payload_size == 0 or payload_size > 10_000_000:
  315. logger.error("Chamber image: invalid payload size %s", payload_size)
  316. return None
  317. # Read the JPEG data
  318. jpeg_data = await asyncio.wait_for(
  319. reader.readexactly(payload_size),
  320. timeout=timeout,
  321. )
  322. return jpeg_data
  323. except asyncio.IncompleteReadError:
  324. logger.warning("Chamber image: connection closed by printer")
  325. return None
  326. except TimeoutError:
  327. logger.warning("Chamber image: read timeout")
  328. return None
  329. except Exception as e:
  330. logger.error("Chamber image: error reading frame: %s", e)
  331. return None
  332. async def capture_camera_frame(
  333. ip_address: str,
  334. access_code: str,
  335. model: str | None,
  336. output_path: Path,
  337. timeout: int = 30,
  338. ) -> bool:
  339. """Capture a single frame from the printer's camera stream and save to disk.
  340. Uses capture_camera_frame_bytes() internally for protocol selection,
  341. then writes the result to the specified output path.
  342. Args:
  343. ip_address: Printer IP address
  344. access_code: Printer access code
  345. model: Printer model (X1, H2D, P1, A1, etc.)
  346. output_path: Path where to save the captured image
  347. timeout: Timeout in seconds for the capture operation
  348. Returns:
  349. True if capture was successful, False otherwise
  350. """
  351. output_path.parent.mkdir(parents=True, exist_ok=True)
  352. jpeg_data = await capture_camera_frame_bytes(ip_address, access_code, model, timeout)
  353. if jpeg_data:
  354. try:
  355. with open(output_path, "wb") as f:
  356. f.write(jpeg_data)
  357. logger.info("Saved camera frame to: %s", output_path)
  358. return True
  359. except OSError as e:
  360. logger.error("Failed to write camera frame: %s", e)
  361. return False
  362. return False
  363. async def capture_camera_frame_bytes(
  364. ip_address: str,
  365. access_code: str,
  366. model: str | None,
  367. timeout: int = 15,
  368. ) -> bytes | None:
  369. """Capture a single frame and return as JPEG bytes (no disk write).
  370. Uses the same protocol selection as capture_camera_frame but returns
  371. bytes directly instead of writing to disk.
  372. Args:
  373. ip_address: Printer IP address
  374. access_code: Printer access code
  375. model: Printer model (X1, H2D, P1, A1, etc.)
  376. timeout: Timeout in seconds for the capture operation
  377. Returns:
  378. JPEG bytes if capture was successful, None otherwise
  379. """
  380. # Chamber image models: A1/P1 - returns bytes directly
  381. if is_chamber_image_model(model):
  382. logger.info("Capturing camera frame bytes from %s using chamber image protocol (model: %s)", ip_address, model)
  383. return await read_chamber_image_frame(ip_address, access_code, timeout=float(timeout))
  384. # RTSP models: X1/H2/P2 - use ffmpeg piping to stdout
  385. # TLS proxy avoids GnuTLS compatibility issues with some printer firmwares
  386. port = get_camera_port(model)
  387. proxy_port, proxy_server = await create_tls_proxy(ip_address, port)
  388. camera_url = f"rtsp://bblp:{access_code}@127.0.0.1:{proxy_port}/streaming/live/1"
  389. ffmpeg = get_ffmpeg_path()
  390. if not ffmpeg:
  391. proxy_server.close()
  392. await proxy_server.wait_closed()
  393. logger.error("ffmpeg not found for camera frame capture")
  394. return None
  395. cmd = [
  396. ffmpeg,
  397. "-y",
  398. "-rtsp_transport",
  399. "tcp",
  400. "-rtsp_flags",
  401. "prefer_tcp",
  402. "-i",
  403. camera_url,
  404. "-frames:v",
  405. "1",
  406. "-f",
  407. "image2pipe",
  408. "-vcodec",
  409. "mjpeg",
  410. "-q:v",
  411. "2",
  412. "-",
  413. ]
  414. logger.info("Capturing camera frame bytes from %s using RTSP (model: %s)", ip_address, model)
  415. try:
  416. process = await asyncio.create_subprocess_exec(
  417. *cmd,
  418. stdout=asyncio.subprocess.PIPE,
  419. stderr=asyncio.subprocess.PIPE,
  420. )
  421. try:
  422. stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
  423. except TimeoutError:
  424. process.kill()
  425. await process.wait()
  426. logger.error("Camera frame bytes capture timed out after %ss", timeout)
  427. return None
  428. if process.returncode == 0 and stdout and len(stdout) >= 100:
  429. logger.info("Successfully captured camera frame bytes: %s bytes", len(stdout))
  430. return stdout
  431. else:
  432. stderr_text = stderr.decode() if stderr else "Unknown error"
  433. logger.error("ffmpeg frame bytes capture failed (code %s): %s", process.returncode, stderr_text[:200])
  434. return None
  435. except FileNotFoundError:
  436. logger.error("ffmpeg not found for camera frame capture")
  437. return None
  438. except Exception as e:
  439. logger.exception("Camera frame bytes capture failed: %s", e)
  440. return None
  441. finally:
  442. proxy_server.close()
  443. await proxy_server.wait_closed()
  444. async def capture_finish_photo(
  445. printer_id: int,
  446. ip_address: str,
  447. access_code: str,
  448. model: str | None,
  449. archive_dir: Path,
  450. ) -> str | None:
  451. """Capture a finish photo and save it to the archive's photos folder.
  452. Args:
  453. printer_id: ID of the printer
  454. ip_address: Printer IP address
  455. access_code: Printer access code
  456. model: Printer model
  457. archive_dir: Directory of the archive (where the 3MF is stored)
  458. Returns:
  459. Filename of the captured photo, or None if capture failed
  460. """
  461. # Create photos subdirectory
  462. photos_dir = archive_dir / "photos"
  463. photos_dir.mkdir(parents=True, exist_ok=True)
  464. # Generate filename with timestamp
  465. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  466. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  467. output_path = photos_dir / filename
  468. success = await capture_camera_frame(
  469. ip_address=ip_address,
  470. access_code=access_code,
  471. model=model,
  472. output_path=output_path,
  473. timeout=30,
  474. )
  475. if success:
  476. logger.info("Finish photo saved: %s", filename)
  477. return filename
  478. else:
  479. logger.warning("Failed to capture finish photo for printer %s", printer_id)
  480. return None
  481. async def test_camera_connection(
  482. ip_address: str,
  483. access_code: str,
  484. model: str | None,
  485. ) -> dict:
  486. """Test if the camera stream is accessible.
  487. Returns dict with success status and any error message.
  488. """
  489. import tempfile
  490. fd, tmp_name = tempfile.mkstemp(suffix=".jpg")
  491. os.close(fd)
  492. test_path = Path(tmp_name)
  493. test_path.chmod(0o600)
  494. try:
  495. success = await capture_camera_frame(
  496. ip_address=ip_address,
  497. access_code=access_code,
  498. model=model,
  499. output_path=test_path,
  500. timeout=15,
  501. )
  502. if success:
  503. return {"success": True, "message": "Camera connection successful"}
  504. else:
  505. return {
  506. "success": False,
  507. "error": (
  508. "Failed to capture frame from camera. "
  509. "Ensure the printer is powered on, camera is enabled, and Developer Mode is active. "
  510. "If running in Docker, try 'network_mode: host' in docker-compose.yml."
  511. ),
  512. }
  513. finally:
  514. # Clean up test file
  515. if test_path.exists():
  516. test_path.unlink()