diff --git a/docker-compose.yml b/docker-compose.yml index dc70893..26c505d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -54,7 +54,7 @@ services: - TZ=America/New_York command: > sh -lc " - npm ci; + npm install; npm run dev -- --host 0.0.0.0 --port 8080 " # Ensure the web container can resolve host.docker.internal on Linux @@ -62,3 +62,21 @@ services: - "host.docker.internal:host-gateway" ports: - "8080:8080" + + video-remote: + image: node:20-alpine + working_dir: /app + environment: + - TZ=America/New_York + volumes: + - ./video-remote:/app + command: > + sh -lc " + npm install; + npm run build; + npx http-server dist -p 3001 --cors -c-1 + " + extra_hosts: + - "host.docker.internal:host-gateway" + ports: + - "3001:3001" diff --git a/management-dashboard-web-app/API Documentations/docs/AI_AGENT_VIDEO_INTEGRATION_GUIDE.md b/management-dashboard-web-app/API Documentations/docs/AI_AGENT_VIDEO_INTEGRATION_GUIDE.md deleted file mode 100755 index 8901049..0000000 --- a/management-dashboard-web-app/API Documentations/docs/AI_AGENT_VIDEO_INTEGRATION_GUIDE.md +++ /dev/null @@ -1,415 +0,0 @@ -# 🤖 AI Agent Video Integration Guide - -This guide provides comprehensive step-by-step instructions for AI agents and external systems to successfully integrate with the USDA Vision Camera System's video streaming functionality. - -## 🎯 Overview - -The USDA Vision Camera System provides a complete video streaming API that allows AI agents to: -- Browse and select videos from multiple cameras -- Stream videos with seeking capabilities -- Generate thumbnails for preview -- Access video metadata and technical information - -## 🔗 API Base Configuration - -### Connection Details -```bash -# Default API Base URL -API_BASE_URL="http://localhost:8000" - -# For remote access, replace with actual server IP/hostname -API_BASE_URL="http://192.168.1.100:8000" -``` - -### Authentication -**⚠️ IMPORTANT: No authentication is currently required.** -- All endpoints are publicly accessible -- No API keys or tokens needed -- CORS is enabled for web browser integration - -## 📋 Step-by-Step Integration Workflow - -### Step 1: Verify System Connectivity -```bash -# Test basic connectivity -curl -f "${API_BASE_URL}/health" || echo "❌ System not accessible" - -# Check system status -curl "${API_BASE_URL}/system/status" -``` - -**Expected Response:** -```json -{ - "status": "healthy", - "timestamp": "2025-08-05T10:30:00Z" -} -``` - -### Step 2: List Available Videos -```bash -# Get all videos with metadata -curl "${API_BASE_URL}/videos/?include_metadata=true&limit=50" - -# Filter by specific camera -curl "${API_BASE_URL}/videos/?camera_name=camera1&include_metadata=true" - -# Filter by date range -curl "${API_BASE_URL}/videos/?start_date=2025-08-04T00:00:00&end_date=2025-08-05T23:59:59" -``` - -**Response Structure:** -```json -{ - "videos": [ - { - "file_id": "camera1_auto_blower_separator_20250804_143022.mp4", - "camera_name": "camera1", - "filename": "camera1_auto_blower_separator_20250804_143022.mp4", - "file_size_bytes": 31457280, - "format": "mp4", - "status": "completed", - "created_at": "2025-08-04T14:30:22", - "start_time": "2025-08-04T14:30:22", - "end_time": "2025-08-04T14:32:22", - "machine_trigger": "blower_separator", - "is_streamable": true, - "needs_conversion": false, - "metadata": { - "duration_seconds": 120.5, - "width": 1920, - "height": 1080, - "fps": 30.0, - "codec": "mp4v", - "bitrate": 5000000, - "aspect_ratio": 1.777 - } - } - ], - "total_count": 1 -} -``` - -### Step 3: Select and Validate Video -```bash -# Get detailed video information -FILE_ID="camera1_auto_blower_separator_20250804_143022.mp4" -curl "${API_BASE_URL}/videos/${FILE_ID}" - -# Validate video is playable -curl -X POST "${API_BASE_URL}/videos/${FILE_ID}/validate" - -# Get streaming technical details -curl "${API_BASE_URL}/videos/${FILE_ID}/info" -``` - -### Step 4: Generate Video Thumbnail -```bash -# Generate thumbnail at 5 seconds, 320x240 resolution -curl "${API_BASE_URL}/videos/${FILE_ID}/thumbnail?timestamp=5.0&width=320&height=240" \ - --output "thumbnail_${FILE_ID}.jpg" - -# Generate multiple thumbnails for preview -for timestamp in 1 30 60 90; do - curl "${API_BASE_URL}/videos/${FILE_ID}/thumbnail?timestamp=${timestamp}&width=160&height=120" \ - --output "preview_${timestamp}s.jpg" -done -``` - -### Step 5: Stream Video Content -```bash -# Stream entire video -curl "${API_BASE_URL}/videos/${FILE_ID}/stream" --output "video.mp4" - -# Stream specific byte range (for seeking) -curl -H "Range: bytes=0-1048575" \ - "${API_BASE_URL}/videos/${FILE_ID}/stream" \ - --output "video_chunk.mp4" - -# Test range request support -curl -I -H "Range: bytes=0-1023" \ - "${API_BASE_URL}/videos/${FILE_ID}/stream" -``` - -## 🔧 Programming Language Examples - -### Python Integration -```python -import requests -import json -from typing import List, Dict, Optional - -class USDAVideoClient: - def __init__(self, base_url: str = "http://localhost:8000"): - self.base_url = base_url.rstrip('/') - self.session = requests.Session() - - def list_videos(self, camera_name: Optional[str] = None, - include_metadata: bool = True, limit: int = 50) -> Dict: - """List available videos with optional filtering.""" - params = { - 'include_metadata': include_metadata, - 'limit': limit - } - if camera_name: - params['camera_name'] = camera_name - - response = self.session.get(f"{self.base_url}/videos/", params=params) - response.raise_for_status() - return response.json() - - def get_video_info(self, file_id: str) -> Dict: - """Get detailed video information.""" - response = self.session.get(f"{self.base_url}/videos/{file_id}") - response.raise_for_status() - return response.json() - - def get_thumbnail(self, file_id: str, timestamp: float = 1.0, - width: int = 320, height: int = 240) -> bytes: - """Generate and download video thumbnail.""" - params = { - 'timestamp': timestamp, - 'width': width, - 'height': height - } - response = self.session.get( - f"{self.base_url}/videos/{file_id}/thumbnail", - params=params - ) - response.raise_for_status() - return response.content - - def stream_video_range(self, file_id: str, start_byte: int, - end_byte: int) -> bytes: - """Stream specific byte range of video.""" - headers = {'Range': f'bytes={start_byte}-{end_byte}'} - response = self.session.get( - f"{self.base_url}/videos/{file_id}/stream", - headers=headers - ) - response.raise_for_status() - return response.content - - def validate_video(self, file_id: str) -> bool: - """Validate that video is accessible and playable.""" - response = self.session.post(f"{self.base_url}/videos/{file_id}/validate") - response.raise_for_status() - return response.json().get('is_valid', False) - -# Usage example -client = USDAVideoClient("http://192.168.1.100:8000") - -# List videos from camera1 -videos = client.list_videos(camera_name="camera1") -print(f"Found {videos['total_count']} videos") - -# Select first video -if videos['videos']: - video = videos['videos'][0] - file_id = video['file_id'] - - # Validate video - if client.validate_video(file_id): - print(f"✅ Video {file_id} is valid") - - # Get thumbnail - thumbnail = client.get_thumbnail(file_id, timestamp=5.0) - with open(f"thumbnail_{file_id}.jpg", "wb") as f: - f.write(thumbnail) - - # Stream first 1MB - chunk = client.stream_video_range(file_id, 0, 1048575) - print(f"Downloaded {len(chunk)} bytes") -``` - -### JavaScript/Node.js Integration -```javascript -class USDAVideoClient { - constructor(baseUrl = 'http://localhost:8000') { - this.baseUrl = baseUrl.replace(/\/$/, ''); - } - - async listVideos(options = {}) { - const params = new URLSearchParams({ - include_metadata: options.includeMetadata || true, - limit: options.limit || 50 - }); - - if (options.cameraName) { - params.append('camera_name', options.cameraName); - } - - const response = await fetch(`${this.baseUrl}/videos/?${params}`); - if (!response.ok) throw new Error(`HTTP ${response.status}`); - return response.json(); - } - - async getVideoInfo(fileId) { - const response = await fetch(`${this.baseUrl}/videos/${fileId}`); - if (!response.ok) throw new Error(`HTTP ${response.status}`); - return response.json(); - } - - async getThumbnail(fileId, options = {}) { - const params = new URLSearchParams({ - timestamp: options.timestamp || 1.0, - width: options.width || 320, - height: options.height || 240 - }); - - const response = await fetch( - `${this.baseUrl}/videos/${fileId}/thumbnail?${params}` - ); - if (!response.ok) throw new Error(`HTTP ${response.status}`); - return response.blob(); - } - - async validateVideo(fileId) { - const response = await fetch( - `${this.baseUrl}/videos/${fileId}/validate`, - { method: 'POST' } - ); - if (!response.ok) throw new Error(`HTTP ${response.status}`); - const result = await response.json(); - return result.is_valid; - } - - getStreamUrl(fileId) { - return `${this.baseUrl}/videos/${fileId}/stream`; - } -} - -// Usage example -const client = new USDAVideoClient('http://192.168.1.100:8000'); - -async function integrateWithVideos() { - try { - // List videos - const videos = await client.listVideos({ cameraName: 'camera1' }); - console.log(`Found ${videos.total_count} videos`); - - if (videos.videos.length > 0) { - const video = videos.videos[0]; - const fileId = video.file_id; - - // Validate video - const isValid = await client.validateVideo(fileId); - if (isValid) { - console.log(`✅ Video ${fileId} is valid`); - - // Get thumbnail - const thumbnail = await client.getThumbnail(fileId, { - timestamp: 5.0, - width: 320, - height: 240 - }); - - // Create video element for playback - const videoElement = document.createElement('video'); - videoElement.controls = true; - videoElement.src = client.getStreamUrl(fileId); - document.body.appendChild(videoElement); - } - } - } catch (error) { - console.error('Integration error:', error); - } -} -``` - -## 🚨 Error Handling - -### Common HTTP Status Codes -```bash -# Success responses -200 # OK - Request successful -206 # Partial Content - Range request successful - -# Client error responses -400 # Bad Request - Invalid parameters -404 # Not Found - Video file doesn't exist -416 # Range Not Satisfiable - Invalid range request - -# Server error responses -500 # Internal Server Error - Failed to process video -503 # Service Unavailable - Video module not available -``` - -### Error Response Format -```json -{ - "detail": "Video camera1_recording_20250804_143022.avi not found" -} -``` - -### Robust Error Handling Example -```python -def safe_video_operation(client, file_id): - try: - # Validate video first - if not client.validate_video(file_id): - return {"error": "Video is not valid or accessible"} - - # Get video info - video_info = client.get_video_info(file_id) - - # Check if streamable - if not video_info.get('is_streamable', False): - return {"error": "Video is not streamable"} - - return {"success": True, "video_info": video_info} - - except requests.exceptions.HTTPError as e: - if e.response.status_code == 404: - return {"error": "Video not found"} - elif e.response.status_code == 416: - return {"error": "Invalid range request"} - else: - return {"error": f"HTTP error: {e.response.status_code}"} - except requests.exceptions.ConnectionError: - return {"error": "Cannot connect to video server"} - except Exception as e: - return {"error": f"Unexpected error: {str(e)}"} -``` - -## ✅ Integration Checklist - -### Pre-Integration -- [ ] Verify network connectivity to USDA Vision Camera System -- [ ] Test basic API endpoints (`/health`, `/system/status`) -- [ ] Understand video file naming conventions -- [ ] Plan error handling strategy - -### Video Selection -- [ ] Implement video listing with appropriate filters -- [ ] Add video validation before processing -- [ ] Handle pagination for large video collections -- [ ] Implement caching for video metadata - -### Video Playback -- [ ] Test video streaming with range requests -- [ ] Implement thumbnail generation for previews -- [ ] Add progress tracking for video playback -- [ ] Handle different video formats (MP4, AVI) - -### Error Handling -- [ ] Handle network connectivity issues -- [ ] Manage video not found scenarios -- [ ] Deal with invalid range requests -- [ ] Implement retry logic for transient failures - -### Performance -- [ ] Use range requests for efficient seeking -- [ ] Implement client-side caching where appropriate -- [ ] Monitor bandwidth usage for video streaming -- [ ] Consider thumbnail caching for better UX - -## 🎯 Next Steps - -1. **Test Integration**: Use the provided examples to test basic connectivity -2. **Implement Error Handling**: Add robust error handling for production use -3. **Optimize Performance**: Implement caching and efficient streaming -4. **Monitor Usage**: Track API usage and performance metrics -5. **Security Review**: Consider authentication if exposing externally - -This guide provides everything needed for successful integration with the USDA Vision Camera System's video streaming functionality. The system is designed to be simple and reliable for AI agents and external systems to consume video content efficiently. diff --git a/management-dashboard-web-app/API Documentations/docs/API_CHANGES_SUMMARY.md b/management-dashboard-web-app/API Documentations/docs/API_CHANGES_SUMMARY.md deleted file mode 100755 index d7af414..0000000 --- a/management-dashboard-web-app/API Documentations/docs/API_CHANGES_SUMMARY.md +++ /dev/null @@ -1,207 +0,0 @@ -# API Changes Summary: Camera Settings and Video Format Updates - -## Overview -This document tracks major API changes including camera settings enhancements and the MP4 video format update. - -## 🎥 Latest Update: MP4 Video Format (v2.1) -**Date**: August 2025 - -**Major Changes**: -- **Video Format**: Changed from AVI/XVID to MP4/MPEG-4 format -- **File Extensions**: New recordings use `.mp4` instead of `.avi` -- **File Size**: ~40% reduction in file sizes -- **Streaming**: Better web browser compatibility - -**New Configuration Fields**: -```json -{ - "video_format": "mp4", // File format: "mp4" or "avi" - "video_codec": "mp4v", // Video codec: "mp4v", "XVID", "MJPG" - "video_quality": 95 // Quality: 0-100 (higher = better) -} -``` - -**Frontend Impact**: -- ✅ Better streaming performance and browser support -- ✅ Smaller file sizes for faster transfers -- ✅ Universal HTML5 video player compatibility -- ✅ Backward compatible with existing AVI files - -**Documentation**: See [MP4 Format Update Guide](MP4_FORMAT_UPDATE.md) - ---- - -## Previous Changes: Camera Settings and Filename Handling - -Enhanced the `POST /cameras/{camera_name}/start-recording` API endpoint to accept optional camera settings (shutter speed/exposure, gain, and fps) and ensure all filenames have datetime prefixes. - -## Changes Made - -### 1. API Models (`usda_vision_system/api/models.py`) -- **Enhanced `StartRecordingRequest`** to include optional parameters: - - `exposure_ms: Optional[float]` - Exposure time in milliseconds - - `gain: Optional[float]` - Camera gain value - - `fps: Optional[float]` - Target frames per second - -### 2. Camera Recorder (`usda_vision_system/camera/recorder.py`) -- **Added `update_camera_settings()` method** to dynamically update camera settings: - - Updates exposure time using `mvsdk.CameraSetExposureTime()` - - Updates gain using `mvsdk.CameraSetAnalogGain()` - - Updates target FPS in camera configuration - - Logs all setting changes - - Returns boolean indicating success/failure - -### 3. Camera Manager (`usda_vision_system/camera/manager.py`) -- **Enhanced `manual_start_recording()` method** to accept new parameters: - - Added optional `exposure_ms`, `gain`, and `fps` parameters - - Calls `update_camera_settings()` if any settings are provided - - **Automatic datetime prefix**: Always prepends timestamp to filename - - If custom filename provided: `{timestamp}_{custom_filename}` - - If no filename provided: `{camera_name}_manual_{timestamp}.avi` - -### 4. API Server (`usda_vision_system/api/server.py`) -- **Updated start-recording endpoint** to: - - Pass new camera settings to camera manager - - Handle filename response with datetime prefix - - Maintain backward compatibility with existing requests - -### 5. API Tests (`api-tests.http`) -- **Added comprehensive test examples**: - - Basic recording (existing functionality) - - Recording with camera settings - - Recording with settings only (no filename) - - Different parameter combinations - -## Usage Examples - -### Basic Recording (unchanged) -```http -POST http://localhost:8000/cameras/camera1/start-recording -Content-Type: application/json - -{ - "camera_name": "camera1", - "filename": "test.avi" -} -``` -**Result**: File saved as `20241223_143022_test.avi` - -### Recording with Camera Settings -```http -POST http://localhost:8000/cameras/camera1/start-recording -Content-Type: application/json - -{ - "camera_name": "camera1", - "filename": "high_quality.avi", - "exposure_ms": 2.0, - "gain": 4.0, - "fps": 5.0 -} -``` -**Result**: -- Camera settings updated before recording -- File saved as `20241223_143022_high_quality.avi` - -### Maximum FPS Recording -```http -POST http://localhost:8000/cameras/camera1/start-recording -Content-Type: application/json - -{ - "camera_name": "camera1", - "filename": "max_speed.avi", - "exposure_ms": 0.1, - "gain": 1.0, - "fps": 0 -} -``` -**Result**: -- Camera captures at maximum possible speed (no delay between frames) -- Video file saved with 30 FPS metadata for proper playback -- Actual capture rate depends on camera hardware and exposure settings - -### Settings Only (no filename) -```http -POST http://localhost:8000/cameras/camera1/start-recording -Content-Type: application/json - -{ - "camera_name": "camera1", - "exposure_ms": 1.5, - "gain": 3.0, - "fps": 7.0 -} -``` -**Result**: -- Camera settings updated -- File saved as `camera1_manual_20241223_143022.avi` - -## Key Features - -### 1. **Backward Compatibility** -- All existing API calls continue to work unchanged -- New parameters are optional -- Default behavior preserved when no settings provided - -### 2. **Automatic Datetime Prefix** -- **ALL filenames now have datetime prefix** regardless of what's sent -- Format: `YYYYMMDD_HHMMSS_` (Atlanta timezone) -- Ensures unique filenames and chronological ordering - -### 3. **Dynamic Camera Settings** -- Settings can be changed per recording without restarting system -- Based on proven implementation from `old tests/camera_video_recorder.py` -- Proper error handling and logging - -### 4. **Maximum FPS Capture** -- **`fps: 0`** = Capture at maximum possible speed (no delay between frames) -- **`fps > 0`** = Capture at specified frame rate with controlled timing -- **`fps` omitted** = Uses camera config default (usually 3.0 fps) -- Video files saved with 30 FPS metadata when fps=0 for proper playback - -### 5. **Parameter Validation** -- Uses Pydantic models for automatic validation -- Optional parameters with proper type checking -- Descriptive field documentation - -## Testing - -Run the test script to verify functionality: -```bash -# Start the system first -python main.py - -# In another terminal, run tests -python test_api_changes.py -``` - -The test script verifies: -- Basic recording functionality -- Camera settings application -- Filename datetime prefix handling -- API response accuracy - -## Implementation Notes - -### Camera Settings Mapping -- **Exposure**: Converted from milliseconds to microseconds for SDK -- **Gain**: Converted to camera units (multiplied by 100) -- **FPS**: Stored in camera config, used by recording loop - -### Error Handling -- Settings update failures are logged but don't prevent recording -- Invalid camera names return appropriate HTTP errors -- Camera initialization failures are handled gracefully - -### Filename Generation -- Uses `format_filename_timestamp()` from timezone utilities -- Ensures Atlanta timezone consistency -- Handles both custom and auto-generated filenames - -## Similar to Old Implementation -The camera settings functionality mirrors the proven approach in `old tests/camera_video_recorder.py`: -- Same parameter names and ranges -- Same SDK function calls -- Same conversion factors -- Proven to work with the camera hardware diff --git a/management-dashboard-web-app/API Documentations/docs/API_DOCUMENTATION.md b/management-dashboard-web-app/API Documentations/docs/API_DOCUMENTATION.md deleted file mode 100755 index 81ac03f..0000000 --- a/management-dashboard-web-app/API Documentations/docs/API_DOCUMENTATION.md +++ /dev/null @@ -1,824 +0,0 @@ -# 🚀 USDA Vision Camera System - Complete API Documentation - -This document provides comprehensive documentation for all API endpoints in the USDA Vision Camera System, including recent enhancements and new features. - -## 📋 Table of Contents - -- [🔧 System Status & Health](#-system-status--health) -- [📷 Camera Management](#-camera-management) -- [🎥 Recording Control](#-recording-control) -- [🤖 Auto-Recording Management](#-auto-recording-management) -- [🎛️ Camera Configuration](#️-camera-configuration) -- [📡 MQTT & Machine Status](#-mqtt--machine-status) -- [💾 Storage & File Management](#-storage--file-management) -- [🔄 Camera Recovery & Diagnostics](#-camera-recovery--diagnostics) -- [📺 Live Streaming](#-live-streaming) -- [🎬 Video Streaming & Playback](#-video-streaming--playback) -- [🌐 WebSocket Real-time Updates](#-websocket-real-time-updates) - -## 🔧 System Status & Health - -### Get System Status -```http -GET /system/status -``` -**Response**: `SystemStatusResponse` -```json -{ - "system_started": true, - "mqtt_connected": true, - "last_mqtt_message": "2024-01-15T10:30:00Z", - "machines": { - "vibratory_conveyor": { - "name": "vibratory_conveyor", - "state": "ON", - "last_updated": "2024-01-15T10:30:00Z" - } - }, - "cameras": { - "camera1": { - "name": "camera1", - "status": "ACTIVE", - "is_recording": false, - "auto_recording_enabled": true - } - }, - "active_recordings": 0, - "total_recordings": 15, - "uptime_seconds": 3600.5 -} -``` - -### Health Check -```http -GET /health -``` -**Response**: Simple health status -```json -{ - "status": "healthy", - "timestamp": "2024-01-15T10:30:00Z" -} -``` - -## 📷 Camera Management - -### Get All Cameras -```http -GET /cameras -``` -**Response**: `Dict[str, CameraStatusResponse]` - -### Get Specific Camera Status -```http -GET /cameras/{camera_name}/status -``` -**Response**: `CameraStatusResponse` -```json -{ - "name": "camera1", - "status": "ACTIVE", - "is_recording": false, - "last_checked": "2024-01-15T10:30:00Z", - "last_error": null, - "device_info": { - "model": "GigE Camera", - "serial": "12345" - }, - "current_recording_file": null, - "recording_start_time": null, - "auto_recording_enabled": true, - "auto_recording_active": false, - "auto_recording_failure_count": 0, - "auto_recording_last_attempt": null, - "auto_recording_last_error": null -} -``` - -## 🎥 Recording Control - -### Start Recording -```http -POST /cameras/{camera_name}/start-recording -Content-Type: application/json - -{ - "filename": "test_recording.avi", - "exposure_ms": 2.0, - "gain": 4.0, - "fps": 5.0 -} -``` - -**Request Model**: `StartRecordingRequest` -- `filename` (optional): Custom filename (datetime prefix will be added automatically) -- `exposure_ms` (optional): Exposure time in milliseconds -- `gain` (optional): Camera gain value -- `fps` (optional): Target frames per second - -**Response**: `StartRecordingResponse` -```json -{ - "success": true, - "message": "Recording started for camera1", - "filename": "20240115_103000_test_recording.avi" -} -``` - -**Key Features**: -- ✅ **Automatic datetime prefix**: All filenames get `YYYYMMDD_HHMMSS_` prefix -- ✅ **Dynamic camera settings**: Adjust exposure, gain, and FPS per recording -- ✅ **Backward compatibility**: All existing API calls work unchanged - -### Stop Recording -```http -POST /cameras/{camera_name}/stop-recording -``` -**Response**: `StopRecordingResponse` -```json -{ - "success": true, - "message": "Recording stopped for camera1", - "duration_seconds": 45.2 -} -``` - -## 🤖 Auto-Recording Management - -### Enable Auto-Recording for Camera -```http -POST /cameras/{camera_name}/auto-recording/enable -``` -**Response**: `AutoRecordingConfigResponse` -```json -{ - "success": true, - "message": "Auto-recording enabled for camera1", - "camera_name": "camera1", - "enabled": true -} -``` - -### Disable Auto-Recording for Camera -```http -POST /cameras/{camera_name}/auto-recording/disable -``` -**Response**: `AutoRecordingConfigResponse` - -### Get Auto-Recording Status -```http -GET /auto-recording/status -``` -**Response**: `AutoRecordingStatusResponse` -```json -{ - "running": true, - "auto_recording_enabled": true, - "retry_queue": {}, - "enabled_cameras": ["camera1", "camera2"] -} -``` - -**Auto-Recording Features**: -- 🤖 **MQTT-triggered recording**: Automatically starts/stops based on machine state -- 🔄 **Retry logic**: Failed recordings are retried with configurable delays -- 📊 **Per-camera control**: Enable/disable auto-recording individually -- 📈 **Status tracking**: Monitor failure counts and last attempts - -## 🎛️ Camera Configuration - -### Get Camera Configuration -```http -GET /cameras/{camera_name}/config -``` -**Response**: `CameraConfigResponse` -```json -{ - "name": "camera1", - "machine_topic": "blower_separator", - "storage_path": "/storage/camera1", - "exposure_ms": 0.3, - "gain": 4.0, - "target_fps": 0, - "enabled": true, - "video_format": "mp4", - "video_codec": "mp4v", - "video_quality": 95, - "auto_start_recording_enabled": true, - "auto_recording_max_retries": 3, - "auto_recording_retry_delay_seconds": 2, - "contrast": 100, - "saturation": 100, - "gamma": 100, - "noise_filter_enabled": false, - "denoise_3d_enabled": false, - "auto_white_balance": false, - "color_temperature_preset": 0, - "wb_red_gain": 0.94, - "wb_green_gain": 1.0, - "wb_blue_gain": 0.87, - "anti_flicker_enabled": false, - "light_frequency": 0, - "bit_depth": 8, - "hdr_enabled": false, - "hdr_gain_mode": 2 -} -``` - -### Update Camera Configuration -```http -PUT /cameras/{camera_name}/config -Content-Type: application/json - -{ - "exposure_ms": 2.0, - "gain": 4.0, - "target_fps": 5.0, - "sharpness": 130 -} -``` - -### Apply Configuration (Restart Required) -```http -POST /cameras/{camera_name}/apply-config -``` - -**Configuration Categories**: -- ✅ **Real-time**: `exposure_ms`, `gain`, `target_fps`, `sharpness`, `contrast`, etc. -- ⚠️ **Restart required**: `noise_filter_enabled`, `denoise_3d_enabled`, `bit_depth`, `video_format`, `video_codec`, `video_quality` - -For detailed configuration options, see [Camera Configuration API Guide](api/CAMERA_CONFIG_API.md). - -## 📡 MQTT & Machine Status - -### Get All Machines -```http -GET /machines -``` -**Response**: `Dict[str, MachineStatusResponse]` - -### Get MQTT Status -```http -GET /mqtt/status -``` -**Response**: `MQTTStatusResponse` -```json -{ - "connected": true, - "broker_host": "192.168.1.110", - "broker_port": 1883, - "subscribed_topics": ["vibratory_conveyor", "blower_separator"], - "last_message_time": "2024-01-15T10:30:00Z", - "message_count": 1250, - "error_count": 2, - "uptime_seconds": 3600.5 -} -``` - -### Get MQTT Events History -```http -GET /mqtt/events?limit=10 -``` -**Response**: `MQTTEventsHistoryResponse` -```json -{ - "events": [ - { - "machine_name": "vibratory_conveyor", - "topic": "vibratory_conveyor", - "payload": "ON", - "normalized_state": "ON", - "timestamp": "2024-01-15T10:30:00Z", - "message_number": 1250 - } - ], - "total_events": 1250, - "last_updated": "2024-01-15T10:30:00Z" -} -``` - -## 💾 Storage & File Management - -### Get Storage Statistics -```http -GET /storage/stats -``` -**Response**: `StorageStatsResponse` -```json -{ - "base_path": "/storage", - "total_files": 150, - "total_size_bytes": 5368709120, - "cameras": { - "camera1": { - "file_count": 75, - "total_size_bytes": 2684354560 - }, - "camera2": { - "file_count": 75, - "total_size_bytes": 2684354560 - } - }, - "disk_usage": { - "total_bytes": 107374182400, - "used_bytes": 53687091200, - "free_bytes": 53687091200, - "usage_percent": 50.0 - } -} -``` - -### Get File List -```http -POST /storage/files -Content-Type: application/json - -{ - "camera_name": "camera1", - "start_date": "2024-01-15", - "end_date": "2024-01-16", - "limit": 50 -} -``` -**Response**: `FileListResponse` -```json -{ - "files": [ - { - "filename": "20240115_103000_test_recording.avi", - "camera_name": "camera1", - "size_bytes": 52428800, - "created_time": "2024-01-15T10:30:00Z", - "duration_seconds": 30.5 - } - ], - "total_count": 1 -} -``` - -### Cleanup Old Files -```http -POST /storage/cleanup -Content-Type: application/json - -{ - "max_age_days": 30 -} -``` -**Response**: `CleanupResponse` -```json -{ - "files_removed": 25, - "bytes_freed": 1073741824, - "errors": [] -} -``` - -## 🔄 Camera Recovery & Diagnostics - -### Test Camera Connection -```http -POST /cameras/{camera_name}/test-connection -``` -**Response**: `CameraTestResponse` - -### Reconnect Camera -```http -POST /cameras/{camera_name}/reconnect -``` -**Response**: `CameraRecoveryResponse` - -### Restart Camera Grab Process -```http -POST /cameras/{camera_name}/restart-grab -``` -**Response**: `CameraRecoveryResponse` - -### Reset Camera Timestamp -```http -POST /cameras/{camera_name}/reset-timestamp -``` -**Response**: `CameraRecoveryResponse` - -### Full Camera Reset -```http -POST /cameras/{camera_name}/full-reset -``` -**Response**: `CameraRecoveryResponse` - -### Reinitialize Camera -```http -POST /cameras/{camera_name}/reinitialize -``` -**Response**: `CameraRecoveryResponse` - -**Recovery Response Example**: -```json -{ - "success": true, - "message": "Camera camera1 reconnected successfully", - "camera_name": "camera1", - "operation": "reconnect", - "timestamp": "2024-01-15T10:30:00Z" -} -``` - -## 📺 Live Streaming - -### Get Live MJPEG Stream -```http -GET /cameras/{camera_name}/stream -``` -**Response**: MJPEG video stream (multipart/x-mixed-replace) - -### Start Camera Stream -```http -POST /cameras/{camera_name}/start-stream -``` - -### Stop Camera Stream -```http -POST /cameras/{camera_name}/stop-stream -``` - -**Streaming Features**: -- 📺 **MJPEG format**: Compatible with web browsers and React apps -- 🔄 **Concurrent operation**: Stream while recording simultaneously -- ⚡ **Low latency**: Real-time preview for monitoring - -For detailed streaming integration, see [Streaming Guide](guides/STREAMING_GUIDE.md). - -## 🎬 Video Streaming & Playback - -The system includes a comprehensive video streaming module that provides YouTube-like video playback capabilities with HTTP range request support, thumbnail generation, and intelligent caching. - -### List Videos -```http -GET /videos/ -``` -**Query Parameters:** -- `camera_name` (optional): Filter by camera name -- `start_date` (optional): Filter videos created after this date (ISO format) -- `end_date` (optional): Filter videos created before this date (ISO format) -- `limit` (optional): Maximum number of results (default: 50, max: 1000) -- `include_metadata` (optional): Include video metadata (default: false) - -**Response**: `VideoListResponse` -```json -{ - "videos": [ - { - "file_id": "camera1_auto_blower_separator_20250804_143022.mp4", - "camera_name": "camera1", - "filename": "camera1_auto_blower_separator_20250804_143022.mp4", - "file_size_bytes": 31457280, - "format": "mp4", - "status": "completed", - "created_at": "2025-08-04T14:30:22", - "start_time": "2025-08-04T14:30:22", - "end_time": "2025-08-04T14:32:22", - "machine_trigger": "blower_separator", - "is_streamable": true, - "needs_conversion": false, - "metadata": { - "duration_seconds": 120.5, - "width": 1920, - "height": 1080, - "fps": 30.0, - "codec": "mp4v", - "bitrate": 5000000, - "aspect_ratio": 1.777 - } - } - ], - "total_count": 1 -} -``` - -### Get Video Information -```http -GET /videos/{file_id} -``` -**Response**: `VideoInfoResponse` with detailed video information including metadata. - -### Stream Video -```http -GET /videos/{file_id}/stream -``` -**Headers:** -- `Range: bytes=0-1023` (optional): Request specific byte range for seeking - -**Features:** -- ✅ **HTTP Range Requests**: Enables video seeking and progressive download -- ✅ **Partial Content**: Returns 206 status for range requests -- ✅ **Format Conversion**: Automatic AVI to MP4 conversion for web compatibility -- ✅ **Intelligent Caching**: Optimized performance with byte-range caching -- ✅ **CORS Enabled**: Ready for web browser integration - -**Response Headers:** -- `Accept-Ranges: bytes` -- `Content-Length: {size}` -- `Content-Range: bytes {start}-{end}/{total}` (for range requests) -- `Cache-Control: public, max-age=3600` - -### Get Video Thumbnail -```http -GET /videos/{file_id}/thumbnail?timestamp=5.0&width=320&height=240 -``` -**Query Parameters:** -- `timestamp` (optional): Time position in seconds (default: 1.0) -- `width` (optional): Thumbnail width in pixels (default: 320) -- `height` (optional): Thumbnail height in pixels (default: 240) - -**Response**: JPEG image data with caching headers - -### Get Streaming Information -```http -GET /videos/{file_id}/info -``` -**Response**: `StreamingInfoResponse` -```json -{ - "file_id": "camera1_recording_20250804_143022.avi", - "file_size_bytes": 52428800, - "content_type": "video/mp4", - "supports_range_requests": true, - "chunk_size_bytes": 262144 -} -``` - -### Video Validation -```http -POST /videos/{file_id}/validate -``` -**Response**: Validation status and accessibility check -```json -{ - "file_id": "camera1_recording_20250804_143022.avi", - "is_valid": true -} -``` - -### Cache Management -```http -POST /videos/{file_id}/cache/invalidate -``` -**Response**: Cache invalidation status -```json -{ - "file_id": "camera1_recording_20250804_143022.avi", - "cache_invalidated": true -} -``` - -### Admin: Cache Cleanup -```http -POST /admin/videos/cache/cleanup?max_size_mb=100 -``` -**Response**: Cache cleanup results -```json -{ - "cache_cleaned": true, - "entries_removed": 15, - "max_size_mb": 100 -} -``` - -**Video Streaming Features**: -- 🎥 **Multiple Formats**: Native MP4 support with AVI conversion -- 📱 **Web Compatible**: Direct integration with HTML5 video elements -- ⚡ **High Performance**: Intelligent caching and adaptive chunking -- 🖼️ **Thumbnail Generation**: Extract preview images at any timestamp -- 🔄 **Range Requests**: Efficient seeking and progressive download - -## 🌐 WebSocket Real-time Updates - -### Connect to WebSocket -```javascript -const ws = new WebSocket('ws://localhost:8000/ws'); - -ws.onmessage = (event) => { - const update = JSON.parse(event.data); - console.log('Real-time update:', update); -}; -``` - -**WebSocket Message Types**: -- `system_status`: System status changes -- `camera_status`: Camera status updates -- `recording_started`: Recording start events -- `recording_stopped`: Recording stop events -- `mqtt_message`: MQTT message received -- `auto_recording_event`: Auto-recording status changes - -**Example WebSocket Message**: -```json -{ - "type": "recording_started", - "data": { - "camera_name": "camera1", - "filename": "20240115_103000_auto_recording.avi", - "timestamp": "2024-01-15T10:30:00Z" - }, - "timestamp": "2024-01-15T10:30:00Z" -} -``` - -## 🚀 Quick Start Examples - -### Basic System Monitoring -```bash -# Check system health -curl http://localhost:8000/health - -# Get overall system status -curl http://localhost:8000/system/status - -# Get all camera statuses -curl http://localhost:8000/cameras -``` - -### Manual Recording Control -```bash -# Start recording with default settings -curl -X POST http://localhost:8000/cameras/camera1/start-recording \ - -H "Content-Type: application/json" \ - -d '{"filename": "manual_test.avi"}' - -# Start recording with custom camera settings -curl -X POST http://localhost:8000/cameras/camera1/start-recording \ - -H "Content-Type: application/json" \ - -d '{ - "filename": "high_quality.avi", - "exposure_ms": 2.0, - "gain": 4.0, - "fps": 5.0 - }' - -# Stop recording -curl -X POST http://localhost:8000/cameras/camera1/stop-recording -``` - -### Auto-Recording Management -```bash -# Enable auto-recording for camera1 -curl -X POST http://localhost:8000/cameras/camera1/auto-recording/enable - -# Check auto-recording status -curl http://localhost:8000/auto-recording/status - -# Disable auto-recording for camera1 -curl -X POST http://localhost:8000/cameras/camera1/auto-recording/disable -``` - -### Video Streaming Operations -```bash -# List all videos -curl http://localhost:8000/videos/ - -# List videos from specific camera with metadata -curl "http://localhost:8000/videos/?camera_name=camera1&include_metadata=true" - -# Get video information -curl http://localhost:8000/videos/camera1_recording_20250804_143022.avi - -# Get video thumbnail -curl "http://localhost:8000/videos/camera1_recording_20250804_143022.avi/thumbnail?timestamp=5.0&width=320&height=240" \ - --output thumbnail.jpg - -# Get streaming info -curl http://localhost:8000/videos/camera1_recording_20250804_143022.avi/info - -# Stream video with range request -curl -H "Range: bytes=0-1023" \ - http://localhost:8000/videos/camera1_recording_20250804_143022.avi/stream - -# Validate video file -curl -X POST http://localhost:8000/videos/camera1_recording_20250804_143022.avi/validate - -# Clean up video cache (admin) -curl -X POST "http://localhost:8000/admin/videos/cache/cleanup?max_size_mb=100" -``` - -### Camera Configuration -```bash -# Get current camera configuration -curl http://localhost:8000/cameras/camera1/config - -# Update camera settings (real-time) -curl -X PUT http://localhost:8000/cameras/camera1/config \ - -H "Content-Type: application/json" \ - -d '{ - "exposure_ms": 1.5, - "gain": 3.0, - "sharpness": 130, - "contrast": 120 - }' -``` - -## 📈 Recent API Changes & Enhancements - -### ✨ New in Latest Version - -#### 1. Enhanced Recording API -- **Dynamic camera settings**: Set exposure, gain, and FPS per recording -- **Automatic datetime prefixes**: All filenames get timestamp prefixes -- **Backward compatibility**: Existing API calls work unchanged - -#### 2. Auto-Recording Feature -- **Per-camera control**: Enable/disable auto-recording individually -- **MQTT integration**: Automatic recording based on machine states -- **Retry logic**: Failed recordings are automatically retried -- **Status tracking**: Monitor auto-recording attempts and failures - -#### 3. Advanced Camera Configuration -- **Real-time settings**: Update exposure, gain, image quality without restart -- **Image enhancement**: Sharpness, contrast, saturation, gamma controls -- **Noise reduction**: Configurable noise filtering and 3D denoising -- **HDR support**: High Dynamic Range imaging capabilities - -#### 4. Live Streaming -- **MJPEG streaming**: Real-time camera preview -- **Concurrent operation**: Stream while recording simultaneously -- **Web-compatible**: Direct integration with React/HTML video elements - -#### 5. Enhanced Monitoring -- **MQTT event history**: Track machine state changes over time -- **Storage statistics**: Monitor disk usage and file counts -- **WebSocket updates**: Real-time system status notifications - -#### 6. Video Streaming Module -- **HTTP Range Requests**: Efficient video seeking and progressive download -- **Thumbnail Generation**: Extract preview images from videos at any timestamp -- **Format Conversion**: Automatic AVI to MP4 conversion for web compatibility -- **Intelligent Caching**: Byte-range caching for optimal streaming performance -- **Admin Tools**: Cache management and video validation endpoints - -### 🔄 Migration Notes - -#### From Previous Versions -1. **Recording API**: All existing calls work, but now return filenames with datetime prefixes -2. **Configuration**: New camera settings are optional and backward compatible -3. **Auto-recording**: New feature, requires enabling in `config.json` and per camera - -#### Configuration Updates -```json -{ - "cameras": [ - { - "name": "camera1", - "auto_start_recording_enabled": true, // NEW: Enable auto-recording - "sharpness": 120, // NEW: Image quality settings - "contrast": 110, - "saturation": 100, - "gamma": 100, - "noise_filter_enabled": true, - "hdr_enabled": false - } - ], - "system": { - "auto_recording_enabled": true // NEW: Global auto-recording toggle - } -} -``` - -## 🔗 Related Documentation - -- [📷 Camera Configuration API Guide](api/CAMERA_CONFIG_API.md) - Detailed camera settings -- [🤖 Auto-Recording Feature Guide](features/AUTO_RECORDING_FEATURE_GUIDE.md) - React integration -- [📺 Streaming Guide](guides/STREAMING_GUIDE.md) - Live video streaming -- [🎬 Video Streaming Guide](VIDEO_STREAMING.md) - Video playback and streaming -- [🤖 AI Agent Video Integration Guide](AI_AGENT_VIDEO_INTEGRATION_GUIDE.md) - Complete integration guide for AI agents -- [🔧 Camera Recovery Guide](guides/CAMERA_RECOVERY_GUIDE.md) - Troubleshooting -- [📡 MQTT Logging Guide](guides/MQTT_LOGGING_GUIDE.md) - MQTT configuration - -## 📞 Support & Integration - -### API Base URL -- **Development**: `http://localhost:8000` -- **Production**: Configure in `config.json` under `system.api_host` and `system.api_port` - -### Error Handling -All endpoints return standard HTTP status codes: -- `200`: Success -- `206`: Partial Content (for video range requests) -- `400`: Bad Request (invalid parameters) -- `404`: Resource not found (camera, file, video, etc.) -- `416`: Range Not Satisfiable (invalid video range request) -- `500`: Internal server error -- `503`: Service unavailable (camera manager, MQTT, etc.) - -**Video Streaming Specific Errors:** -- `404`: Video file not found or not streamable -- `416`: Invalid range request (malformed Range header) -- `500`: Failed to read video data or generate thumbnail - -### Rate Limiting -- No rate limiting currently implemented -- WebSocket connections are limited to reasonable concurrent connections - -### CORS Support -- CORS is enabled for web dashboard integration -- Configure allowed origins in the API server settings -``` -``` diff --git a/management-dashboard-web-app/API Documentations/docs/API_QUICK_REFERENCE.md b/management-dashboard-web-app/API Documentations/docs/API_QUICK_REFERENCE.md deleted file mode 100755 index 1ec7a54..0000000 --- a/management-dashboard-web-app/API Documentations/docs/API_QUICK_REFERENCE.md +++ /dev/null @@ -1,195 +0,0 @@ -# 🚀 USDA Vision Camera System - API Quick Reference - -Quick reference for the most commonly used API endpoints. For complete documentation, see [API_DOCUMENTATION.md](API_DOCUMENTATION.md). - -## 🔧 System Status - -```bash -# Health check -curl http://localhost:8000/health - -# System overview -curl http://localhost:8000/system/status - -# All cameras -curl http://localhost:8000/cameras - -# All machines -curl http://localhost:8000/machines -``` - -## 🎥 Recording Control - -### Start Recording (Basic) -```bash -curl -X POST http://localhost:8000/cameras/camera1/start-recording \ - -H "Content-Type: application/json" \ - -d '{"filename": "test.avi"}' -``` - -### Start Recording (With Settings) -```bash -curl -X POST http://localhost:8000/cameras/camera1/start-recording \ - -H "Content-Type: application/json" \ - -d '{ - "filename": "high_quality.avi", - "exposure_ms": 2.0, - "gain": 4.0, - "fps": 5.0 - }' -``` - -### Stop Recording -```bash -curl -X POST http://localhost:8000/cameras/camera1/stop-recording -``` - -## 🤖 Auto-Recording - -```bash -# Enable auto-recording -curl -X POST http://localhost:8000/cameras/camera1/auto-recording/enable - -# Disable auto-recording -curl -X POST http://localhost:8000/cameras/camera1/auto-recording/disable - -# Check auto-recording status -curl http://localhost:8000/auto-recording/status -``` - -## 🎛️ Camera Configuration - -```bash -# Get camera config -curl http://localhost:8000/cameras/camera1/config - -# Update camera settings -curl -X PUT http://localhost:8000/cameras/camera1/config \ - -H "Content-Type: application/json" \ - -d '{ - "exposure_ms": 1.5, - "gain": 3.0, - "sharpness": 130 - }' -``` - -## 📺 Live Streaming - -```bash -# Start streaming -curl -X POST http://localhost:8000/cameras/camera1/start-stream - -# Get MJPEG stream (use in browser/video element) -# http://localhost:8000/cameras/camera1/stream - -# Stop streaming -curl -X POST http://localhost:8000/cameras/camera1/stop-stream -``` - -## 🔄 Camera Recovery - -```bash -# Test connection -curl -X POST http://localhost:8000/cameras/camera1/test-connection - -# Reconnect camera -curl -X POST http://localhost:8000/cameras/camera1/reconnect - -# Full reset -curl -X POST http://localhost:8000/cameras/camera1/full-reset -``` - -## 💾 Storage Management - -```bash -# Storage statistics -curl http://localhost:8000/storage/stats - -# List files -curl -X POST http://localhost:8000/storage/files \ - -H "Content-Type: application/json" \ - -d '{"camera_name": "camera1", "limit": 10}' - -# Cleanup old files -curl -X POST http://localhost:8000/storage/cleanup \ - -H "Content-Type: application/json" \ - -d '{"max_age_days": 30}' -``` - -## 📡 MQTT Monitoring - -```bash -# MQTT status -curl http://localhost:8000/mqtt/status - -# Recent MQTT events -curl http://localhost:8000/mqtt/events?limit=10 -``` - -## 🌐 WebSocket Connection - -```javascript -// Connect to real-time updates -const ws = new WebSocket('ws://localhost:8000/ws'); - -ws.onmessage = (event) => { - const update = JSON.parse(event.data); - console.log('Update:', update); -}; -``` - -## 📊 Response Examples - -### System Status Response -```json -{ - "system_started": true, - "mqtt_connected": true, - "cameras": { - "camera1": { - "name": "camera1", - "status": "ACTIVE", - "is_recording": false, - "auto_recording_enabled": true - } - }, - "active_recordings": 0, - "total_recordings": 15 -} -``` - -### Recording Start Response -```json -{ - "success": true, - "message": "Recording started for camera1", - "filename": "20240115_103000_test.avi" -} -``` - -### Camera Status Response -```json -{ - "name": "camera1", - "status": "ACTIVE", - "is_recording": false, - "auto_recording_enabled": true, - "auto_recording_active": false, - "auto_recording_failure_count": 0 -} -``` - -## 🔗 Related Documentation - -- [📚 Complete API Documentation](API_DOCUMENTATION.md) -- [🎛️ Camera Configuration Guide](api/CAMERA_CONFIG_API.md) -- [🤖 Auto-Recording Feature Guide](features/AUTO_RECORDING_FEATURE_GUIDE.md) -- [📺 Streaming Guide](guides/STREAMING_GUIDE.md) - -## 💡 Tips - -- All filenames automatically get datetime prefixes: `YYYYMMDD_HHMMSS_` -- Camera settings can be updated in real-time during recording -- Auto-recording is controlled per camera and globally -- WebSocket provides real-time updates for dashboard integration -- CORS is enabled for web application integration diff --git a/management-dashboard-web-app/API Documentations/docs/CURRENT_CONFIGURATION.md b/management-dashboard-web-app/API Documentations/docs/CURRENT_CONFIGURATION.md deleted file mode 100755 index 891f7e6..0000000 --- a/management-dashboard-web-app/API Documentations/docs/CURRENT_CONFIGURATION.md +++ /dev/null @@ -1,217 +0,0 @@ -# 📋 Current System Configuration Reference - -## Overview -This document shows the exact current configuration structure of the USDA Vision Camera System, including all fields and their current values. - -## 🔧 Complete Configuration Structure - -### System Configuration (`config.json`) - -```json -{ - "mqtt": { - "broker_host": "192.168.1.110", - "broker_port": 1883, - "username": null, - "password": null, - "topics": { - "vibratory_conveyor": "vision/vibratory_conveyor/state", - "blower_separator": "vision/blower_separator/state" - } - }, - "storage": { - "base_path": "/storage", - "max_file_size_mb": 1000, - "max_recording_duration_minutes": 60, - "cleanup_older_than_days": 30 - }, - "system": { - "camera_check_interval_seconds": 2, - "log_level": "DEBUG", - "log_file": "usda_vision_system.log", - "api_host": "0.0.0.0", - "api_port": 8000, - "enable_api": true, - "timezone": "America/New_York", - "auto_recording_enabled": true - }, - "cameras": [ - { - "name": "camera1", - "machine_topic": "blower_separator", - "storage_path": "/storage/camera1", - "exposure_ms": 0.3, - "gain": 4.0, - "target_fps": 0, - "enabled": true, - "video_format": "mp4", - "video_codec": "mp4v", - "video_quality": 95, - "auto_start_recording_enabled": true, - "auto_recording_max_retries": 3, - "auto_recording_retry_delay_seconds": 2, - "sharpness": 0, - "contrast": 100, - "saturation": 100, - "gamma": 100, - "noise_filter_enabled": false, - "denoise_3d_enabled": false, - "auto_white_balance": false, - "color_temperature_preset": 0, - "wb_red_gain": 0.94, - "wb_green_gain": 1.0, - "wb_blue_gain": 0.87, - "anti_flicker_enabled": false, - "light_frequency": 0, - "bit_depth": 8, - "hdr_enabled": false, - "hdr_gain_mode": 2 - }, - { - "name": "camera2", - "machine_topic": "vibratory_conveyor", - "storage_path": "/storage/camera2", - "exposure_ms": 0.2, - "gain": 2.0, - "target_fps": 0, - "enabled": true, - "video_format": "mp4", - "video_codec": "mp4v", - "video_quality": 95, - "auto_start_recording_enabled": true, - "auto_recording_max_retries": 3, - "auto_recording_retry_delay_seconds": 2, - "sharpness": 0, - "contrast": 100, - "saturation": 100, - "gamma": 100, - "noise_filter_enabled": false, - "denoise_3d_enabled": false, - "auto_white_balance": false, - "color_temperature_preset": 0, - "wb_red_gain": 1.01, - "wb_green_gain": 1.0, - "wb_blue_gain": 0.87, - "anti_flicker_enabled": false, - "light_frequency": 0, - "bit_depth": 8, - "hdr_enabled": false, - "hdr_gain_mode": 0 - } - ] -} -``` - -## 📊 Configuration Field Reference - -### MQTT Settings -| Field | Value | Description | -|-------|-------|-------------| -| `broker_host` | `"192.168.1.110"` | MQTT broker IP address | -| `broker_port` | `1883` | MQTT broker port | -| `username` | `null` | MQTT authentication (not used) | -| `password` | `null` | MQTT authentication (not used) | - -### MQTT Topics -| Machine | Topic | Camera | -|---------|-------|--------| -| Vibratory Conveyor | `vision/vibratory_conveyor/state` | camera2 | -| Blower Separator | `vision/blower_separator/state` | camera1 | - -### Storage Settings -| Field | Value | Description | -|-------|-------|-------------| -| `base_path` | `"/mnt/nfs_share"` | Root storage directory | -| `max_file_size_mb` | `1000` | Maximum file size (1GB) | -| `max_recording_duration_minutes` | `60` | Maximum recording duration | -| `cleanup_older_than_days` | `30` | Auto-cleanup threshold | - -### System Settings -| Field | Value | Description | -|-------|-------|-------------| -| `camera_check_interval_seconds` | `2` | Camera health check interval | -| `log_level` | `"DEBUG"` | Logging verbosity | -| `api_host` | `"0.0.0.0"` | API server bind address | -| `api_port` | `8000` | API server port | -| `timezone` | `"America/New_York"` | System timezone | -| `auto_recording_enabled` | `true` | Enable MQTT-triggered recording | - -## 🎥 Camera Configuration Details - -### Camera 1 (Blower Separator) -| Setting | Value | Description | -|---------|-------|-------------| -| **Basic Settings** | | | -| `name` | `"camera1"` | Camera identifier | -| `machine_topic` | `"blower_separator"` | MQTT topic to monitor | -| `storage_path` | `"/mnt/nfs_share/camera1"` | Video storage location | -| `exposure_ms` | `0.3` | Exposure time (milliseconds) | -| `gain` | `4.0` | Camera gain multiplier | -| `target_fps` | `0` | Target FPS (0 = unlimited) | -| **Video Recording** | | | -| `video_format` | `"mp4"` | Video file format | -| `video_codec` | `"mp4v"` | Video codec (MPEG-4) | -| `video_quality` | `95` | Video quality (0-100) | -| **Auto Recording** | | | -| `auto_start_recording_enabled` | `true` | Enable auto-recording | -| `auto_recording_max_retries` | `3` | Max retry attempts | -| `auto_recording_retry_delay_seconds` | `2` | Delay between retries | -| **Image Quality** | | | -| `sharpness` | `0` | Sharpness adjustment | -| `contrast` | `100` | Contrast level | -| `saturation` | `100` | Color saturation | -| `gamma` | `100` | Gamma correction | -| **White Balance** | | | -| `auto_white_balance` | `false` | Auto white balance disabled | -| `wb_red_gain` | `0.94` | Red channel gain | -| `wb_green_gain` | `1.0` | Green channel gain | -| `wb_blue_gain` | `0.87` | Blue channel gain | -| **Advanced** | | | -| `bit_depth` | `8` | Color bit depth | -| `hdr_enabled` | `false` | HDR disabled | -| `hdr_gain_mode` | `2` | HDR gain mode | - -### Camera 2 (Vibratory Conveyor) -| Setting | Value | Difference from Camera 1 | -|---------|-------|--------------------------| -| `name` | `"camera2"` | Different identifier | -| `machine_topic` | `"vibratory_conveyor"` | Different MQTT topic | -| `storage_path` | `"/storage/camera2"` | Different storage path | -| `exposure_ms` | `0.2` | Faster exposure (0.2 vs 0.3) | -| `gain` | `2.0` | Lower gain (2.0 vs 4.0) | -| `wb_red_gain` | `1.01` | Different red balance (1.01 vs 0.94) | -| `hdr_gain_mode` | `0` | Different HDR mode (0 vs 2) | - -*All other settings are identical to Camera 1* - -## 🔄 Recent Changes - -### MP4 Format Update -- **Added**: `video_format`, `video_codec`, `video_quality` fields -- **Changed**: Default recording format from AVI to MP4 -- **Impact**: Requires service restart to take effect - -### Current Status -- ✅ Configuration updated with MP4 settings -- ⚠️ Service restart required to apply changes -- 📁 Existing AVI files remain accessible - -## 📝 Notes - -1. **Target FPS = 0**: Both cameras use unlimited frame rate for maximum capture speed -2. **Auto Recording**: Both cameras automatically start recording when their respective machines turn on -3. **White Balance**: Manual white balance settings optimized for each camera's environment -4. **Storage**: Each camera has its own dedicated storage directory -5. **Video Quality**: Set to 95/100 for high-quality recordings with MP4 compression benefits - -## 🔧 Configuration Management - -To modify these settings: -1. Edit `config.json` file -2. Restart the camera service: `sudo ./start_system.sh` -3. Verify changes via API: `GET /cameras/{camera_name}/config` - -For real-time settings (exposure, gain, fps), use the API without restart: -```bash -PUT /cameras/{camera_name}/config -``` diff --git a/management-dashboard-web-app/API Documentations/docs/MP4_FORMAT_UPDATE.md b/management-dashboard-web-app/API Documentations/docs/MP4_FORMAT_UPDATE.md deleted file mode 100755 index ecae663..0000000 --- a/management-dashboard-web-app/API Documentations/docs/MP4_FORMAT_UPDATE.md +++ /dev/null @@ -1,211 +0,0 @@ -# 🎥 MP4 Video Format Update - Frontend Integration Guide - -## Overview -The USDA Vision Camera System has been updated to record videos in **MP4 format** instead of AVI format for better streaming compatibility and smaller file sizes. - -## 🔄 What Changed - -### Video Format -- **Before**: AVI files with XVID codec (`.avi` extension) -- **After**: MP4 files with MPEG-4 codec (`.mp4` extension) - -### File Extensions -- All new video recordings now use `.mp4` extension -- Existing `.avi` files remain accessible and functional -- File size reduction: ~40% smaller than equivalent AVI files - -### API Response Updates -New fields added to camera configuration responses: - -```json -{ - "video_format": "mp4", // File format: "mp4" or "avi" - "video_codec": "mp4v", // Video codec: "mp4v", "XVID", "MJPG" - "video_quality": 95 // Quality: 0-100 (higher = better) -} -``` - -## 🌐 Frontend Impact - -### 1. Video Player Compatibility -**✅ Better Browser Support** -- MP4 format has native support in all modern browsers -- No need for additional codecs or plugins -- Better mobile device compatibility (iOS/Android) - -### 2. File Handling Updates -**File Extension Handling** -```javascript -// Update file extension checks -const isVideoFile = (filename) => { - return filename.endsWith('.mp4') || filename.endsWith('.avi'); -}; - -// Video MIME type detection -const getVideoMimeType = (filename) => { - if (filename.endsWith('.mp4')) return 'video/mp4'; - if (filename.endsWith('.avi')) return 'video/x-msvideo'; - return 'video/mp4'; // default -}; -``` - -### 3. Video Streaming -**Improved Streaming Performance** -```javascript -// MP4 files can be streamed directly without conversion -const videoUrl = `/api/videos/${videoId}/stream`; - -// For HTML5 video element - -``` - -### 4. File Size Display -**Updated Size Expectations** -- MP4 files are ~40% smaller than equivalent AVI files -- Update any file size warnings or storage calculations -- Better compression means faster downloads and uploads - -## 📡 API Changes - -### Camera Configuration Endpoint -**GET** `/cameras/{camera_name}/config` - -**New Response Fields:** -```json -{ - "name": "camera1", - "machine_topic": "blower_separator", - "storage_path": "/storage/camera1", - "exposure_ms": 0.3, - "gain": 4.0, - "target_fps": 0, - "enabled": true, - "video_format": "mp4", - "video_codec": "mp4v", - "video_quality": 95, - "auto_start_recording_enabled": true, - "auto_recording_max_retries": 3, - "auto_recording_retry_delay_seconds": 2, - - // ... other existing fields -} -``` - -### Video Listing Endpoints -**File Extension Updates** -- Video files in responses will now have `.mp4` extensions -- Existing `.avi` files will still appear in listings -- Filter by both extensions when needed - -## 🔧 Configuration Options - -### Video Format Settings -```json -{ - "video_format": "mp4", // Options: "mp4", "avi" - "video_codec": "mp4v", // Options: "mp4v", "XVID", "MJPG" - "video_quality": 95 // Range: 0-100 (higher = better quality) -} -``` - -### Recommended Settings -- **Production**: `"mp4"` format, `"mp4v"` codec, `95` quality -- **Storage Optimized**: `"mp4"` format, `"mp4v"` codec, `85` quality -- **Legacy Mode**: `"avi"` format, `"XVID"` codec, `95` quality - -## 🎯 Frontend Implementation Checklist - -### ✅ Video Player Updates -- [ ] Verify HTML5 video player works with MP4 files -- [ ] Update video MIME type handling -- [ ] Test streaming performance with new format - -### ✅ File Management -- [ ] Update file extension filters to include `.mp4` -- [ ] Modify file type detection logic -- [ ] Update download/upload handling for MP4 files - -### ✅ UI/UX Updates -- [ ] Update file size expectations in UI -- [ ] Modify any format-specific icons or indicators -- [ ] Update help text or tooltips mentioning video formats - -### ✅ Configuration Interface -- [ ] Add video format settings to camera config UI -- [ ] Include video quality slider/selector -- [ ] Add restart warning for video format changes - -### ✅ Testing -- [ ] Test video playback with new MP4 files -- [ ] Verify backward compatibility with existing AVI files -- [ ] Test streaming performance and loading times - -## 🔄 Backward Compatibility - -### Existing AVI Files -- All existing `.avi` files remain fully functional -- No conversion or migration required -- Video player should handle both formats - -### API Compatibility -- All existing API endpoints continue to work -- New fields are additive (won't break existing code) -- Default values provided for new configuration fields - -## 📊 Performance Benefits - -### File Size Reduction -``` -Example 5-minute recording at 1280x1024: -- AVI/XVID: ~180 MB -- MP4/MPEG-4: ~108 MB (40% reduction) -``` - -### Streaming Improvements -- Faster initial load times -- Better progressive download support -- Reduced bandwidth usage -- Native browser optimization - -### Storage Efficiency -- More recordings fit in same storage space -- Faster backup and transfer operations -- Reduced storage costs over time - -## 🚨 Important Notes - -### Restart Required -- Video format changes require camera service restart -- Mark video format settings as "restart required" in UI -- Provide clear user feedback about restart necessity - -### Browser Compatibility -- MP4 format supported in all modern browsers -- Better mobile device support than AVI -- No additional plugins or codecs needed - -### Quality Assurance -- Video quality maintained at 95/100 setting -- No visual degradation compared to AVI -- High bitrate ensures professional quality - -## 🔗 Related Documentation - -- [API Documentation](API_DOCUMENTATION.md) - Complete API reference -- [Camera Configuration API](api/CAMERA_CONFIG_API.md) - Detailed config options -- [Video Streaming Guide](VIDEO_STREAMING.md) - Streaming implementation -- [MP4 Conversion Summary](../MP4_CONVERSION_SUMMARY.md) - Technical details - -## 📞 Support - -If you encounter any issues with the MP4 format update: - -1. **Video Playback Issues**: Check browser console for codec errors -2. **File Size Concerns**: Verify quality settings in camera config -3. **Streaming Problems**: Test with both MP4 and AVI files for comparison -4. **API Integration**: Refer to updated API documentation - -The MP4 format provides better web compatibility and performance while maintaining the same high video quality required for the USDA vision system. diff --git a/management-dashboard-web-app/API Documentations/docs/PROJECT_COMPLETE.md b/management-dashboard-web-app/API Documentations/docs/PROJECT_COMPLETE.md deleted file mode 100755 index 0f4df48..0000000 --- a/management-dashboard-web-app/API Documentations/docs/PROJECT_COMPLETE.md +++ /dev/null @@ -1,212 +0,0 @@ -# 🎉 USDA Vision Camera System - PROJECT COMPLETE! - -## ✅ Final Status: READY FOR PRODUCTION - -The USDA Vision Camera System has been successfully implemented, tested, and documented. All requirements have been met and the system is production-ready. - -## 📋 Completed Requirements - -### ✅ Core Functionality -- **MQTT Integration**: Dual topic listening for machine states -- **Automatic Recording**: Camera recording triggered by machine on/off states -- **GigE Camera Support**: Full integration with camera SDK library -- **Multi-threading**: Concurrent MQTT + camera monitoring + recording -- **File Management**: Timestamp-based naming in organized directories - -### ✅ Advanced Features -- **REST API**: Complete FastAPI server with all endpoints -- **WebSocket Support**: Real-time updates for dashboard integration -- **Time Synchronization**: Atlanta, Georgia timezone with NTP sync -- **Storage Management**: File indexing, cleanup, and statistics -- **Comprehensive Logging**: Rotating logs with error tracking -- **Configuration System**: JSON-based configuration management - -### ✅ Documentation & Testing -- **Complete README**: Installation, usage, API docs, troubleshooting -- **Test Suite**: Comprehensive system testing (`test_system.py`) -- **Time Verification**: Timezone and sync testing (`check_time.py`) -- **Startup Scripts**: Easy deployment with `start_system.sh` -- **Clean Repository**: Organized structure with proper .gitignore - -## 🏗️ Final Project Structure - -``` -USDA-Vision-Cameras/ -├── README.md # Complete documentation -├── main.py # System entry point -├── config.json # System configuration -├── requirements.txt # Python dependencies -├── pyproject.toml # UV package configuration -├── .gitignore # Git ignore rules -├── start_system.sh # Startup script -├── setup_timezone.sh # Time sync setup -├── test_system.py # System test suite -├── check_time.py # Time verification -├── test_timezone.py # Timezone testing -├── usda_vision_system/ # Main application -│ ├── core/ # Core functionality -│ ├── mqtt/ # MQTT integration -│ ├── camera/ # Camera management -│ ├── storage/ # File management -│ ├── api/ # REST API server -│ └── main.py # Application coordinator -├── camera_sdk/ # GigE camera SDK library -├── demos/ # Demo and example code -│ ├── cv_grab*.py # Camera SDK usage examples -│ └── mqtt_*.py # MQTT demo scripts -├── storage/ # Recording storage -│ ├── camera1/ # Camera 1 recordings -│ └── camera2/ # Camera 2 recordings -├── tests/ # Test files and legacy tests -├── notebooks/ # Jupyter notebooks -└── docs/ # Documentation files -``` - -## 🚀 How to Deploy - -### 1. Clone and Setup -```bash -git clone https://github.com/your-username/USDA-Vision-Cameras.git -cd USDA-Vision-Cameras -uv sync -``` - -### 2. Configure System -```bash -# Edit config.json for your environment -# Set MQTT broker, camera settings, storage paths -``` - -### 3. Setup Time Sync -```bash -./setup_timezone.sh -``` - -### 4. Test System -```bash -python test_system.py -``` - -### 5. Start System -```bash -./start_system.sh -``` - -## 🌐 API Integration - -### Dashboard Integration -```javascript -// React component example -const systemStatus = await fetch('http://localhost:8000/system/status'); -const cameras = await fetch('http://localhost:8000/cameras'); - -// WebSocket for real-time updates -const ws = new WebSocket('ws://localhost:8000/ws'); -ws.onmessage = (event) => { - const update = JSON.parse(event.data); - // Handle real-time system updates -}; -``` - -### Manual Control -```bash -# Start recording manually -curl -X POST http://localhost:8000/cameras/camera1/start-recording - -# Stop recording manually -curl -X POST http://localhost:8000/cameras/camera1/stop-recording - -# Get system status -curl http://localhost:8000/system/status -``` - -## 📊 System Capabilities - -### Discovered Hardware -- **2 GigE Cameras**: Blower-Yield-Cam, Cracker-Cam -- **Network Ready**: Cameras accessible at 192.168.1.165, 192.168.1.167 -- **MQTT Ready**: Configured for broker at 192.168.1.110 - -### Recording Features -- **Automatic Start/Stop**: Based on MQTT machine states -- **Timezone Aware**: Atlanta time timestamps (EST/EDT) -- **Organized Storage**: Separate directories per camera -- **File Naming**: `camera1_recording_20250725_213000.avi` -- **Manual Control**: API endpoints for manual recording - -### Monitoring Features -- **Real-time Status**: Camera and machine state monitoring -- **Health Checks**: Automatic system health verification -- **Performance Tracking**: Recording metrics and system stats -- **Error Handling**: Comprehensive error tracking and recovery - -## 🔧 Maintenance - -### Regular Tasks -- **Log Monitoring**: Check `usda_vision_system.log` -- **Storage Cleanup**: Automatic cleanup of old recordings -- **Time Sync**: Automatic NTP synchronization -- **Health Checks**: Built-in system monitoring - -### Troubleshooting -- **Test Suite**: `python test_system.py` -- **Time Check**: `python check_time.py` -- **API Health**: `curl http://localhost:8000/health` -- **Debug Mode**: `python main.py --log-level DEBUG` - -## 🎯 Production Readiness - -### ✅ All Tests Passing -- System initialization: ✅ -- Camera discovery: ✅ (2 cameras found) -- MQTT configuration: ✅ -- Storage setup: ✅ -- Time synchronization: ✅ -- API endpoints: ✅ - -### ✅ Documentation Complete -- Installation guide: ✅ -- Configuration reference: ✅ -- API documentation: ✅ -- Troubleshooting guide: ✅ -- Integration examples: ✅ - -### ✅ Production Features -- Error handling: ✅ -- Logging system: ✅ -- Time synchronization: ✅ -- Storage management: ✅ -- API security: ✅ -- Performance monitoring: ✅ - -## 🚀 Next Steps - -The system is now ready for: - -1. **Production Deployment**: Deploy on target hardware -2. **Dashboard Integration**: Connect to React + Supabase dashboard -3. **MQTT Configuration**: Connect to production MQTT broker -4. **Camera Calibration**: Fine-tune camera settings for production -5. **Monitoring Setup**: Configure production monitoring and alerts - -## 📞 Support - -For ongoing support: -- **Documentation**: Complete README.md with troubleshooting -- **Test Suite**: Comprehensive diagnostic tools -- **Logging**: Detailed system logs for debugging -- **API Health**: Built-in health check endpoints - ---- - -**🎊 PROJECT STATUS: COMPLETE AND PRODUCTION-READY! 🎊** - -The USDA Vision Camera System is fully implemented, tested, and documented. All original requirements have been met, and the system is ready for production deployment with your React dashboard integration. - -**Key Achievements:** -- ✅ Dual MQTT topic monitoring -- ✅ Automatic camera recording -- ✅ Atlanta timezone synchronization -- ✅ Complete REST API -- ✅ Comprehensive documentation -- ✅ Production-ready deployment diff --git a/management-dashboard-web-app/API Documentations/docs/REACT_INTEGRATION_GUIDE.md b/management-dashboard-web-app/API Documentations/docs/REACT_INTEGRATION_GUIDE.md deleted file mode 100755 index 29170f9..0000000 --- a/management-dashboard-web-app/API Documentations/docs/REACT_INTEGRATION_GUIDE.md +++ /dev/null @@ -1,276 +0,0 @@ -# 🚀 React Frontend Integration Guide - MP4 Update - -## 🎯 Quick Summary for React Team - -The camera system now records in **MP4 format** instead of AVI. This provides better web compatibility and smaller file sizes. - -## 🔄 What You Need to Update - -### 1. File Extension Handling -```javascript -// OLD: Only checked for .avi -const isVideoFile = (filename) => filename.endsWith('.avi'); - -// NEW: Check for both formats -const isVideoFile = (filename) => { - return filename.endsWith('.mp4') || filename.endsWith('.avi'); -}; - -// Video MIME types -const getVideoMimeType = (filename) => { - if (filename.endsWith('.mp4')) return 'video/mp4'; - if (filename.endsWith('.avi')) return 'video/x-msvideo'; - return 'video/mp4'; // default for new files -}; -``` - -### 2. Video Player Component -```jsx -// MP4 files work better with HTML5 video -const VideoPlayer = ({ videoUrl, filename }) => { - const mimeType = getVideoMimeType(filename); - - return ( - - ); -}; -``` - -### 3. Camera Configuration Interface -Add these new fields to your camera config forms: - -```jsx -const CameraConfigForm = () => { - const [config, setConfig] = useState({ - // ... existing fields - video_format: 'mp4', // 'mp4' or 'avi' - video_codec: 'mp4v', // 'mp4v', 'XVID', 'MJPG' - video_quality: 95 // 0-100 - }); - - return ( -
- {/* ... existing fields */} - -
-

Video Recording Settings

- - - - - - setConfig({...config, video_quality: parseInt(e.target.value)})} - /> - - -
- ⚠️ Video format changes require camera restart -
-
-
- ); -}; -``` - -## 📡 API Response Changes - -### Camera Configuration Response -```json -{ - "name": "camera1", - "machine_topic": "blower_separator", - "storage_path": "/storage/camera1", - "exposure_ms": 0.3, - "gain": 4.0, - "target_fps": 0, - "enabled": true, - "video_format": "mp4", - "video_codec": "mp4v", - "video_quality": 95, - "auto_start_recording_enabled": true, - "auto_recording_max_retries": 3, - "auto_recording_retry_delay_seconds": 2, - - // ... other existing fields -} -``` - -### Video File Listings -```json -{ - "videos": [ - { - "file_id": "camera1_recording_20250804_143022.mp4", - "filename": "camera1_recording_20250804_143022.mp4", - "format": "mp4", - "file_size_bytes": 31457280, - "created_at": "2025-08-04T14:30:22" - } - ] -} -``` - -## 🎨 UI/UX Improvements - -### File Size Display -```javascript -// MP4 files are ~40% smaller -const formatFileSize = (bytes) => { - const mb = bytes / (1024 * 1024); - return `${mb.toFixed(1)} MB`; -}; - -// Show format in file listings -const FileListItem = ({ video }) => ( -
- {video.filename} - - {video.format.toUpperCase()} - - {formatFileSize(video.file_size_bytes)} -
-); -``` - -### Format Indicators -```css -.format.mp4 { - background: #4CAF50; - color: white; - padding: 2px 6px; - border-radius: 3px; - font-size: 0.8em; -} - -.format.avi { - background: #FF9800; - color: white; - padding: 2px 6px; - border-radius: 3px; - font-size: 0.8em; -} -``` - -## ⚡ Performance Benefits - -### Streaming Improvements -- **Faster Loading**: MP4 files start playing sooner -- **Better Seeking**: More responsive video scrubbing -- **Mobile Friendly**: Better iOS/Android compatibility -- **Bandwidth Savings**: 40% smaller files = faster transfers - -### Implementation Tips -```javascript -// Preload video metadata for better UX -const VideoThumbnail = ({ videoUrl }) => ( - -); -``` - -## 🔧 Configuration Management - -### Restart Warning Component -```jsx -const RestartWarning = ({ show }) => { - if (!show) return null; - - return ( -
- ⚠️ Restart Required -

Video format changes require a camera service restart to take effect.

- -
- ); -}; -``` - -### Settings Validation -```javascript -const validateVideoSettings = (settings) => { - const errors = {}; - - if (!['mp4', 'avi'].includes(settings.video_format)) { - errors.video_format = 'Must be mp4 or avi'; - } - - if (!['mp4v', 'XVID', 'MJPG'].includes(settings.video_codec)) { - errors.video_codec = 'Invalid codec'; - } - - if (settings.video_quality < 50 || settings.video_quality > 100) { - errors.video_quality = 'Quality must be between 50-100'; - } - - return errors; -}; -``` - -## 📱 Mobile Considerations - -### Responsive Video Player -```jsx -const ResponsiveVideoPlayer = ({ videoUrl, filename }) => ( -
- -
-); -``` - -## 🧪 Testing Checklist - -- [ ] Video playback works with new MP4 files -- [ ] File extension filtering includes both .mp4 and .avi -- [ ] Camera configuration UI shows video format options -- [ ] Restart warning appears for video format changes -- [ ] File size displays are updated for smaller MP4 files -- [ ] Mobile video playback works correctly -- [ ] Video streaming performance is improved -- [ ] Backward compatibility with existing AVI files - -## 📞 Support - -If you encounter issues: - -1. **Video won't play**: Check browser console for codec errors -2. **File size unexpected**: Verify quality settings in camera config -3. **Streaming slow**: Compare MP4 vs AVI performance -4. **Mobile issues**: Ensure `playsInline` attribute is set - -The MP4 update provides significant improvements in web compatibility and performance while maintaining full backward compatibility with existing AVI files. diff --git a/management-dashboard-web-app/API Documentations/docs/README.md b/management-dashboard-web-app/API Documentations/docs/README.md deleted file mode 100755 index 5ba7b70..0000000 --- a/management-dashboard-web-app/API Documentations/docs/README.md +++ /dev/null @@ -1,100 +0,0 @@ -# USDA Vision Camera System - Documentation - -This directory contains detailed documentation for the USDA Vision Camera System. - -## Documentation Files - -### 🚀 [API_DOCUMENTATION.md](API_DOCUMENTATION.md) **⭐ NEW** -**Complete API reference documentation** covering all endpoints, features, and recent enhancements: -- System status and health monitoring -- Camera management and configuration -- Recording control with dynamic settings -- Auto-recording management -- MQTT and machine status -- Storage and file management -- Camera recovery and diagnostics -- Live streaming capabilities -- WebSocket real-time updates -- Quick start examples and migration notes - -### ⚡ [API_QUICK_REFERENCE.md](API_QUICK_REFERENCE.md) **⭐ NEW** -**Quick reference card** for the most commonly used API endpoints with curl examples and response formats. - -### 📋 [PROJECT_COMPLETE.md](PROJECT_COMPLETE.md) -Complete project overview and final status documentation. Contains: -- Project completion status -- Final system architecture -- Deployment instructions -- Production readiness checklist - -### 🎥 [MP4_FORMAT_UPDATE.md](MP4_FORMAT_UPDATE.md) **⭐ NEW** -**Frontend integration guide** for the MP4 video format update: -- Video format changes from AVI to MP4 -- Frontend implementation checklist -- API response updates -- Performance benefits and browser compatibility - -### 🚀 [REACT_INTEGRATION_GUIDE.md](REACT_INTEGRATION_GUIDE.md) **⭐ NEW** -**Quick reference for React developers** implementing the MP4 format changes: -- Code examples and components -- File handling updates -- Configuration interface -- Testing checklist - -### 📋 [CURRENT_CONFIGURATION.md](CURRENT_CONFIGURATION.md) **⭐ NEW** -**Complete current system configuration reference**: -- Exact config.json structure with all current values -- Field-by-field documentation -- Camera-specific settings comparison -- MQTT topics and machine mappings - -### 🎬 [VIDEO_STREAMING.md](VIDEO_STREAMING.md) **⭐ UPDATED** -**Complete video streaming module documentation**: -- Comprehensive API endpoint documentation -- Authentication and security information -- Error handling and troubleshooting -- Performance optimization guidelines - -### 🤖 [AI_AGENT_VIDEO_INTEGRATION_GUIDE.md](AI_AGENT_VIDEO_INTEGRATION_GUIDE.md) **⭐ NEW** -**Complete integration guide for AI agents and external systems**: -- Step-by-step integration workflow -- Programming language examples (Python, JavaScript) -- Error handling and debugging strategies -- Performance optimization recommendations - -### 🔧 [API_CHANGES_SUMMARY.md](API_CHANGES_SUMMARY.md) -Summary of API changes and enhancements made to the system. - -### 📷 [CAMERA_RECOVERY_GUIDE.md](CAMERA_RECOVERY_GUIDE.md) -Guide for camera recovery procedures and troubleshooting camera-related issues. - -### 📡 [MQTT_LOGGING_GUIDE.md](MQTT_LOGGING_GUIDE.md) -Comprehensive guide for MQTT logging configuration and troubleshooting. - -## Main Documentation - -The main system documentation is located in the root directory: -- **[../README.md](../README.md)** - Primary system documentation with installation, configuration, and usage instructions - -## Additional Resources - -### Demo Code -- **[../demos/](../demos/)** - Demo scripts and camera SDK examples - -### Test Files -- **[../tests/](../tests/)** - Test scripts and legacy test files - -### Jupyter Notebooks -- **[../notebooks/](../notebooks/)** - Interactive notebooks for system exploration and testing - -## Quick Links - -- [System Installation](../README.md#installation) -- [Configuration Guide](../README.md#configuration) -- [API Documentation](../README.md#api-reference) -- [Troubleshooting](../README.md#troubleshooting) -- [Camera SDK Examples](../demos/camera_sdk_examples/) - -## Support - -For technical support and questions, refer to the main [README.md](../README.md) troubleshooting section or check the system logs. diff --git a/management-dashboard-web-app/API Documentations/docs/VIDEO_STREAMING.md b/management-dashboard-web-app/API Documentations/docs/VIDEO_STREAMING.md deleted file mode 100755 index 69b9d6e..0000000 --- a/management-dashboard-web-app/API Documentations/docs/VIDEO_STREAMING.md +++ /dev/null @@ -1,601 +0,0 @@ -# 🎬 Video Streaming Module - -The USDA Vision Camera System now includes a modular video streaming system that provides YouTube-like video playback capabilities for your React web application. - -## 🌟 Features - -- **Progressive Streaming** - True chunked streaming for web browsers (no download required) -- **HTTP Range Request Support** - Enables seeking and progressive download with 206 Partial Content -- **Native MP4 Support** - Direct streaming of MP4 files optimized for web playback -- **Memory Efficient** - 8KB chunked delivery, no large file loading into memory -- **Browser Compatible** - Works with HTML5 `