import { useState, useEffect, useRef } from 'react' interface LiveCameraViewProps { cameraName: string } export function LiveCameraView({ cameraName }: LiveCameraViewProps) { const [isStreaming, setIsStreaming] = useState(false) const [error, setError] = useState(null) const [loading, setLoading] = useState(true) const imgRef = useRef(null) const API_BASE = import.meta.env.VITE_VISION_API_URL || 'http://localhost:8000' useEffect(() => { startStreaming() return () => stopStreaming() }, [cameraName]) const startStreaming = async () => { try { setLoading(true) setError(null) // Start the stream const response = await fetch(`${API_BASE}/cameras/${cameraName}/start-stream`, { method: 'POST' }) if (response.ok) { setIsStreaming(true) // Set the stream source with timestamp to prevent caching if (imgRef.current) { imgRef.current.src = `${API_BASE}/cameras/${cameraName}/stream?t=${Date.now()}` } } else { throw new Error(`Failed to start stream: ${response.statusText}`) } } catch (err) { const errorMessage = err instanceof Error ? err.message : 'Failed to start stream' setError(errorMessage) } finally { setLoading(false) } } const stopStreaming = async () => { try { if (isStreaming) { await fetch(`${API_BASE}/cameras/${cameraName}/stop-stream`, { method: 'POST' }) setIsStreaming(false) } } catch (err) { console.error('Error stopping stream:', err) } } const handleImageError = () => { setError('Failed to load camera stream') } const handleImageLoad = () => { setError(null) } if (loading) { return (

Starting camera stream...

) } if (error) { return (

Stream Error

{error}

) } return (
{/* Camera Label */}
{cameraName} - Live View
{/* Live Stream */} {`Live {/* Status Indicator */}
LIVE
) }