Add comprehensive test suite for USDA Vision Camera System

- Implemented main test script to verify system components and functionality.
- Added individual test scripts for camera exposure settings, API changes, camera recovery, maximum FPS, MQTT events, logging, and timezone functionality.
- Created service file for system management and automatic startup.
- Included detailed logging and error handling in test scripts for better diagnostics.
- Ensured compatibility with existing camera SDK and API endpoints.
This commit is contained in:
Alireza Vaezi
2025-07-28 17:33:49 -04:00
parent 9cb043ef5f
commit 7bc8138f24
72 changed files with 419 additions and 118 deletions

175
docs/API_CHANGES_SUMMARY.md Normal file
View File

@@ -0,0 +1,175 @@
# API Changes Summary: Camera Settings and Filename Handling
## Overview
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

View File

@@ -0,0 +1,158 @@
# Camera Recovery and Diagnostics Guide
This guide explains the new camera recovery functionality implemented in the USDA Vision Camera System API.
## Overview
The system now includes comprehensive camera recovery capabilities to handle connection issues, initialization failures, and other camera-related problems. These features use the underlying mvsdk (python demo) library functions to perform various recovery operations.
## Available Recovery Operations
### 1. Connection Test (`/cameras/{camera_name}/test-connection`)
- **Purpose**: Test if the camera connection is working
- **SDK Function**: `CameraConnectTest()`
- **Use Case**: Diagnose connection issues
- **HTTP Method**: POST
- **Response**: `CameraTestResponse`
### 2. Reconnect (`/cameras/{camera_name}/reconnect`)
- **Purpose**: Soft reconnection to the camera
- **SDK Function**: `CameraReConnect()`
- **Use Case**: Most common fix for connection issues
- **HTTP Method**: POST
- **Response**: `CameraRecoveryResponse`
### 3. Restart Grab (`/cameras/{camera_name}/restart-grab`)
- **Purpose**: Restart the camera grab process
- **SDK Function**: `CameraRestartGrab()`
- **Use Case**: Fix issues with image capture
- **HTTP Method**: POST
- **Response**: `CameraRecoveryResponse`
### 4. Reset Timestamp (`/cameras/{camera_name}/reset-timestamp`)
- **Purpose**: Reset camera timestamp
- **SDK Function**: `CameraRstTimeStamp()`
- **Use Case**: Fix timing-related issues
- **HTTP Method**: POST
- **Response**: `CameraRecoveryResponse`
### 5. Full Reset (`/cameras/{camera_name}/full-reset`)
- **Purpose**: Complete camera reset (uninitialize and reinitialize)
- **SDK Functions**: `CameraUnInit()` + `CameraInit()`
- **Use Case**: Hard reset for persistent issues
- **HTTP Method**: POST
- **Response**: `CameraRecoveryResponse`
### 6. Reinitialize (`/cameras/{camera_name}/reinitialize`)
- **Purpose**: Reinitialize cameras that failed initial setup
- **SDK Functions**: Complete recorder recreation
- **Use Case**: Cameras that never initialized properly
- **HTTP Method**: POST
- **Response**: `CameraRecoveryResponse`
## Recommended Troubleshooting Workflow
When a camera has issues, follow this order:
1. **Test Connection** - Diagnose the problem
```http
POST http://localhost:8000/cameras/camera1/test-connection
```
2. **Try Reconnect** - Most common fix
```http
POST http://localhost:8000/cameras/camera1/reconnect
```
3. **Restart Grab** - If reconnect doesn't work
```http
POST http://localhost:8000/cameras/camera1/restart-grab
```
4. **Full Reset** - For persistent issues
```http
POST http://localhost:8000/cameras/camera1/full-reset
```
5. **Reinitialize** - For cameras that never worked
```http
POST http://localhost:8000/cameras/camera1/reinitialize
```
## Response Format
All recovery operations return structured responses:
### CameraTestResponse
```json
{
"success": true,
"message": "Camera camera1 connection test passed",
"camera_name": "camera1",
"timestamp": "2024-01-01T12:00:00"
}
```
### CameraRecoveryResponse
```json
{
"success": true,
"message": "Camera camera1 reconnected successfully",
"camera_name": "camera1",
"operation": "reconnect",
"timestamp": "2024-01-01T12:00:00"
}
```
## Implementation Details
### CameraRecorder Methods
- `test_connection()`: Tests camera connection
- `reconnect()`: Performs soft reconnection
- `restart_grab()`: Restarts grab process
- `reset_timestamp()`: Resets timestamp
- `full_reset()`: Complete reset with cleanup and reinitialization
### CameraManager Methods
- `test_camera_connection(camera_name)`: Test specific camera
- `reconnect_camera(camera_name)`: Reconnect specific camera
- `restart_camera_grab(camera_name)`: Restart grab for specific camera
- `reset_camera_timestamp(camera_name)`: Reset timestamp for specific camera
- `full_reset_camera(camera_name)`: Full reset for specific camera
- `reinitialize_failed_camera(camera_name)`: Reinitialize failed camera
### State Management
All recovery operations automatically update the camera status in the state manager:
- Success: Status set to "connected"
- Failure: Status set to appropriate error state with error message
## Error Handling
The system includes comprehensive error handling:
- SDK exceptions are caught and logged
- State manager is updated with error information
- Proper HTTP status codes are returned
- Detailed error messages are provided
## Testing
Use the provided test files:
- `api-tests.http`: Manual API testing with VS Code REST Client
- `test_camera_recovery_api.py`: Automated testing script
## Safety Features
- Recording is automatically stopped before recovery operations
- Camera resources are properly cleaned up
- Thread-safe operations with proper locking
- Graceful error handling prevents system crashes
## Common Use Cases
1. **Camera Lost Connection**: Use reconnect
2. **Camera Won't Capture**: Use restart-grab
3. **Camera Initialization Failed**: Use reinitialize
4. **Persistent Issues**: Use full-reset
5. **Timing Problems**: Use reset-timestamp
This recovery system provides robust tools to handle most camera-related issues without requiring system restart or manual intervention.

187
docs/MQTT_LOGGING_GUIDE.md Normal file
View File

@@ -0,0 +1,187 @@
# MQTT Console Logging & API Guide
## 🎯 Overview
Your USDA Vision Camera System now has **enhanced MQTT console logging** and **comprehensive API endpoints** for monitoring machine status via MQTT.
## ✨ What's New
### 1. **Enhanced Console Logging**
- **Colorful emoji-based console output** for all MQTT events
- **Real-time visibility** of MQTT connections, subscriptions, and messages
- **Clear status indicators** for debugging and monitoring
### 2. **New MQTT Status API Endpoint**
- **GET /mqtt/status** - Detailed MQTT client statistics
- **Message counts, error tracking, uptime monitoring**
- **Real-time connection status and broker information**
### 3. **Existing Machine Status APIs** (already available)
- **GET /machines** - All machine states from MQTT
- **GET /system/status** - Overall system status including MQTT
## 🖥️ Console Logging Examples
When you run the system, you'll see:
```bash
🔗 MQTT CONNECTED: 192.168.1.110:1883
📋 MQTT SUBSCRIBED: vibratory_conveyor → vision/vibratory_conveyor/state
📋 MQTT SUBSCRIBED: blower_separator → vision/blower_separator/state
📡 MQTT MESSAGE: vibratory_conveyor → on
📡 MQTT MESSAGE: blower_separator → off
⚠️ MQTT DISCONNECTED: Unexpected disconnection (code: 1)
🔗 MQTT CONNECTED: 192.168.1.110:1883
```
## 🌐 API Endpoints
### MQTT Status
```http
GET http://localhost:8000/mqtt/status
```
**Response:**
```json
{
"connected": true,
"broker_host": "192.168.1.110",
"broker_port": 1883,
"subscribed_topics": [
"vision/vibratory_conveyor/state",
"vision/blower_separator/state"
],
"last_message_time": "2025-07-28T12:00:00",
"message_count": 42,
"error_count": 0,
"uptime_seconds": 3600.5
}
```
### Machine Status
```http
GET http://localhost:8000/machines
```
**Response:**
```json
{
"vibratory_conveyor": {
"name": "vibratory_conveyor",
"state": "on",
"last_updated": "2025-07-28T12:00:00",
"last_message": "on",
"mqtt_topic": "vision/vibratory_conveyor/state"
},
"blower_separator": {
"name": "blower_separator",
"state": "off",
"last_updated": "2025-07-28T12:00:00",
"last_message": "off",
"mqtt_topic": "vision/blower_separator/state"
}
}
```
### System Status
```http
GET http://localhost:8000/system/status
```
**Response:**
```json
{
"system_started": true,
"mqtt_connected": true,
"last_mqtt_message": "2025-07-28T12:00:00",
"machines": { ... },
"cameras": { ... },
"active_recordings": 0,
"total_recordings": 5,
"uptime_seconds": 3600.5
}
```
## 🚀 How to Use
### 1. **Start the Full System**
```bash
python main.py
```
You'll see enhanced console logging for all MQTT events.
### 2. **Test MQTT Demo (MQTT only)**
```bash
python demo_mqtt_console.py
```
Shows just the MQTT client with enhanced logging.
### 3. **Test API Endpoints**
```bash
python test_mqtt_logging.py
```
Tests all the API endpoints and shows expected responses.
### 4. **Query APIs Directly**
```bash
# Check MQTT status
curl http://localhost:8000/mqtt/status
# Check machine states
curl http://localhost:8000/machines
# Check overall system status
curl http://localhost:8000/system/status
```
## 🔧 Configuration
The MQTT settings are in `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"
}
}
}
```
## 🎨 Console Output Features
- **🔗 Connection Events**: Green for successful connections
- **📋 Subscriptions**: Blue for topic subscriptions
- **📡 Messages**: Real-time message display with machine name and payload
- **⚠️ Warnings**: Yellow for unexpected disconnections
- **❌ Errors**: Red for connection failures and errors
- **❓ Unknown Topics**: Purple for unrecognized MQTT topics
## 📊 Monitoring & Debugging
### Real-time Monitoring
- **Console**: Watch live MQTT events as they happen
- **API**: Query `/mqtt/status` for statistics and health
- **Logs**: Check `usda_vision_system.log` for detailed logs
### Troubleshooting
1. **No MQTT messages?** Check broker connectivity and topic configuration
2. **Connection issues?** Verify broker host/port in config.json
3. **API not responding?** Ensure the system is running with `python main.py`
## 🎯 Use Cases
1. **Development**: See MQTT messages in real-time while developing
2. **Debugging**: Identify connection issues and message patterns
3. **Monitoring**: Use APIs to build dashboards or monitoring tools
4. **Integration**: Query machine states from external applications
5. **Maintenance**: Track MQTT statistics and error rates
---
**🎉 Your MQTT monitoring is now fully enhanced with both console logging and comprehensive APIs!**

212
docs/PROJECT_COMPLETE.md Normal file
View File

@@ -0,0 +1,212 @@
# 🎉 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

49
docs/README.md Normal file
View File

@@ -0,0 +1,49 @@
# USDA Vision Camera System - Documentation
This directory contains detailed documentation for the USDA Vision Camera System.
## Documentation Files
### 📋 [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
### 🔧 [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.