Enhance Docker Compose configuration and improve camera manager error handling

- Added container names for better identification of services in docker-compose.yml.
- Refactored CameraManager to include error handling during initialization of camera recorders and streamers, ensuring the system remains operational even if some components fail.
- Updated frontend components to support new MQTT Debug Panel functionality, enhancing monitoring capabilities.
This commit is contained in:
salirezav
2025-12-01 15:30:10 -05:00
parent 73849b40a8
commit b3a94d2d4f
14 changed files with 940 additions and 67 deletions

View File

@@ -75,18 +75,31 @@ class CameraManager:
self.logger.info("Starting camera manager...")
self.running = True
# Start camera monitor
if self.camera_monitor:
self.camera_monitor.start()
try:
# Start camera monitor
if self.camera_monitor:
self.camera_monitor.start()
# Initialize camera recorders
self._initialize_recorders()
# Initialize camera recorders
try:
self._initialize_recorders()
except Exception as e:
self.logger.error(f"Error initializing camera recorders: {e}", exc_info=True)
# Continue anyway - some cameras might still work
# Initialize camera streamers
self._initialize_streamers()
# Initialize camera streamers
try:
self._initialize_streamers()
except Exception as e:
self.logger.error(f"Error initializing camera streamers: {e}", exc_info=True)
# Continue anyway - streaming is optional
self.logger.info("Camera manager started successfully")
return True
self.logger.info("Camera manager started successfully")
return True
except Exception as e:
self.logger.error(f"Critical error starting camera manager: {e}", exc_info=True)
self.running = False
return False
def stop(self) -> None:
"""Stop the camera manager"""

View File

@@ -1,5 +1,6 @@
services:
api:
container_name: usda-vision-api
build:
context: ./camera-management-api
dockerfile: Dockerfile
@@ -45,6 +46,7 @@ services:
network_mode: host
web:
container_name: usda-vision-web
image: node:20-alpine
working_dir: /app
env_file:
@@ -66,6 +68,7 @@ services:
- "8080:8080"
video-remote:
container_name: usda-vision-video-remote
image: node:20-alpine
working_dir: /app
environment:
@@ -86,6 +89,7 @@ services:
- "3001:3001"
vision-system-remote:
container_name: usda-vision-vision-system-remote
image: node:20-alpine
working_dir: /app
environment:
@@ -105,6 +109,7 @@ services:
- "3002:3002"
scheduling-remote:
container_name: usda-vision-scheduling-remote
image: node:20-alpine
working_dir: /app
env_file:
@@ -125,6 +130,7 @@ services:
- "3003:3003"
media-api:
container_name: usda-vision-media-api
build:
context: ./media-api
dockerfile: Dockerfile
@@ -150,6 +156,7 @@ services:
# mem_reservation: 512m
mediamtx:
container_name: usda-vision-mediamtx
image: bluenviron/mediamtx:latest
volumes:
- ./mediamtx.yml:/mediamtx.yml:ro

View File

@@ -87,15 +87,15 @@ function App() {
}
}
// Check if current route is a camera live route
const isCameraLiveRoute = (route: string) => {
const cameraRoutePattern = /^\/camera(\d+)\/live$/
// Check if current route is a camera route (no authentication required)
const isCameraRoute = (route: string) => {
const cameraRoutePattern = /^\/camera(\d+)$/
return cameraRoutePattern.test(route)
}
// Extract camera number from route
const getCameraNumber = (route: string) => {
const match = route.match(/^\/camera(\d+)\/live$/)
const match = route.match(/^\/camera(\d+)$/)
return match ? `camera${match[1]}` : null
}
@@ -136,8 +136,8 @@ function App() {
)
}
// Handle camera live routes (no authentication required)
if (isCameraLiveRoute(currentRoute)) {
// Handle camera routes (no authentication required)
if (isCameraRoute(currentRoute)) {
const cameraNumber = getCameraNumber(currentRoute)
if (cameraNumber) {
return <CameraRoute cameraNumber={cameraNumber} />

View File

@@ -0,0 +1,530 @@
import { useState, useEffect, useRef } from 'react'
import { visionApi, type CameraStatus, type CameraConfig, type MqttEvent } from '../lib/visionApi'
interface CameraPageProps {
cameraName: string
}
export function CameraPage({ cameraName }: CameraPageProps) {
const [cameraStatus, setCameraStatus] = useState<CameraStatus | null>(null)
const [cameraConfig, setCameraConfig] = useState<CameraConfig | null>(null)
const [isStreaming, setIsStreaming] = useState(false)
const [streamStatus, setStreamStatus] = useState<'idle' | 'starting' | 'streaming' | 'stopping' | 'error'>('idle')
const [isRecording, setIsRecording] = useState(false)
const [mqttEvents, setMqttEvents] = useState<MqttEvent[]>([])
const [autoRecordingError, setAutoRecordingError] = useState<string | null>(null)
const [loading, setLoading] = useState(true)
const imgRef = useRef<HTMLImageElement>(null)
const statusIntervalRef = useRef<number | null>(null)
const mqttEventsIntervalRef = useRef<number | null>(null)
// Load initial data and auto-start stream
useEffect(() => {
loadCameraData()
// Auto-start stream when component loads
startStreaming()
return () => {
if (statusIntervalRef.current) {
clearInterval(statusIntervalRef.current)
}
if (mqttEventsIntervalRef.current) {
clearInterval(mqttEventsIntervalRef.current)
}
stopStreaming()
}
}, [cameraName])
// Poll camera status
useEffect(() => {
statusIntervalRef.current = window.setInterval(() => {
loadCameraStatus()
}, 2000) // Poll every 2 seconds
return () => {
if (statusIntervalRef.current) {
clearInterval(statusIntervalRef.current)
}
}
}, [cameraName])
// Poll MQTT events
useEffect(() => {
loadMqttEvents()
mqttEventsIntervalRef.current = window.setInterval(() => {
loadMqttEvents()
}, 3000) // Poll every 3 seconds
return () => {
if (mqttEventsIntervalRef.current) {
clearInterval(mqttEventsIntervalRef.current)
}
}
}, [cameraName, cameraConfig])
// Update image src when streaming state changes
useEffect(() => {
if (isStreaming && imgRef.current && streamStatus === 'streaming') {
// Set stream URL with timestamp to prevent caching
const streamUrl = `${visionApi.getStreamUrl(cameraName)}?t=${Date.now()}`
if (imgRef.current.src !== streamUrl) {
imgRef.current.src = streamUrl
}
} else if (!isStreaming && imgRef.current) {
imgRef.current.src = ''
}
}, [isStreaming, streamStatus, cameraName])
// Monitor auto-recording failures
useEffect(() => {
if (cameraStatus && cameraConfig) {
// Check if auto-recording is enabled
if (cameraStatus.auto_recording_enabled) {
// Check if there was a recent MQTT event that should have triggered recording
const recentMqttEvent = mqttEvents.find(event => {
// Check if this event is for the camera's machine topic and state is "on"
return (
event.machine_name === cameraConfig.machine_topic &&
event.normalized_state === 'on' &&
new Date(event.timestamp).getTime() > Date.now() - 60000 // Within last 60 seconds
)
})
// If there was a recent trigger event, check if recording actually started
if (recentMqttEvent) {
// If recording didn't start and there's an error, show the error
if (!cameraStatus.is_recording && cameraStatus.auto_recording_last_error) {
setAutoRecordingError(
`Auto-recording failed to start! MQTT trigger received (${cameraConfig.machine_topic} → ON) but recording did not start. Error: ${cameraStatus.auto_recording_last_error}`
)
} else if (!cameraStatus.is_recording && cameraStatus.auto_recording_failure_count > 0) {
// Even without last_error, if there are failures and no recording, show warning
setAutoRecordingError(
`Auto-recording failed to start! MQTT trigger received (${cameraConfig.machine_topic} → ON) but recording did not start after ${cameraStatus.auto_recording_failure_count} attempt(s).`
)
} else {
// Recording started successfully or no error yet
setAutoRecordingError(null)
}
} else {
// No recent trigger event, clear error
setAutoRecordingError(null)
}
} else {
// Auto-recording not enabled, clear error
setAutoRecordingError(null)
}
} else {
setAutoRecordingError(null)
}
}, [cameraStatus, mqttEvents, cameraConfig])
const loadCameraData = async () => {
try {
setLoading(true)
await Promise.all([loadCameraStatus(), loadCameraConfig()])
} catch (error) {
console.error('Error loading camera data:', error)
} finally {
setLoading(false)
}
}
const loadCameraStatus = async () => {
try {
const status = await visionApi.getCameraStatus(cameraName)
setCameraStatus(status)
setIsRecording(status.is_recording)
// Update stream status based on camera status
if (status.status === 'streaming' || status.status === 'available') {
if (!isStreaming) {
setIsStreaming(true)
setStreamStatus('streaming')
}
}
} catch (error) {
console.error('Error loading camera status:', error)
}
}
const loadCameraConfig = async () => {
try {
const config = await visionApi.getCameraConfig(cameraName)
setCameraConfig(config)
} catch (error) {
console.error('Error loading camera config:', error)
}
}
const loadMqttEvents = async () => {
try {
const response = await visionApi.getMqttEvents(20) // Get last 20 events
if (cameraConfig) {
// Filter events relevant to this camera's machine topic
const relevantEvents = response.events.filter(
event => event.machine_name === cameraConfig.machine_topic
)
setMqttEvents(relevantEvents)
} else {
// If config not loaded yet, show all events
setMqttEvents(response.events)
}
} catch (error) {
console.error('Error loading MQTT events:', error)
}
}
const startStreaming = async () => {
try {
setStreamStatus('starting')
const result = await visionApi.startStream(cameraName)
if (result.success) {
setIsStreaming(true)
setStreamStatus('streaming')
// The useEffect will handle setting the image src
} else {
setStreamStatus('error')
setIsStreaming(false)
throw new Error(result.message || 'Failed to start stream')
}
} catch (error) {
setStreamStatus('error')
setIsStreaming(false)
console.error('Error starting stream:', error)
}
}
const stopStreaming = async () => {
try {
setStreamStatus('stopping')
await visionApi.stopStream(cameraName)
setIsStreaming(false)
setStreamStatus('idle')
if (imgRef.current) {
imgRef.current.src = ''
}
} catch (error) {
console.error('Error stopping stream:', error)
setStreamStatus('error')
}
}
const startRecording = async () => {
try {
const result = await visionApi.startRecording(cameraName)
if (result.success) {
setIsRecording(true)
await loadCameraStatus() // Refresh status
} else {
throw new Error(result.message || 'Failed to start recording')
}
} catch (error) {
console.error('Error starting recording:', error)
alert(`Failed to start recording: ${error instanceof Error ? error.message : 'Unknown error'}`)
}
}
const stopRecording = async () => {
try {
const result = await visionApi.stopRecording(cameraName)
if (result.success) {
setIsRecording(false)
await loadCameraStatus() // Refresh status
} else {
throw new Error(result.message || 'Failed to stop recording')
}
} catch (error) {
console.error('Error stopping recording:', error)
alert(`Failed to stop recording: ${error instanceof Error ? error.message : 'Unknown error'}`)
}
}
const getHealthStatus = () => {
if (!cameraStatus) return { status: 'unknown', message: 'Loading...' }
if (cameraStatus.device_info) {
return { status: 'healthy', message: 'Initialized & Found on Network' }
} else if (cameraStatus.status === 'disconnected' || cameraStatus.status === 'error') {
return { status: 'error', message: cameraStatus.last_error || 'Not Found on Network' }
} else {
return { status: 'warning', message: 'Status Unknown' }
}
}
const getStreamStatusText = () => {
switch (streamStatus) {
case 'idle':
return 'Ready to Stream'
case 'starting':
return 'Starting...'
case 'streaming':
return 'Now Streaming'
case 'stopping':
return 'Stopping...'
case 'error':
return 'Error'
default:
return 'Unknown'
}
}
const formatTimestamp = (timestamp: string) => {
try {
const date = new Date(timestamp)
return date.toLocaleTimeString()
} catch {
return timestamp
}
}
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-900">
<div className="text-center text-white">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-white mx-auto"></div>
<p className="mt-4">Loading camera data...</p>
</div>
</div>
)
}
const healthStatus = getHealthStatus()
return (
<div className="min-h-screen bg-gray-900 flex">
{/* Left Side - Live Stream (3/5) */}
<div className="flex-[3] flex flex-col bg-black">
{/* Auto-recording Error Banner */}
{autoRecordingError && (
<div className="bg-red-600 text-white px-4 py-3 flex items-center justify-between animate-pulse">
<div className="flex items-center space-x-2">
<svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
</svg>
<span className="font-semibold">{autoRecordingError}</span>
</div>
<button
onClick={() => setAutoRecordingError(null)}
className="text-white hover:text-gray-200"
>
<svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
</svg>
</button>
</div>
)}
{/* Stream Container */}
<div className="flex-1 flex items-center justify-center relative">
{isStreaming && streamStatus === 'streaming' ? (
<img
ref={imgRef}
alt={`Live stream from ${cameraName}`}
className="max-w-full max-h-full object-contain"
src={`${visionApi.getStreamUrl(cameraName)}?t=${Date.now()}`}
onError={() => {
console.error('Stream image failed to load, retrying...')
// Retry loading the stream
if (imgRef.current) {
setTimeout(() => {
if (imgRef.current && isStreaming) {
imgRef.current.src = `${visionApi.getStreamUrl(cameraName)}?t=${Date.now()}`
}
}, 1000)
}
}}
onLoad={() => {
// Stream loaded successfully
console.log('Stream loaded successfully')
}}
/>
) : streamStatus === 'starting' ? (
<div className="text-center text-white">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-white mx-auto mb-4"></div>
<p className="text-lg">Starting stream...</p>
</div>
) : (
<div className="text-center text-gray-500">
<svg className="w-24 h-24 mx-auto mb-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
<p className="text-lg">Stream not active</p>
<p className="text-sm mt-2">Click "Start Stream" to begin</p>
</div>
)}
{/* Camera Label Overlay */}
<div className="absolute top-4 left-4 z-10">
<div className="bg-black bg-opacity-75 text-white px-3 py-1 rounded-md text-sm font-medium">
{cameraName} - Live View
</div>
</div>
{/* Stream Status Indicator */}
{isStreaming && (
<div className="absolute bottom-4 right-4 z-10">
<div className="flex items-center space-x-2 bg-black bg-opacity-75 text-white px-3 py-1 rounded-md">
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
<span className="text-sm">LIVE</span>
</div>
</div>
)}
</div>
</div>
{/* Right Side - Controls & Info (2/5) */}
<div className="flex-[2] bg-gray-800 text-white p-6 overflow-y-auto">
<h1 className="text-2xl font-bold mb-6">{cameraName.toUpperCase()}</h1>
{/* Health Status */}
<div className="mb-6">
<h2 className="text-lg font-semibold mb-2">Health Status</h2>
<div className={`p-3 rounded-md ${
healthStatus.status === 'healthy' ? 'bg-green-600' :
healthStatus.status === 'error' ? 'bg-red-600' :
'bg-yellow-600'
}`}>
<div className="flex items-center space-x-2">
<div className={`w-3 h-3 rounded-full ${
healthStatus.status === 'healthy' ? 'bg-green-200' :
healthStatus.status === 'error' ? 'bg-red-200' :
'bg-yellow-200'
}`}></div>
<span className="font-medium">{healthStatus.message}</span>
</div>
{cameraStatus?.device_info && (
<div className="mt-2 text-sm opacity-90">
<div>Model: {cameraStatus.device_info.model || 'N/A'}</div>
<div>Serial: {cameraStatus.device_info.serial_number || 'N/A'}</div>
</div>
)}
</div>
</div>
{/* Stream Controls */}
<div className="mb-6">
<h2 className="text-lg font-semibold mb-2">Stream Control</h2>
<div className="bg-gray-700 p-4 rounded-md">
<div className="mb-3">
<div className="text-sm text-gray-300 mb-1">Status:</div>
<div className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
streamStatus === 'streaming' ? 'bg-green-600 text-white' :
streamStatus === 'error' ? 'bg-red-600 text-white' :
'bg-gray-600 text-gray-200'
}`}>
{getStreamStatusText()}
</div>
</div>
<div className="flex space-x-2">
<button
onClick={isStreaming ? stopStreaming : startStreaming}
disabled={streamStatus === 'starting' || streamStatus === 'stopping'}
className={`flex-1 px-4 py-2 rounded-md font-medium transition-colors ${
isStreaming
? 'bg-red-600 hover:bg-red-700 disabled:bg-red-800'
: 'bg-blue-600 hover:bg-blue-700 disabled:bg-blue-800'
} disabled:opacity-50 disabled:cursor-not-allowed`}
>
{isStreaming ? 'Stop Stream' : 'Start Stream'}
</button>
</div>
</div>
</div>
{/* Recording Status */}
<div className="mb-6">
<h2 className="text-lg font-semibold mb-2">Recording Status</h2>
<div className="bg-gray-700 p-4 rounded-md">
<div className="mb-3">
<div className="text-sm text-gray-300 mb-1">Status:</div>
<div className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
isRecording ? 'bg-red-600 text-white' : 'bg-gray-600 text-gray-200'
}`}>
{isRecording ? 'Recording Now' : 'Not Recording'}
</div>
</div>
{isRecording && cameraStatus?.current_recording_file && (
<div className="text-sm text-gray-300 mb-2">
File: {cameraStatus.current_recording_file.split('/').pop()}
</div>
)}
<div className="flex space-x-2">
<button
onClick={isRecording ? stopRecording : startRecording}
className={`flex-1 px-4 py-2 rounded-md font-medium transition-colors ${
isRecording
? 'bg-red-600 hover:bg-red-700'
: 'bg-green-600 hover:bg-green-700'
}`}
>
{isRecording ? 'Stop Recording' : 'Start Recording'}
</button>
</div>
</div>
</div>
{/* MQTT Message Log */}
<div className="mb-6">
<h2 className="text-lg font-semibold mb-2">MQTT Message Log</h2>
<div className="bg-gray-700 rounded-md overflow-hidden">
<div className="max-h-64 overflow-y-auto p-2 space-y-2">
{mqttEvents.length === 0 ? (
<div className="text-center text-gray-400 py-4">
No MQTT messages received yet
</div>
) : (
mqttEvents.map((event, index) => (
<div
key={`${event.message_number}-${index}`}
className="bg-gray-800 p-2 rounded text-sm"
>
<div className="flex justify-between items-start mb-1">
<span className="font-medium text-blue-300">{event.machine_name}</span>
<span className="text-gray-400 text-xs">{formatTimestamp(event.timestamp)}</span>
</div>
<div className="text-gray-300">
<span className="text-gray-400">State: </span>
<span className={`font-medium ${
event.normalized_state === 'on' ? 'text-green-400' : 'text-red-400'
}`}>
{event.normalized_state.toUpperCase()}
</span>
</div>
<div className="text-xs text-gray-500 mt-1">
Topic: {event.topic}
</div>
</div>
))
)}
</div>
</div>
</div>
{/* Auto-Recording Info */}
{cameraStatus && cameraStatus.auto_recording_enabled && (
<div className="mb-6">
<h2 className="text-lg font-semibold mb-2">Auto-Recording</h2>
<div className="bg-gray-700 p-4 rounded-md">
<div className="text-sm text-gray-300">
<div className="mb-1">
<span className="text-green-400"> Enabled</span>
</div>
{cameraConfig && (
<div className="text-xs mt-2">
Machine Topic: <span className="font-mono">{cameraConfig.machine_topic}</span>
</div>
)}
{cameraStatus.auto_recording_failure_count > 0 && (
<div className="text-red-400 mt-2 text-xs">
Failures: {cameraStatus.auto_recording_failure_count}
</div>
)}
</div>
</div>
</div>
)}
</div>
</div>
)
}

View File

@@ -1,4 +1,4 @@
import { LiveCameraView } from './LiveCameraView'
import { CameraPage } from './CameraPage'
interface CameraRouteProps {
cameraNumber: string
@@ -17,7 +17,7 @@ export function CameraRoute({ cameraNumber }: CameraRouteProps) {
)
}
return <LiveCameraView cameraName={cameraNumber} />
return <CameraPage cameraName={cameraNumber} />
}

View File

@@ -0,0 +1,120 @@
import React, { useState } from 'react'
import { visionApi } from '../lib/visionApi'
interface MqttDebugPanelProps {
isOpen: boolean
onClose: () => void
}
export const MqttDebugPanel: React.FC<MqttDebugPanelProps> = ({ isOpen, onClose }) => {
const [loading, setLoading] = useState<string | null>(null)
const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null)
const publishMessage = async (topic: string, payload: string) => {
const action = `${topic.split('/').pop()}${payload}`
setLoading(action)
setMessage(null)
try {
const result = await visionApi.publishMqttMessage(topic, payload, 0, false)
if (result.success) {
setMessage({ type: 'success', text: `Published: ${action}` })
setTimeout(() => setMessage(null), 3000)
} else {
setMessage({ type: 'error', text: `Failed: ${result.message}` })
}
} catch (error: any) {
setMessage({ type: 'error', text: `Error: ${error.message || 'Failed to publish message'}` })
} finally {
setLoading(null)
}
}
if (!isOpen) return null
return (
<div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
<div className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
{/* Header */}
<div className="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
<h2 className="text-xl font-semibold text-gray-900">MQTT Debug Panel</h2>
<button
onClick={onClose}
className="text-gray-400 hover:text-gray-600 transition-colors"
>
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{/* Content */}
<div className="p-6 space-y-6">
{/* Message Status */}
{message && (
<div className={`p-3 rounded-md ${
message.type === 'success'
? 'bg-green-50 text-green-800 border border-green-200'
: 'bg-red-50 text-red-800 border border-red-200'
}`}>
{message.text}
</div>
)}
{/* Vibratory Conveyor Section */}
<div className="border border-gray-200 rounded-lg p-4">
<h3 className="text-lg font-medium text-gray-900 mb-4">Vibratory Conveyor</h3>
<p className="text-sm text-gray-600 mb-4">Topic: <code className="bg-gray-100 px-2 py-1 rounded">vision/vibratory_conveyor/state</code></p>
<div className="flex gap-3">
<button
onClick={() => publishMessage('vision/vibratory_conveyor/state', 'on')}
disabled={loading !== null}
className="flex-1 px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{loading === 'vibratory_conveyor → on' ? 'Publishing...' : 'Turn ON'}
</button>
<button
onClick={() => publishMessage('vision/vibratory_conveyor/state', 'off')}
disabled={loading !== null}
className="flex-1 px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{loading === 'vibratory_conveyor → off' ? 'Publishing...' : 'Turn OFF'}
</button>
</div>
</div>
{/* Blower Separator Section */}
<div className="border border-gray-200 rounded-lg p-4">
<h3 className="text-lg font-medium text-gray-900 mb-4">Blower Separator</h3>
<p className="text-sm text-gray-600 mb-4">Topic: <code className="bg-gray-100 px-2 py-1 rounded">vision/blower_separator/state</code></p>
<div className="flex gap-3">
<button
onClick={() => publishMessage('vision/blower_separator/state', 'on')}
disabled={loading !== null}
className="flex-1 px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{loading === 'blower_separator → on' ? 'Publishing...' : 'Turn ON'}
</button>
<button
onClick={() => publishMessage('vision/blower_separator/state', 'off')}
disabled={loading !== null}
className="flex-1 px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{loading === 'blower_separator → off' ? 'Publishing...' : 'Turn OFF'}
</button>
</div>
</div>
{/* Info */}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
<p className="text-sm text-blue-800">
<strong>Note:</strong> These buttons publish MQTT messages to test auto-recording.
Check the logs to see if cameras start/stop recording automatically.
</p>
</div>
</div>
</div>
</div>
)
}

View File

@@ -16,9 +16,10 @@ import {
import { useAuth } from '../hooks/useAuth'
import { CameraConfigModal } from './CameraConfigModal'
import { CameraPreviewModal } from './CameraPreviewModal'
import { MqttDebugPanel } from './MqttDebugPanel'
// Memoized components to prevent unnecessary re-renders
const SystemOverview = memo(({ systemStatus }: { systemStatus: SystemStatus }) => (
const SystemOverview = memo(({ systemStatus, onMqttDebugClick }: { systemStatus: SystemStatus, onMqttDebugClick?: () => void }) => (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div className="bg-white overflow-hidden shadow rounded-lg">
<div className="p-5">
@@ -38,7 +39,7 @@ const SystemOverview = memo(({ systemStatus }: { systemStatus: SystemStatus }) =
</div>
</div>
<div className="bg-white overflow-hidden shadow rounded-lg">
<div className="bg-white overflow-hidden shadow rounded-lg relative">
<div className="p-5">
<div className="flex items-center">
<div className="flex-shrink-0">
@@ -54,6 +55,17 @@ const SystemOverview = memo(({ systemStatus }: { systemStatus: SystemStatus }) =
</div>
</div>
</div>
{onMqttDebugClick && (
<button
onClick={onMqttDebugClick}
className="absolute top-2 right-2 text-gray-400 hover:text-purple-600 transition-colors p-1"
title="MQTT Debug Panel"
>
<svg className="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 20 20">
<path d="M10 2a1 1 0 011 1v1a1 1 0 11-2 0V3a1 1 0 011-1zm4 8a4 4 0 11-8 0 4 4 0 018 0zm-.464 4.95l.707.707a1 1 0 001.414-1.414l-.707-.707a1 1 0 00-1.414 1.414zm2.12-10.607a1 1 0 010 1.414l-.706.707a1 1 0 11-1.414-1.414l.707-.707a1 1 0 011.414 0zM17 11a1 1 0 100-2h-1a1 1 0 100 2h1zm-7 4a1 1 0 011 1v1a1 1 0 11-2 0v-1a1 1 0 011-1zM5.05 6.464A1 1 0 106.465 5.05l-.708-.707a1 1 0 00-1.414 1.414l.707.707zm1.414 8.486l-.707.707a1 1 0 01-1.414-1.414l.707-.707a1 1 0 011.414 1.414zM4 11a1 1 0 100-2H3a1 1 0 000 2h1z" fillRule="evenodd" clipRule="evenodd" />
</svg>
</button>
)}
</div>
<div className="bg-white overflow-hidden shadow rounded-lg">
@@ -499,6 +511,9 @@ export function VisionSystem() {
const [previewModalOpen, setPreviewModalOpen] = useState(false)
const [previewCamera, setPreviewCamera] = useState<string | null>(null)
// MQTT debug panel state
const [debugPanelOpen, setDebugPanelOpen] = useState(false)
const intervalRef = useRef<NodeJS.Timeout | null>(null)
const clearAutoRefresh = useCallback(() => {
@@ -837,7 +852,7 @@ export function VisionSystem() {
</div>
{/* System Overview */}
{systemStatus && <SystemOverview systemStatus={systemStatus} />}
{systemStatus && <SystemOverview systemStatus={systemStatus} onMqttDebugClick={() => setDebugPanelOpen(true)} />}
@@ -932,6 +947,10 @@ export function VisionSystem() {
setPreviewCamera(null)
}}
/>
<MqttDebugPanel
isOpen={debugPanelOpen}
onClose={() => setDebugPanelOpen(false)}
/>
)}
{/* Notification */}

View File

@@ -329,6 +329,13 @@ class VisionApiClient {
return this.request(`/mqtt/events?limit=${limit}`)
}
async publishMqttMessage(topic: string, payload: string, qos: number = 0, retain: boolean = false): Promise<{ success: boolean; message: string; topic: string; payload: string }> {
return this.request('/mqtt/publish', {
method: 'POST',
body: JSON.stringify({ topic, payload, qos, retain }),
})
}
// Camera endpoints
async getCameras(): Promise<Record<string, CameraStatus>> {
return this.request('/cameras')

View File

@@ -1 +1 @@
v2.54.11
v2.62.10

View File

@@ -114,6 +114,124 @@ CREATE POLICY "User roles are updatable by authenticated users" ON public.user_r
CREATE POLICY "User roles are deletable by authenticated users" ON public.user_roles
FOR DELETE USING (auth.role() = 'authenticated');
-- =============================================
-- 9. USER MANAGEMENT FUNCTIONS
-- =============================================
-- Function to create a new user with roles
CREATE OR REPLACE FUNCTION public.create_user_with_roles(
user_email TEXT,
role_names TEXT[],
temp_password TEXT
)
RETURNS JSON AS $$
DECLARE
new_user_id UUID;
encrypted_pwd TEXT;
role_name TEXT;
role_id_val UUID;
assigned_by_id UUID;
result JSON;
user_roles_array TEXT[];
BEGIN
-- Generate new user ID
new_user_id := uuid_generate_v4();
-- Encrypt the password
encrypted_pwd := crypt(temp_password, gen_salt('bf'));
-- Get the current user ID for assigned_by, but only if they have a profile
-- Otherwise, use the new user ID (which we'll create next)
SELECT id INTO assigned_by_id
FROM public.user_profiles
WHERE id = auth.uid();
-- If no valid assigned_by user found, use the new user ID (self-assigned)
IF assigned_by_id IS NULL THEN
assigned_by_id := new_user_id;
END IF;
-- Create user in auth.users
INSERT INTO auth.users (
instance_id,
id,
aud,
role,
email,
encrypted_password,
email_confirmed_at,
created_at,
updated_at,
confirmation_token,
email_change,
email_change_token_new,
recovery_token
) VALUES (
'00000000-0000-0000-0000-000000000000',
new_user_id,
'authenticated',
'authenticated',
user_email,
encrypted_pwd,
NOW(),
NOW(),
NOW(),
'',
'',
'',
''
);
-- Create user profile
INSERT INTO public.user_profiles (id, email, status)
VALUES (new_user_id, user_email, 'active');
-- Assign roles
user_roles_array := ARRAY[]::TEXT[];
FOREACH role_name IN ARRAY role_names
LOOP
-- Get role ID
SELECT id INTO role_id_val
FROM public.roles
WHERE name = role_name;
-- If role exists, assign it
IF role_id_val IS NOT NULL THEN
INSERT INTO public.user_roles (user_id, role_id, assigned_by)
VALUES (new_user_id, role_id_val, assigned_by_id)
ON CONFLICT (user_id, role_id) DO NOTHING;
-- Add to roles array for return value
user_roles_array := array_append(user_roles_array, role_name);
END IF;
END LOOP;
-- Return the result as JSON
result := json_build_object(
'user_id', new_user_id::TEXT,
'email', user_email,
'temp_password', temp_password,
'roles', user_roles_array,
'status', 'active'
);
RETURN result;
EXCEPTION
WHEN unique_violation THEN
RAISE EXCEPTION 'User with email % already exists', user_email;
WHEN OTHERS THEN
RAISE EXCEPTION 'Error creating user: %', SQLERRM;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Grant execute permission on the function
GRANT EXECUTE ON FUNCTION public.create_user_with_roles(TEXT, TEXT[], TEXT) TO authenticated;
-- Comment for documentation
COMMENT ON FUNCTION public.create_user_with_roles(TEXT, TEXT[], TEXT) IS
'Creates a new user in auth.users, creates a profile in user_profiles, and assigns the specified roles. Returns user information including user_id, email, temp_password, roles, and status.';

View File

@@ -507,6 +507,54 @@ AND r.name IN ('conductor', 'data recorder')
;
-- Create engr-ugaif user (Conductor, Analyst & Data Recorder)
INSERT INTO auth.users (
instance_id,
id,
aud,
role,
email,
encrypted_password,
email_confirmed_at,
created_at,
updated_at,
confirmation_token,
email_change,
email_change_token_new,
recovery_token
) VALUES (
'00000000-0000-0000-0000-000000000000',
uuid_generate_v4(),
'authenticated',
'authenticated',
'engr-ugaif@uga.edu',
crypt('1048lab&2021', gen_salt('bf')),
NOW(),
NOW(),
NOW(),
'',
'',
'',
''
);
INSERT INTO public.user_profiles (id, email, status)
SELECT id, email, 'active'
FROM auth.users
WHERE email = 'engr-ugaif@uga.edu'
;
INSERT INTO public.user_roles (user_id, role_id, assigned_by)
SELECT
up.id,
r.id,
(SELECT id FROM public.user_profiles WHERE email = 's.alireza.v@gmail.com')
FROM public.user_profiles up
CROSS JOIN public.roles r
WHERE up.email = 'engr-ugaif@uga.edu'
AND r.name IN ('conductor', 'analyst', 'data recorder')
;
-- =============================================
-- 4. CREATE MACHINE TYPES
-- =============================================

View File

@@ -13,13 +13,13 @@ import { MqttDebugPanel } from './components/MqttDebugPanel'
// Get WebSocket URL from environment or construct it
const getWebSocketUrl = () => {
const apiUrl = import.meta.env.VITE_VISION_API_URL || '/api'
// If it's a relative path, use relative WebSocket URL
if (apiUrl.startsWith('/')) {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
return `${protocol}//${window.location.host}${apiUrl.replace(/\/api$/, '')}/ws`
}
// Convert http(s):// to ws(s)://
const wsUrl = apiUrl.replace(/^http/, 'ws')
return `${wsUrl.replace(/\/api$/, '')}/ws`
@@ -33,7 +33,7 @@ export default function App() {
const [error, setError] = useState<string | null>(null)
const [lastUpdate, setLastUpdate] = useState<Date | null>(null)
const [notification, setNotification] = useState<{ type: 'success' | 'error', message: string } | null>(null)
// Modal states
const [previewModalOpen, setPreviewModalOpen] = useState(false)
const [previewCamera, setPreviewCamera] = useState<string | null>(null)
@@ -100,13 +100,13 @@ export default function App() {
is_recording: true,
},
}))
// Refresh recordings to get accurate count
visionApi.getRecordings().then(setRecordings).catch(console.error)
// Refresh system status to update counts
visionApi.getSystemStatus().then(setSystemStatus).catch(console.error)
setLastUpdate(new Date())
})
)
@@ -122,7 +122,7 @@ export default function App() {
is_recording: false,
},
}))
// Refresh recordings and system status
Promise.all([
visionApi.getRecordings(),
@@ -131,7 +131,7 @@ export default function App() {
setRecordings(recordingsData)
setSystemStatus(statusData)
}).catch(console.error)
setLastUpdate(new Date())
})
)
@@ -171,7 +171,7 @@ export default function App() {
if (result.success) {
setNotification({ type: 'success', message: `Recording started: ${result.filename}` })
// Immediately update state optimistically (UI updates instantly)
setCameras((prev) => ({
...prev,
@@ -181,7 +181,7 @@ export default function App() {
current_recording_file: result.filename,
},
}))
// Refresh camera status from API as backup (in case WebSocket is delayed)
setTimeout(() => {
visionApi.getCameras().then(setCameras).catch(console.error)
@@ -199,7 +199,7 @@ export default function App() {
const result = await visionApi.stopRecording(cameraName)
if (result.success) {
setNotification({ type: 'success', message: 'Recording stopped' })
// Immediately update state optimistically (UI updates instantly)
setCameras((prev) => ({
...prev,
@@ -209,7 +209,7 @@ export default function App() {
current_recording_file: null,
},
}))
// Refresh camera status from API as backup (in case WebSocket is delayed)
setTimeout(() => {
visionApi.getCameras().then(setCameras).catch(console.error)
@@ -241,7 +241,7 @@ export default function App() {
status: 'streaming',
},
}))
// Open camera stream in new window/tab
const streamUrl = visionApi.getStreamUrl(cameraName)
window.open(streamUrl, '_blank')
@@ -262,7 +262,7 @@ export default function App() {
try {
setNotification({ type: 'success', message: `Restarting camera ${cameraName}...` })
const result = await visionApi.reinitializeCamera(cameraName)
if (result.success) {
setNotification({ type: 'success', message: `Camera ${cameraName} restarted successfully` })
// Refresh camera status
@@ -283,7 +283,7 @@ export default function App() {
const result = await visionApi.stopStream(cameraName)
if (result.success) {
setNotification({ type: 'success', message: 'Streaming stopped' })
// Immediately update camera status (UI updates instantly)
setCameras((prev) => ({
...prev,
@@ -292,7 +292,7 @@ export default function App() {
status: 'available',
},
}))
// Refresh camera status from API as backup
setTimeout(() => {
visionApi.getCameras().then(setCameras).catch(console.error)
@@ -390,7 +390,10 @@ export default function App() {
{/* Status Widgets */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<SystemHealthWidget systemStatus={systemStatus} />
<MqttStatusWidget systemStatus={systemStatus} />
<MqttStatusWidget
systemStatus={systemStatus}
onDebugClick={() => setDebugPanelOpen(true)}
/>
<RecordingsCountWidget active={activeRecordings} total={totalRecordings} />
<CameraCountWidget cameraCount={cameraCount} machineCount={machineCount} />
</div>
@@ -426,11 +429,10 @@ export default function App() {
{/* Notification */}
{notification && (
<div
className={`fixed top-4 right-4 z-[999999] p-4 rounded-md shadow-lg ${
notification.type === 'success'
className={`fixed top-4 right-4 z-[999999] p-4 rounded-md shadow-lg ${notification.type === 'success'
? 'bg-green-50 border border-green-200 text-green-800'
: 'bg-red-50 border border-red-200 text-red-800'
}`}
}`}
>
<div className="flex items-center">
<div className="flex-shrink-0">
@@ -450,11 +452,10 @@ export default function App() {
<div className="ml-auto pl-3">
<button
onClick={() => setNotification(null)}
className={`inline-flex rounded-md p-1.5 focus:outline-none focus:ring-2 focus:ring-offset-2 ${
notification.type === 'success'
className={`inline-flex rounded-md p-1.5 focus:outline-none focus:ring-2 focus:ring-offset-2 ${notification.type === 'success'
? 'text-green-500 hover:bg-green-100 focus:ring-green-600'
: 'text-red-500 hover:bg-red-100 focus:ring-red-600'
}`}
}`}
>
<svg className="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
<path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
@@ -515,25 +516,13 @@ export default function App() {
setNotification({ type: 'error', message: error })
}}
/>
)}
{/* MQTT Debug Panel */}
<MqttDebugPanel
isOpen={debugPanelOpen}
onClose={() => setDebugPanelOpen(false)}
/>
{/* Debug Button - Bottom Right */}
<button
onClick={() => setDebugPanelOpen(true)}
className="fixed bottom-6 right-6 z-40 bg-purple-600 text-white px-4 py-2 rounded-lg shadow-lg hover:bg-purple-700 transition-colors flex items-center gap-2"
title="Open MQTT Debug Panel"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
Debug
</button>
</div>
)
}

View File

@@ -4,9 +4,10 @@ import { visionApi, type SystemStatus, type MqttEvent } from '../services/api'
interface MqttStatusWidgetProps {
systemStatus: SystemStatus | null
onDebugClick?: () => void
}
export const MqttStatusWidget: React.FC<MqttStatusWidgetProps> = ({ systemStatus }) => {
export const MqttStatusWidget: React.FC<MqttStatusWidgetProps> = ({ systemStatus, onDebugClick }) => {
const [lastEvent, setLastEvent] = useState<MqttEvent | null>(null)
const isConnected = systemStatus?.mqtt_connected ?? false
const lastMessage = systemStatus?.last_mqtt_message
@@ -44,14 +45,27 @@ export const MqttStatusWidget: React.FC<MqttStatusWidgetProps> = ({ systemStatus
: 'No messages'
return (
<StatusWidget
title="MQTT Status"
status={isConnected}
statusText={isConnected ? 'Connected' : 'Disconnected'}
subtitle={subtitle || undefined}
icon={
<div className={`w-3 h-3 rounded-full ${isConnected ? 'bg-green-500 animate-pulse' : 'bg-red-500'}`} />
}
/>
<div className="relative">
<StatusWidget
title="MQTT Status"
status={isConnected}
statusText={isConnected ? 'Connected' : 'Disconnected'}
subtitle={subtitle || undefined}
icon={
<div className={`w-3 h-3 rounded-full ${isConnected ? 'bg-green-500 animate-pulse' : 'bg-red-500'}`} />
}
/>
{onDebugClick && (
<button
onClick={onDebugClick}
className="absolute top-2 right-2 text-gray-400 hover:text-purple-600 transition-colors p-1"
title="MQTT Debug Panel"
>
<svg className="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 20 20">
<path d="M10 2a1 1 0 011 1v1a1 1 0 11-2 0V3a1 1 0 011-1zm4 8a4 4 0 11-8 0 4 4 0 018 0zm-.464 4.95l.707.707a1 1 0 001.414-1.414l-.707-.707a1 1 0 00-1.414 1.414zm2.12-10.607a1 1 0 010 1.414l-.706.707a1 1 0 11-1.414-1.414l.707-.707a1 1 0 011.414 0zM17 11a1 1 0 100-2h-1a1 1 0 100 2h1zm-7 4a1 1 0 011 1v1a1 1 0 11-2 0v-1a1 1 0 011-1zM5.05 6.464A1 1 0 106.465 5.05l-.708-.707a1 1 0 00-1.414 1.414l.707.707zm1.414 8.486l-.707.707a1 1 0 01-1.414-1.414l.707-.707a1 1 0 011.414 1.414zM4 11a1 1 0 100-2H3a1 1 0 000 2h1z" fillRule="evenodd" clipRule="evenodd" />
</svg>
</button>
)}
</div>
)
}

View File

@@ -27,6 +27,14 @@ export default defineConfig({
},
build: {
target: 'esnext',
rollupOptions: {
output: {
// Add hash to filenames for cache busting
entryFileNames: 'assets/[name]-[hash].js',
chunkFileNames: 'assets/[name]-[hash].js',
assetFileNames: 'assets/[name]-[hash].[ext]',
},
},
},
})