camera.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  1. """Camera streaming API endpoints for Bambu Lab printers."""
  2. import asyncio
  3. import logging
  4. from collections.abc import AsyncGenerator
  5. from fastapi import APIRouter, Depends, HTTPException, Request
  6. from fastapi.responses import Response, StreamingResponse
  7. from sqlalchemy import select
  8. from sqlalchemy.ext.asyncio import AsyncSession
  9. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  10. from backend.app.core.database import get_db
  11. from backend.app.core.permissions import Permission
  12. from backend.app.models.printer import Printer
  13. from backend.app.models.user import User
  14. from backend.app.services.camera import (
  15. capture_camera_frame,
  16. generate_chamber_image_stream,
  17. get_camera_port,
  18. get_ffmpeg_path,
  19. is_chamber_image_model,
  20. read_next_chamber_frame,
  21. test_camera_connection,
  22. )
  23. logger = logging.getLogger(__name__)
  24. router = APIRouter(prefix="/printers", tags=["camera"])
  25. # Track active ffmpeg processes for cleanup
  26. _active_streams: dict[str, asyncio.subprocess.Process] = {}
  27. # Track active chamber image connections for cleanup
  28. _active_chamber_streams: dict[str, tuple] = {}
  29. # Store last frame for each printer (for photo capture from active stream)
  30. _last_frames: dict[int, bytes] = {}
  31. # Track last frame timestamp for each printer (for stall detection)
  32. _last_frame_times: dict[int, float] = {}
  33. # Track stream start times for each printer
  34. _stream_start_times: dict[int, float] = {}
  35. # Track active external camera streams by printer ID
  36. _active_external_streams: set[int] = set()
  37. # Track ALL spawned ffmpeg PIDs (persists even if _active_streams entries are removed)
  38. # Maps PID -> spawn timestamp — used by cleanup to find truly orphaned OS processes
  39. _spawned_ffmpeg_pids: dict[int, float] = {}
  40. def get_buffered_frame(printer_id: int) -> bytes | None:
  41. """Get the last buffered frame for a printer from an active stream.
  42. Returns the JPEG frame data if available, or None if no active stream.
  43. """
  44. return _last_frames.get(printer_id)
  45. async def get_printer_or_404(printer_id: int, db: AsyncSession) -> Printer:
  46. """Get printer by ID or raise 404."""
  47. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  48. printer = result.scalar_one_or_none()
  49. if not printer:
  50. raise HTTPException(status_code=404, detail="Printer not found")
  51. return printer
  52. async def generate_chamber_mjpeg_stream(
  53. ip_address: str,
  54. access_code: str,
  55. model: str | None,
  56. fps: int = 5,
  57. stream_id: str | None = None,
  58. disconnect_event: asyncio.Event | None = None,
  59. printer_id: int | None = None,
  60. ) -> AsyncGenerator[bytes, None]:
  61. """Generate MJPEG stream from A1/P1 printer using chamber image protocol.
  62. This connects to port 6000 and reads JPEG frames using the Bambu binary protocol.
  63. """
  64. logger.info("Starting chamber image stream for %s (stream_id=%s, model=%s)", ip_address, stream_id, model)
  65. connection = await generate_chamber_image_stream(ip_address, access_code, fps)
  66. if connection is None:
  67. logger.error("Failed to connect to chamber image stream for %s", ip_address)
  68. yield (
  69. b"--frame\r\n"
  70. b"Content-Type: text/plain\r\n\r\n"
  71. b"Error: Camera connection failed. Check printer is on and camera is enabled.\r\n"
  72. )
  73. return
  74. reader, writer = connection
  75. # Track active connection for cleanup
  76. if stream_id:
  77. _active_chamber_streams[stream_id] = (reader, writer)
  78. try:
  79. frame_interval = 1.0 / fps if fps > 0 else 0.2
  80. last_frame_time = 0.0
  81. while True:
  82. # Check if client disconnected
  83. if disconnect_event and disconnect_event.is_set():
  84. logger.info("Client disconnected, stopping chamber stream %s", stream_id)
  85. break
  86. # Read next frame
  87. frame = await read_next_chamber_frame(reader, timeout=30.0)
  88. if frame is None:
  89. logger.warning("Chamber image stream ended for %s", stream_id)
  90. break
  91. # Save frame to buffer for photo capture and track timestamp
  92. if printer_id is not None:
  93. import time
  94. _last_frames[printer_id] = frame
  95. _last_frame_times[printer_id] = time.time()
  96. # Rate limiting - skip frames if needed to maintain target FPS
  97. current_time = asyncio.get_event_loop().time()
  98. if current_time - last_frame_time < frame_interval:
  99. continue
  100. last_frame_time = current_time
  101. # Yield frame in MJPEG format
  102. yield (
  103. b"--frame\r\n"
  104. b"Content-Type: image/jpeg\r\n"
  105. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  106. b"\r\n" + frame + b"\r\n"
  107. )
  108. except asyncio.CancelledError:
  109. logger.info("Chamber image stream cancelled (stream_id=%s)", stream_id)
  110. except GeneratorExit:
  111. logger.info("Chamber image stream generator exit (stream_id=%s)", stream_id)
  112. except Exception as e:
  113. logger.exception("Chamber image stream error: %s", e)
  114. finally:
  115. # Remove from active streams
  116. if stream_id and stream_id in _active_chamber_streams:
  117. del _active_chamber_streams[stream_id]
  118. # Clean up frame buffer and timestamps
  119. if printer_id is not None:
  120. _last_frames.pop(printer_id, None)
  121. _last_frame_times.pop(printer_id, None)
  122. _stream_start_times.pop(printer_id, None)
  123. # Close the connection
  124. try:
  125. writer.close()
  126. await writer.wait_closed()
  127. except OSError:
  128. pass # Connection already closed or broken; cleanup is best-effort
  129. logger.info("Chamber image stream stopped for %s (stream_id=%s)", ip_address, stream_id)
  130. async def generate_rtsp_mjpeg_stream(
  131. ip_address: str,
  132. access_code: str,
  133. model: str | None,
  134. fps: int = 10,
  135. stream_id: str | None = None,
  136. disconnect_event: asyncio.Event | None = None,
  137. printer_id: int | None = None,
  138. ) -> AsyncGenerator[bytes, None]:
  139. """Generate MJPEG stream from printer camera using ffmpeg/RTSP.
  140. This is for X1/H2/P2 models that support RTSP streaming.
  141. """
  142. ffmpeg = get_ffmpeg_path()
  143. if not ffmpeg:
  144. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  145. yield (b"--frame\r\nContent-Type: text/plain\r\n\r\nError: ffmpeg not installed\r\n")
  146. return
  147. port = get_camera_port(model)
  148. camera_url = f"rtsps://bblp:{access_code}@{ip_address}:{port}/streaming/live/1"
  149. # ffmpeg command to output MJPEG stream to stdout
  150. # -rtsp_transport tcp: Use TCP for reliability
  151. # -rtsp_flags prefer_tcp: Prefer TCP for RTSP
  152. # -timeout: Connection timeout in microseconds (30 seconds)
  153. # -buffer_size: Larger buffer for network jitter
  154. # -max_delay: Maximum demuxing delay
  155. # -f mjpeg: Output as MJPEG
  156. # -q:v 5: Quality (lower = better, 2-10 is good range)
  157. # -r: Output framerate
  158. cmd = [
  159. ffmpeg,
  160. "-rtsp_transport",
  161. "tcp",
  162. "-rtsp_flags",
  163. "prefer_tcp",
  164. "-timeout",
  165. "30000000", # 30 seconds in microseconds
  166. "-buffer_size",
  167. "1024000", # 1MB buffer
  168. "-max_delay",
  169. "500000", # 0.5 seconds max delay
  170. "-i",
  171. camera_url,
  172. "-f",
  173. "mjpeg",
  174. "-q:v",
  175. "5",
  176. "-r",
  177. str(fps),
  178. "-an", # No audio
  179. "-", # Output to stdout
  180. ]
  181. logger.info(
  182. "Starting RTSP camera stream for %s (stream_id=%s, model=%s, fps=%s)", ip_address, stream_id, model, fps
  183. )
  184. logger.debug("ffmpeg command: %s ... (url hidden)", ffmpeg)
  185. process = None
  186. try:
  187. process = await asyncio.create_subprocess_exec(
  188. *cmd,
  189. stdout=asyncio.subprocess.PIPE,
  190. stderr=asyncio.subprocess.PIPE,
  191. )
  192. # Track active process for cleanup
  193. if stream_id:
  194. _active_streams[stream_id] = process
  195. import time as _time
  196. _spawned_ffmpeg_pids[process.pid] = _time.time()
  197. # Give ffmpeg a moment to start and check for immediate failures
  198. await asyncio.sleep(0.5)
  199. if process.returncode is not None:
  200. stderr = await process.stderr.read()
  201. logger.error("ffmpeg failed immediately: %s", stderr.decode())
  202. yield (
  203. b"--frame\r\n"
  204. b"Content-Type: text/plain\r\n\r\n"
  205. b"Error: Camera connection failed. Check printer is on and camera is enabled.\r\n"
  206. )
  207. return
  208. # Read JPEG frames from ffmpeg output
  209. # JPEG images start with 0xFFD8 and end with 0xFFD9
  210. buffer = b""
  211. jpeg_start = b"\xff\xd8"
  212. jpeg_end = b"\xff\xd9"
  213. while True:
  214. # Check if client disconnected
  215. if disconnect_event and disconnect_event.is_set():
  216. logger.info("Client disconnected, stopping stream %s", stream_id)
  217. break
  218. try:
  219. # Read chunk from ffmpeg - use longer timeout for network hiccups
  220. chunk = await asyncio.wait_for(process.stdout.read(8192), timeout=30.0)
  221. if not chunk:
  222. logger.warning("Camera stream ended (no more data)")
  223. break
  224. buffer += chunk
  225. # Find complete JPEG frames in buffer
  226. while True:
  227. start_idx = buffer.find(jpeg_start)
  228. if start_idx == -1:
  229. # No start marker, clear buffer up to last 2 bytes
  230. buffer = buffer[-2:] if len(buffer) > 2 else buffer
  231. break
  232. # Trim anything before the start marker
  233. if start_idx > 0:
  234. buffer = buffer[start_idx:]
  235. end_idx = buffer.find(jpeg_end, 2) # Skip first 2 bytes
  236. if end_idx == -1:
  237. # No end marker yet, wait for more data
  238. break
  239. # Extract complete frame
  240. frame = buffer[: end_idx + 2]
  241. buffer = buffer[end_idx + 2 :]
  242. # Save frame to buffer for photo capture and track timestamp
  243. if printer_id is not None:
  244. import time
  245. _last_frames[printer_id] = frame
  246. _last_frame_times[printer_id] = time.time()
  247. # Yield frame in MJPEG format
  248. yield (
  249. b"--frame\r\n"
  250. b"Content-Type: image/jpeg\r\n"
  251. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  252. b"\r\n" + frame + b"\r\n"
  253. )
  254. except TimeoutError:
  255. logger.warning("Camera stream read timeout")
  256. break
  257. except asyncio.CancelledError:
  258. logger.info("Camera stream cancelled (stream_id=%s)", stream_id)
  259. break
  260. except GeneratorExit:
  261. logger.info("Camera stream generator exit (stream_id=%s)", stream_id)
  262. break
  263. except FileNotFoundError:
  264. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  265. yield (b"--frame\r\nContent-Type: text/plain\r\n\r\nError: ffmpeg not installed\r\n")
  266. except asyncio.CancelledError:
  267. logger.info("Camera stream task cancelled (stream_id=%s)", stream_id)
  268. except GeneratorExit:
  269. logger.info("Camera stream generator closed (stream_id=%s)", stream_id)
  270. except Exception as e:
  271. logger.exception("Camera stream error: %s", e)
  272. finally:
  273. # Remove from active streams
  274. if stream_id and stream_id in _active_streams:
  275. del _active_streams[stream_id]
  276. # Clean up frame buffer and timestamps
  277. if printer_id is not None:
  278. _last_frames.pop(printer_id, None)
  279. _last_frame_times.pop(printer_id, None)
  280. _stream_start_times.pop(printer_id, None)
  281. if process and process.returncode is None:
  282. logger.info("Terminating ffmpeg process for stream %s", stream_id)
  283. try:
  284. process.terminate()
  285. try:
  286. await asyncio.wait_for(process.wait(), timeout=2.0)
  287. except TimeoutError:
  288. logger.warning("ffmpeg didn't terminate gracefully, killing (stream_id=%s)", stream_id)
  289. process.kill()
  290. await process.wait()
  291. except ProcessLookupError:
  292. pass # Process already dead
  293. except OSError as e:
  294. logger.warning("Error terminating ffmpeg: %s", e)
  295. logger.info("Camera stream stopped for %s (stream_id=%s)", ip_address, stream_id)
  296. # Remove from PID tracking now that process is confirmed dead
  297. if process:
  298. _spawned_ffmpeg_pids.pop(process.pid, None)
  299. @router.get("/{printer_id}/camera/stream")
  300. async def camera_stream(
  301. printer_id: int,
  302. request: Request,
  303. fps: int = 10,
  304. db: AsyncSession = Depends(get_db),
  305. ):
  306. """Stream live video from printer camera as MJPEG.
  307. This endpoint returns a multipart MJPEG stream that can be used directly
  308. in an <img> tag or video player.
  309. Note: Unauthenticated - loaded via <img> tags which can't send auth headers.
  310. Uses external camera if configured, otherwise uses built-in camera:
  311. - External: MJPEG, RTSP, or HTTP snapshot
  312. - A1/P1: Chamber image protocol (port 6000)
  313. - X1/H2/P2: RTSP via ffmpeg (port 322)
  314. Args:
  315. printer_id: Printer ID
  316. fps: Target frames per second (default: 10, max: 30)
  317. """
  318. import uuid
  319. printer = await get_printer_or_404(printer_id, db)
  320. # Check for external camera first
  321. if printer.external_camera_enabled and printer.external_camera_url:
  322. import time
  323. from backend.app.services.external_camera import generate_mjpeg_stream
  324. # Limit external camera FPS to reduce browser load
  325. fps = min(max(fps, 1), 15)
  326. logger.info(
  327. "Using external camera (%s) for printer %s at %s fps", printer.external_camera_type, printer_id, fps
  328. )
  329. # Track stream start
  330. _stream_start_times[printer_id] = time.time()
  331. _active_external_streams.add(printer_id)
  332. async def external_stream_wrapper():
  333. """Wrap external stream to track start/stop and update frame times."""
  334. frame_interval = 1.0 / fps
  335. last_yield_time = 0.0
  336. try:
  337. async for frame in generate_mjpeg_stream(
  338. printer.external_camera_url, printer.external_camera_type, fps
  339. ):
  340. # Rate limit to prevent overwhelming browser
  341. current_time = time.time()
  342. elapsed = current_time - last_yield_time
  343. if elapsed < frame_interval:
  344. await asyncio.sleep(frame_interval - elapsed)
  345. last_yield_time = time.time()
  346. _last_frame_times[printer_id] = last_yield_time
  347. yield frame
  348. finally:
  349. _active_external_streams.discard(printer_id)
  350. logger.info("External camera stream ended for printer %s", printer_id)
  351. return StreamingResponse(
  352. external_stream_wrapper(),
  353. media_type="multipart/x-mixed-replace; boundary=frame",
  354. headers={
  355. "Cache-Control": "no-cache, no-store, must-revalidate",
  356. "Pragma": "no-cache",
  357. "Expires": "0",
  358. },
  359. )
  360. # Validate FPS - A1/P1 models max out at ~5 FPS
  361. if is_chamber_image_model(printer.model):
  362. fps = min(max(fps, 1), 5)
  363. else:
  364. fps = min(max(fps, 1), 30)
  365. # Generate unique stream ID for tracking
  366. stream_id = f"{printer_id}-{uuid.uuid4().hex[:8]}"
  367. # Create disconnect event that will be set when client disconnects
  368. disconnect_event = asyncio.Event()
  369. # Choose the appropriate stream generator based on model
  370. if is_chamber_image_model(printer.model):
  371. stream_generator = generate_chamber_mjpeg_stream
  372. logger.info("Using chamber image protocol for %s", printer.model)
  373. else:
  374. stream_generator = generate_rtsp_mjpeg_stream
  375. logger.info("Using RTSP protocol for %s", printer.model)
  376. # Track stream start time
  377. import time
  378. _stream_start_times[printer_id] = time.time()
  379. async def _kill_stream_process(sid: str):
  380. """Terminate+kill the ffmpeg process for a stream ID."""
  381. proc = _active_streams.get(sid)
  382. if proc and proc.returncode is None:
  383. try:
  384. proc.terminate()
  385. try:
  386. await asyncio.wait_for(proc.wait(), timeout=2.0)
  387. except TimeoutError:
  388. proc.kill()
  389. await proc.wait()
  390. except (ProcessLookupError, OSError):
  391. pass
  392. async def _monitor_disconnect():
  393. """Background task: poll for client disconnect independently of frame loop."""
  394. try:
  395. while not disconnect_event.is_set():
  396. await asyncio.sleep(2)
  397. if await request.is_disconnected():
  398. logger.info("Disconnect monitor: client gone (stream %s)", stream_id)
  399. disconnect_event.set()
  400. # Kill ffmpeg process (RTSP streams)
  401. await _kill_stream_process(stream_id)
  402. # Close chamber stream connection if applicable
  403. chamber = _active_chamber_streams.get(stream_id)
  404. if chamber:
  405. try:
  406. chamber[1].close()
  407. except OSError:
  408. pass
  409. break
  410. except asyncio.CancelledError:
  411. pass
  412. monitor_task = asyncio.create_task(_monitor_disconnect())
  413. async def stream_with_disconnect_check():
  414. """Wrapper generator that monitors for client disconnect."""
  415. try:
  416. async for chunk in stream_generator(
  417. ip_address=printer.ip_address,
  418. access_code=printer.access_code,
  419. model=printer.model,
  420. fps=fps,
  421. stream_id=stream_id,
  422. disconnect_event=disconnect_event,
  423. printer_id=printer_id,
  424. ):
  425. # Check if client is still connected
  426. if disconnect_event.is_set() or await request.is_disconnected():
  427. logger.info("Client disconnected detected for stream %s", stream_id)
  428. disconnect_event.set()
  429. break
  430. yield chunk
  431. except asyncio.CancelledError:
  432. logger.info("Stream %s cancelled", stream_id)
  433. disconnect_event.set()
  434. except GeneratorExit:
  435. logger.info("Stream %s generator closed", stream_id)
  436. disconnect_event.set()
  437. finally:
  438. disconnect_event.set()
  439. monitor_task.cancel()
  440. # Give a moment for the inner generator to clean up
  441. await asyncio.sleep(0.1)
  442. return StreamingResponse(
  443. stream_with_disconnect_check(),
  444. media_type="multipart/x-mixed-replace; boundary=frame",
  445. headers={
  446. "Cache-Control": "no-cache, no-store, must-revalidate",
  447. "Pragma": "no-cache",
  448. "Expires": "0",
  449. },
  450. )
  451. @router.api_route("/{printer_id}/camera/stop", methods=["GET", "POST"])
  452. async def stop_camera_stream(
  453. printer_id: int,
  454. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  455. ):
  456. """Stop all active camera streams for a printer.
  457. This can be called by the frontend when the camera window is closed.
  458. Accepts both GET and POST (POST for sendBeacon compatibility).
  459. """
  460. stopped = 0
  461. # Stop ffmpeg/RTSP streams
  462. to_remove = []
  463. for stream_id, process in list(_active_streams.items()):
  464. if stream_id.startswith(f"{printer_id}-"):
  465. to_remove.append(stream_id)
  466. if process.returncode is None:
  467. try:
  468. process.terminate()
  469. try:
  470. await asyncio.wait_for(process.wait(), timeout=2.0)
  471. except TimeoutError:
  472. logger.warning("ffmpeg didn't terminate gracefully, killing (stream_id=%s)", stream_id)
  473. process.kill()
  474. await process.wait()
  475. stopped += 1
  476. logger.info("Terminated ffmpeg process for stream %s", stream_id)
  477. except ProcessLookupError:
  478. pass # Process already dead
  479. except OSError as e:
  480. logger.warning("Error stopping stream %s: %s", stream_id, e)
  481. _spawned_ffmpeg_pids.pop(process.pid, None)
  482. for stream_id in to_remove:
  483. _active_streams.pop(stream_id, None)
  484. # Stop chamber image streams
  485. to_remove_chamber = []
  486. for stream_id, (_reader, writer) in list(_active_chamber_streams.items()):
  487. if stream_id.startswith(f"{printer_id}-"):
  488. to_remove_chamber.append(stream_id)
  489. try:
  490. writer.close()
  491. stopped += 1
  492. logger.info("Closed chamber image connection for stream %s", stream_id)
  493. except OSError as e:
  494. logger.warning("Error stopping chamber stream %s: %s", stream_id, e)
  495. for stream_id in to_remove_chamber:
  496. _active_chamber_streams.pop(stream_id, None)
  497. logger.info("Stopped %s camera stream(s) for printer %s", stopped, printer_id)
  498. return {"stopped": stopped}
  499. @router.get("/{printer_id}/camera/snapshot")
  500. async def camera_snapshot(
  501. printer_id: int,
  502. db: AsyncSession = Depends(get_db),
  503. ):
  504. """Capture a single frame from the printer camera.
  505. Returns a JPEG image.
  506. Note: Unauthenticated - loaded via <img> tags which can't send auth headers.
  507. """
  508. import tempfile
  509. from pathlib import Path
  510. printer = await get_printer_or_404(printer_id, db)
  511. # Check for external camera first
  512. if printer.external_camera_enabled and printer.external_camera_url:
  513. from backend.app.services.external_camera import capture_frame
  514. frame_data = await capture_frame(printer.external_camera_url, printer.external_camera_type, timeout=15)
  515. if not frame_data:
  516. raise HTTPException(
  517. status_code=503,
  518. detail="Failed to capture frame from external camera.",
  519. )
  520. return Response(
  521. content=frame_data,
  522. media_type="image/jpeg",
  523. headers={
  524. "Cache-Control": "no-cache, no-store, must-revalidate",
  525. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  526. },
  527. )
  528. # Create temporary file for the snapshot
  529. with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f:
  530. temp_path = Path(f.name)
  531. try:
  532. success = await capture_camera_frame(
  533. ip_address=printer.ip_address,
  534. access_code=printer.access_code,
  535. model=printer.model,
  536. output_path=temp_path,
  537. timeout=15,
  538. )
  539. if not success:
  540. raise HTTPException(
  541. status_code=503,
  542. detail="Failed to capture camera frame. Ensure printer is on and camera is enabled.",
  543. )
  544. # Read and return the image
  545. with open(temp_path, "rb") as f:
  546. image_data = f.read()
  547. return Response(
  548. content=image_data,
  549. media_type="image/jpeg",
  550. headers={
  551. "Cache-Control": "no-cache, no-store, must-revalidate",
  552. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  553. },
  554. )
  555. finally:
  556. # Clean up temp file
  557. if temp_path.exists():
  558. temp_path.unlink()
  559. @router.get("/{printer_id}/camera/test")
  560. async def test_camera(
  561. printer_id: int,
  562. db: AsyncSession = Depends(get_db),
  563. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  564. ):
  565. """Test camera connection for a printer.
  566. Returns success status and any error message.
  567. """
  568. printer = await get_printer_or_404(printer_id, db)
  569. result = await test_camera_connection(
  570. ip_address=printer.ip_address,
  571. access_code=printer.access_code,
  572. model=printer.model,
  573. )
  574. return result
  575. @router.get("/{printer_id}/camera/status")
  576. async def camera_status(
  577. printer_id: int,
  578. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  579. ):
  580. """Get the status of an active camera stream.
  581. Returns whether a stream is active and when the last frame was received.
  582. Used by the frontend to detect stalled streams and auto-reconnect.
  583. """
  584. import time
  585. # Check if there's an active stream for this printer
  586. has_active_stream = False
  587. # Check external camera streams
  588. if printer_id in _active_external_streams:
  589. has_active_stream = True
  590. # Check ffmpeg/RTSP streams
  591. if not has_active_stream:
  592. for stream_id in _active_streams:
  593. if stream_id.startswith(f"{printer_id}-"):
  594. process = _active_streams[stream_id]
  595. if process.returncode is None:
  596. has_active_stream = True
  597. break
  598. # Check chamber image streams
  599. if not has_active_stream:
  600. for stream_id in _active_chamber_streams:
  601. if stream_id.startswith(f"{printer_id}-"):
  602. has_active_stream = True
  603. break
  604. # Get timing information
  605. current_time = time.time()
  606. last_frame_time = _last_frame_times.get(printer_id)
  607. stream_start_time = _stream_start_times.get(printer_id)
  608. # Calculate seconds since last frame
  609. seconds_since_frame = None
  610. if last_frame_time is not None:
  611. seconds_since_frame = current_time - last_frame_time
  612. # Calculate stream uptime
  613. stream_uptime = None
  614. if stream_start_time is not None:
  615. stream_uptime = current_time - stream_start_time
  616. return {
  617. "active": has_active_stream,
  618. "has_frames": printer_id in _last_frames,
  619. "seconds_since_frame": seconds_since_frame,
  620. "stream_uptime": stream_uptime,
  621. # Consider stalled if no frame for more than 10 seconds after stream started
  622. "stalled": (
  623. has_active_stream
  624. and stream_uptime is not None
  625. and stream_uptime > 5 # Give 5 seconds for stream to start
  626. and (seconds_since_frame is None or seconds_since_frame > 10)
  627. ),
  628. }
  629. @router.post("/{printer_id}/camera/external/test")
  630. async def test_external_camera(
  631. printer_id: int,
  632. url: str,
  633. camera_type: str,
  634. db: AsyncSession = Depends(get_db),
  635. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  636. ):
  637. """Test external camera connection.
  638. Args:
  639. printer_id: Printer ID (for authorization)
  640. url: Camera URL or USB device path to test
  641. camera_type: Camera type ("mjpeg", "rtsp", "snapshot", "usb")
  642. Returns:
  643. Dict with {success: bool, error?: str, resolution?: str}
  644. """
  645. # Verify printer exists (for authorization)
  646. await get_printer_or_404(printer_id, db)
  647. from backend.app.services.external_camera import test_connection
  648. return await test_connection(url, camera_type)
  649. @router.get("/{printer_id}/camera/check-plate")
  650. async def check_plate_empty(
  651. printer_id: int,
  652. plate_type: str | None = None,
  653. use_external: bool = False,
  654. include_debug_image: bool = False,
  655. db: AsyncSession = Depends(get_db),
  656. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  657. ):
  658. """Check if the build plate is empty using camera vision.
  659. Uses calibration-based difference detection - compares current frame
  660. to a reference image of the empty plate.
  661. IMPORTANT: Chamber light must be ON for reliable detection.
  662. Args:
  663. printer_id: Printer ID
  664. plate_type: Type of build plate (e.g., "High Temp Plate") for calibration lookup
  665. use_external: If True, prefer external camera over built-in
  666. include_debug_image: If True, return URL to annotated debug image
  667. Returns:
  668. Dict with detection results:
  669. - is_empty: bool - Whether plate appears empty
  670. - confidence: float - Confidence level (0.0 to 1.0)
  671. - difference_percent: float - How different from calibration reference
  672. - message: str - Human-readable result message
  673. - needs_calibration: bool - True if calibration is required
  674. - light_warning: bool - True if chamber light is off
  675. """
  676. from backend.app.services.plate_detection import (
  677. check_plate_empty as do_check,
  678. is_plate_detection_available,
  679. )
  680. from backend.app.services.printer_manager import printer_manager
  681. # Check printer exists first (before OpenCV check)
  682. printer = await get_printer_or_404(printer_id, db)
  683. if not is_plate_detection_available():
  684. raise HTTPException(
  685. status_code=503,
  686. detail="Plate detection not available. Install opencv-python-headless to enable.",
  687. )
  688. # Check chamber light status
  689. light_warning = False
  690. state = printer_manager.get_status(printer_id)
  691. if state and not state.chamber_light:
  692. light_warning = True
  693. from backend.app.services.plate_detection import PlateDetector
  694. # Build ROI tuple from printer settings if available
  695. roi = None
  696. if all(
  697. [
  698. printer.plate_detection_roi_x is not None,
  699. printer.plate_detection_roi_y is not None,
  700. printer.plate_detection_roi_w is not None,
  701. printer.plate_detection_roi_h is not None,
  702. ]
  703. ):
  704. roi = (
  705. printer.plate_detection_roi_x,
  706. printer.plate_detection_roi_y,
  707. printer.plate_detection_roi_w,
  708. printer.plate_detection_roi_h,
  709. )
  710. result = await do_check(
  711. printer_id=printer.id,
  712. ip_address=printer.ip_address,
  713. access_code=printer.access_code,
  714. model=printer.model,
  715. plate_type=plate_type,
  716. include_debug_image=include_debug_image,
  717. external_camera_url=printer.external_camera_url if printer.external_camera_enabled else None,
  718. external_camera_type=printer.external_camera_type if printer.external_camera_enabled else None,
  719. use_external=use_external,
  720. roi=roi,
  721. )
  722. # Get reference count for the response
  723. detector = PlateDetector()
  724. ref_count = detector.get_calibration_count(printer.id)
  725. response = result.to_dict()
  726. response["light_warning"] = light_warning
  727. response["reference_count"] = ref_count
  728. response["max_references"] = detector.MAX_REFERENCES
  729. # Include current ROI in response
  730. if roi:
  731. response["roi"] = {"x": roi[0], "y": roi[1], "w": roi[2], "h": roi[3]}
  732. else:
  733. # Return default ROI
  734. response["roi"] = {"x": 0.15, "y": 0.35, "w": 0.70, "h": 0.55}
  735. # If debug image requested and available, encode as base64 data URL
  736. if include_debug_image and result.debug_image:
  737. import base64
  738. b64_image = base64.b64encode(result.debug_image).decode("utf-8")
  739. response["debug_image_url"] = f"data:image/jpeg;base64,{b64_image}"
  740. return response
  741. @router.post("/{printer_id}/camera/plate-detection/calibrate")
  742. async def calibrate_plate_detection(
  743. printer_id: int,
  744. label: str | None = None,
  745. use_external: bool = False,
  746. db: AsyncSession = Depends(get_db),
  747. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  748. ):
  749. """Calibrate plate detection by capturing a reference image of the empty plate.
  750. The plate MUST be empty when calling this endpoint. The captured image
  751. will be used as the reference for future detection comparisons.
  752. Supports up to 5 reference images per printer. When adding a 6th, the oldest
  753. is automatically removed.
  754. IMPORTANT: Chamber light should be ON for calibration.
  755. Args:
  756. printer_id: Printer ID
  757. label: Optional label for this reference (e.g., "High Temp Plate", "Wham Bam")
  758. use_external: If True, prefer external camera over built-in
  759. Returns:
  760. Dict with:
  761. - success: bool - Whether calibration succeeded
  762. - message: str - Status message
  763. - index: int - The reference slot used (0-4)
  764. """
  765. from backend.app.services.plate_detection import (
  766. calibrate_plate,
  767. is_plate_detection_available,
  768. )
  769. from backend.app.services.printer_manager import printer_manager
  770. # Check printer exists first (before OpenCV check)
  771. printer = await get_printer_or_404(printer_id, db)
  772. if not is_plate_detection_available():
  773. raise HTTPException(
  774. status_code=503,
  775. detail="Plate detection not available. Install opencv-python-headless to enable.",
  776. )
  777. # Check chamber light - warn but don't block
  778. state = printer_manager.get_status(printer_id)
  779. light_warning = state and not state.chamber_light
  780. success, message, index = await calibrate_plate(
  781. printer_id=printer.id,
  782. ip_address=printer.ip_address,
  783. access_code=printer.access_code,
  784. model=printer.model,
  785. label=label,
  786. external_camera_url=printer.external_camera_url if printer.external_camera_enabled else None,
  787. external_camera_type=printer.external_camera_type if printer.external_camera_enabled else None,
  788. use_external=use_external,
  789. )
  790. if light_warning and success:
  791. message += " (Warning: Chamber light was off)"
  792. return {"success": success, "message": message, "index": index}
  793. @router.delete("/{printer_id}/camera/plate-detection/calibrate")
  794. async def delete_plate_calibration(
  795. printer_id: int,
  796. plate_type: str | None = None,
  797. db: AsyncSession = Depends(get_db),
  798. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  799. ):
  800. """Delete the plate detection calibration for a printer and plate type.
  801. Args:
  802. printer_id: Printer ID
  803. plate_type: Type of build plate (if None, deletes legacy non-plate-specific calibration)
  804. Returns:
  805. Dict with:
  806. - success: bool - Whether deletion succeeded
  807. - message: str - Status message
  808. """
  809. from backend.app.services.plate_detection import (
  810. delete_calibration,
  811. is_plate_detection_available,
  812. )
  813. # Verify printer exists first (before OpenCV check)
  814. await get_printer_or_404(printer_id, db)
  815. if not is_plate_detection_available():
  816. raise HTTPException(
  817. status_code=503,
  818. detail="Plate detection not available. Install opencv-python-headless to enable.",
  819. )
  820. deleted = delete_calibration(printer_id, plate_type)
  821. plate_msg = f" for '{plate_type}'" if plate_type else ""
  822. return {
  823. "success": deleted,
  824. "message": f"Calibration deleted{plate_msg}" if deleted else f"No calibration found{plate_msg}",
  825. }
  826. @router.get("/{printer_id}/camera/plate-detection/status")
  827. async def get_plate_detection_status(
  828. printer_id: int,
  829. plate_type: str | None = None,
  830. db: AsyncSession = Depends(get_db),
  831. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  832. ):
  833. """Check plate detection status for a printer and plate type.
  834. Returns:
  835. Dict with:
  836. - available: bool - Whether OpenCV is installed
  837. - calibrated: bool - Whether printer has calibration for this plate type
  838. - plate_type: str - The plate type queried
  839. - chamber_light: bool - Whether chamber light is on
  840. - message: str - Status message
  841. """
  842. from backend.app.services.plate_detection import (
  843. get_calibration_status,
  844. is_plate_detection_available,
  845. )
  846. from backend.app.services.printer_manager import printer_manager
  847. # Verify printer exists first (before OpenCV check)
  848. await get_printer_or_404(printer_id, db)
  849. if not is_plate_detection_available():
  850. return {
  851. "available": False,
  852. "calibrated": False,
  853. "plate_type": plate_type,
  854. "chamber_light": False,
  855. "message": "OpenCV not installed",
  856. }
  857. # Get chamber light status
  858. state = printer_manager.get_status(printer_id)
  859. chamber_light = state.chamber_light if state else False
  860. status = get_calibration_status(printer_id, plate_type)
  861. status["chamber_light"] = chamber_light
  862. return status
  863. @router.get("/{printer_id}/camera/plate-detection/references")
  864. async def get_plate_references(
  865. printer_id: int,
  866. db: AsyncSession = Depends(get_db),
  867. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  868. ):
  869. """Get all calibration references for a printer with metadata.
  870. Returns list of references with index, label, timestamp, and thumbnail URL.
  871. """
  872. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  873. # Verify printer exists first (before OpenCV check)
  874. await get_printer_or_404(printer_id, db)
  875. if not is_plate_detection_available():
  876. raise HTTPException(503, "Plate detection not available")
  877. detector = PlateDetector()
  878. references = detector.get_references(printer_id)
  879. # Add thumbnail URLs
  880. for ref in references:
  881. ref["thumbnail_url"] = (
  882. f"/api/v1/printers/{printer_id}/camera/plate-detection/references/{ref['index']}/thumbnail"
  883. )
  884. return {
  885. "references": references,
  886. "max_references": detector.MAX_REFERENCES,
  887. }
  888. @router.get("/{printer_id}/camera/plate-detection/references/{index}/thumbnail")
  889. async def get_reference_thumbnail(
  890. printer_id: int,
  891. index: int,
  892. db: AsyncSession = Depends(get_db),
  893. ):
  894. """Get thumbnail image for a calibration reference.
  895. Note: Unauthenticated - loaded via <img> tags which can't send auth headers.
  896. """
  897. from fastapi.responses import Response
  898. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  899. # Verify printer exists first (before OpenCV check)
  900. await get_printer_or_404(printer_id, db)
  901. if not is_plate_detection_available():
  902. raise HTTPException(503, "Plate detection not available")
  903. detector = PlateDetector()
  904. thumbnail = detector.get_reference_thumbnail(printer_id, index)
  905. if thumbnail is None:
  906. raise HTTPException(404, "Reference not found")
  907. return Response(content=thumbnail, media_type="image/jpeg")
  908. @router.put("/{printer_id}/camera/plate-detection/references/{index}")
  909. async def update_reference_label(
  910. printer_id: int,
  911. index: int,
  912. label: str,
  913. db: AsyncSession = Depends(get_db),
  914. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  915. ):
  916. """Update the label for a calibration reference."""
  917. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  918. # Verify printer exists first (before OpenCV check)
  919. await get_printer_or_404(printer_id, db)
  920. if not is_plate_detection_available():
  921. raise HTTPException(503, "Plate detection not available")
  922. detector = PlateDetector()
  923. success = detector.update_reference_label(printer_id, index, label)
  924. if not success:
  925. raise HTTPException(404, "Reference not found")
  926. return {"success": True, "index": index, "label": label}
  927. @router.delete("/{printer_id}/camera/plate-detection/references/{index}")
  928. async def delete_reference(
  929. printer_id: int,
  930. index: int,
  931. db: AsyncSession = Depends(get_db),
  932. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  933. ):
  934. """Delete a specific calibration reference."""
  935. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  936. # Verify printer exists first (before OpenCV check)
  937. await get_printer_or_404(printer_id, db)
  938. if not is_plate_detection_available():
  939. raise HTTPException(503, "Plate detection not available")
  940. detector = PlateDetector()
  941. success = detector.delete_reference(printer_id, index)
  942. if not success:
  943. raise HTTPException(404, "Reference not found")
  944. return {"success": True, "message": "Reference deleted"}
  945. def _scan_bambu_ffmpeg_pids() -> list[int]:
  946. """Scan /proc for ffmpeg processes with Bambu RTSP URLs.
  947. These are definitely ours — no other software connects to rtsps://bblp:.
  948. This catches orphans that survive app restarts and are not in any tracking dict.
  949. """
  950. import os
  951. pids = []
  952. try:
  953. for entry in os.listdir("/proc"):
  954. if not entry.isdigit():
  955. continue
  956. try:
  957. with open(f"/proc/{entry}/cmdline", "rb") as f:
  958. cmdline = f.read()
  959. if b"ffmpeg" in cmdline and b"rtsps://bblp:" in cmdline:
  960. pids.append(int(entry))
  961. except (OSError, PermissionError, ValueError):
  962. continue
  963. except OSError:
  964. pass
  965. return pids
  966. async def cleanup_orphaned_streams():
  967. """Clean up orphaned ffmpeg processes and stale stream entries.
  968. Called periodically from the background task loop in main.py.
  969. Three-layer cleanup:
  970. 1. /proc scan — finds ALL Bambu ffmpeg processes on the system, even those
  971. from previous app sessions. This is the nuclear safety net.
  972. 2. _spawned_ffmpeg_pids — tracks PIDs spawned this session, catches orphans
  973. that were removed from _active_streams but not killed.
  974. 3. _active_streams — kills stale entries with no recent frames.
  975. """
  976. import os
  977. import signal
  978. import time
  979. cleaned = 0
  980. now = time.time()
  981. # Collect PIDs that are legitimately in-use (active stream, process alive)
  982. active_pids = {proc.pid for proc in _active_streams.values() if proc.returncode is None}
  983. # 1. /proc scan — catch ALL orphaned Bambu ffmpeg processes on the system.
  984. # Any ffmpeg with rtsps://bblp: that is NOT in an active stream is orphaned.
  985. for pid in _scan_bambu_ffmpeg_pids():
  986. if pid in active_pids:
  987. continue
  988. logger.info("Killing orphaned ffmpeg process found via /proc (pid=%d)", pid)
  989. try:
  990. os.kill(pid, signal.SIGKILL)
  991. except (ProcessLookupError, OSError):
  992. pass
  993. _spawned_ffmpeg_pids.pop(pid, None)
  994. cleaned += 1
  995. # 2. Clean up _spawned_ffmpeg_pids entries for dead processes
  996. for pid in list(_spawned_ffmpeg_pids):
  997. try:
  998. os.kill(pid, 0) # existence check
  999. except (ProcessLookupError, OSError):
  1000. _spawned_ffmpeg_pids.pop(pid, None)
  1001. # 3. Clean up _active_streams entries with dead processes
  1002. dead_streams = [sid for sid, proc in _active_streams.items() if proc.returncode is not None]
  1003. for sid in dead_streams:
  1004. proc = _active_streams.pop(sid, None)
  1005. if proc:
  1006. _spawned_ffmpeg_pids.pop(proc.pid, None)
  1007. cleaned += 1
  1008. # 4. Kill stale active streams (alive but no frames for >60s)
  1009. for sid, proc in list(_active_streams.items()):
  1010. if proc.returncode is not None:
  1011. continue
  1012. try:
  1013. printer_id = int(sid.split("-", 1)[0])
  1014. except (ValueError, IndexError):
  1015. continue
  1016. start_time = _stream_start_times.get(printer_id, now)
  1017. last_frame = _last_frame_times.get(printer_id, start_time)
  1018. if now - start_time > 120 and now - last_frame > 60:
  1019. logger.info("Killing stale ffmpeg stream %s (no frames for %.0fs)", sid, now - last_frame)
  1020. try:
  1021. proc.kill()
  1022. await proc.wait()
  1023. except (ProcessLookupError, OSError):
  1024. pass
  1025. _active_streams.pop(sid, None)
  1026. _spawned_ffmpeg_pids.pop(proc.pid, None)
  1027. cleaned += 1
  1028. # 4. Clean stale chamber stream entries
  1029. dead_chamber = [sid for sid, (_reader, writer) in _active_chamber_streams.items() if writer.is_closing()]
  1030. for sid in dead_chamber:
  1031. _active_chamber_streams.pop(sid, None)
  1032. cleaned += 1
  1033. if cleaned:
  1034. logger.info("Cleaned up %d orphaned camera stream(s)", cleaned)