camera.py 20 KB

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