camera.py 21 KB

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