camera.py 20 KB

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