camera.py 37 KB

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