Chore: rename api->camera-management-api and web->management-dashboard-web-app; update compose, ignore, README references
This commit is contained in:
173
camera-management-api/tests/api/test_api_changes.py
Normal file
173
camera-management-api/tests/api/test_api_changes.py
Normal file
@@ -0,0 +1,173 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script to verify the API changes for camera settings and filename handling.
|
||||
"""
|
||||
|
||||
import requests
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
# API base URL
|
||||
BASE_URL = "http://localhost:8000"
|
||||
|
||||
def test_api_endpoint(endpoint, method="GET", data=None):
|
||||
"""Test an API endpoint and return the response"""
|
||||
url = f"{BASE_URL}{endpoint}"
|
||||
|
||||
try:
|
||||
if method == "GET":
|
||||
response = requests.get(url)
|
||||
elif method == "POST":
|
||||
response = requests.post(url, json=data, headers={"Content-Type": "application/json"})
|
||||
|
||||
print(f"\n{method} {endpoint}")
|
||||
print(f"Status: {response.status_code}")
|
||||
|
||||
if response.status_code == 200:
|
||||
result = response.json()
|
||||
print(f"Response: {json.dumps(result, indent=2)}")
|
||||
return result
|
||||
else:
|
||||
print(f"Error: {response.text}")
|
||||
return None
|
||||
|
||||
except requests.exceptions.ConnectionError:
|
||||
print(f"Error: Could not connect to {url}")
|
||||
print("Make sure the API server is running with: python main.py")
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
return None
|
||||
|
||||
def test_camera_recording_with_settings():
|
||||
"""Test camera recording with new settings parameters"""
|
||||
|
||||
print("=" * 60)
|
||||
print("Testing Camera Recording API with New Settings")
|
||||
print("=" * 60)
|
||||
|
||||
# Test 1: Basic recording without settings
|
||||
print("\n1. Testing basic recording (no settings)")
|
||||
basic_request = {
|
||||
"camera_name": "camera1",
|
||||
"filename": "test_basic.avi"
|
||||
}
|
||||
|
||||
result = test_api_endpoint("/cameras/camera1/start-recording", "POST", basic_request)
|
||||
if result and result.get("success"):
|
||||
print("✅ Basic recording started successfully")
|
||||
print(f" Filename: {result.get('filename')}")
|
||||
|
||||
# Stop recording
|
||||
time.sleep(2)
|
||||
test_api_endpoint("/cameras/camera1/stop-recording", "POST")
|
||||
else:
|
||||
print("❌ Basic recording failed")
|
||||
|
||||
# Test 2: Recording with camera settings
|
||||
print("\n2. Testing recording with camera settings")
|
||||
settings_request = {
|
||||
"camera_name": "camera1",
|
||||
"filename": "test_with_settings.avi",
|
||||
"exposure_ms": 2.0,
|
||||
"gain": 4.0,
|
||||
"fps": 5.0
|
||||
}
|
||||
|
||||
result = test_api_endpoint("/cameras/camera1/start-recording", "POST", settings_request)
|
||||
if result and result.get("success"):
|
||||
print("✅ Recording with settings started successfully")
|
||||
print(f" Filename: {result.get('filename')}")
|
||||
|
||||
# Stop recording
|
||||
time.sleep(2)
|
||||
test_api_endpoint("/cameras/camera1/stop-recording", "POST")
|
||||
else:
|
||||
print("❌ Recording with settings failed")
|
||||
|
||||
# Test 3: Recording with only settings (no filename)
|
||||
print("\n3. Testing recording with settings only (no filename)")
|
||||
settings_only_request = {
|
||||
"camera_name": "camera1",
|
||||
"exposure_ms": 1.5,
|
||||
"gain": 3.0,
|
||||
"fps": 7.0
|
||||
}
|
||||
|
||||
result = test_api_endpoint("/cameras/camera1/start-recording", "POST", settings_only_request)
|
||||
if result and result.get("success"):
|
||||
print("✅ Recording with settings only started successfully")
|
||||
print(f" Filename: {result.get('filename')}")
|
||||
|
||||
# Stop recording
|
||||
time.sleep(2)
|
||||
test_api_endpoint("/cameras/camera1/stop-recording", "POST")
|
||||
else:
|
||||
print("❌ Recording with settings only failed")
|
||||
|
||||
# Test 4: Test filename datetime prefix
|
||||
print("\n4. Testing filename datetime prefix")
|
||||
timestamp_before = datetime.now().strftime("%Y%m%d_%H%M")
|
||||
|
||||
filename_test_request = {
|
||||
"camera_name": "camera1",
|
||||
"filename": "my_custom_name.avi"
|
||||
}
|
||||
|
||||
result = test_api_endpoint("/cameras/camera1/start-recording", "POST", filename_test_request)
|
||||
if result and result.get("success"):
|
||||
returned_filename = result.get('filename', '')
|
||||
print(f" Original filename: my_custom_name.avi")
|
||||
print(f" Returned filename: {returned_filename}")
|
||||
|
||||
# Check if datetime prefix was added
|
||||
if timestamp_before in returned_filename and "my_custom_name.avi" in returned_filename:
|
||||
print("✅ Datetime prefix correctly added to filename")
|
||||
else:
|
||||
print("❌ Datetime prefix not properly added")
|
||||
|
||||
# Stop recording
|
||||
time.sleep(2)
|
||||
test_api_endpoint("/cameras/camera1/stop-recording", "POST")
|
||||
else:
|
||||
print("❌ Filename test failed")
|
||||
|
||||
def test_system_status():
|
||||
"""Test basic system status to ensure API is working"""
|
||||
print("\n" + "=" * 60)
|
||||
print("Testing System Status")
|
||||
print("=" * 60)
|
||||
|
||||
# Test system status
|
||||
result = test_api_endpoint("/system/status")
|
||||
if result:
|
||||
print("✅ System status API working")
|
||||
print(f" System started: {result.get('system_started')}")
|
||||
print(f" MQTT connected: {result.get('mqtt_connected')}")
|
||||
else:
|
||||
print("❌ System status API failed")
|
||||
|
||||
# Test camera status
|
||||
result = test_api_endpoint("/cameras")
|
||||
if result:
|
||||
print("✅ Camera status API working")
|
||||
for camera_name, camera_info in result.items():
|
||||
print(f" {camera_name}: {camera_info.get('status')}")
|
||||
else:
|
||||
print("❌ Camera status API failed")
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("USDA Vision Camera System - API Changes Test")
|
||||
print("This script tests the new camera settings parameters and filename handling")
|
||||
print("\nMake sure the system is running with: python main.py")
|
||||
|
||||
# Test system status first
|
||||
test_system_status()
|
||||
|
||||
# Test camera recording with new features
|
||||
test_camera_recording_with_settings()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("Test completed!")
|
||||
print("=" * 60)
|
||||
92
camera-management-api/tests/api/test_camera_recovery_api.py
Normal file
92
camera-management-api/tests/api/test_camera_recovery_api.py
Normal file
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script for camera recovery API endpoints.
|
||||
|
||||
This script tests the new camera recovery functionality without requiring actual cameras.
|
||||
"""
|
||||
|
||||
import requests
|
||||
import json
|
||||
import time
|
||||
from typing import Dict, Any
|
||||
|
||||
# API base URL
|
||||
BASE_URL = "http://localhost:8000"
|
||||
|
||||
def test_endpoint(method: str, endpoint: str, data: Dict[Any, Any] = None) -> Dict[Any, Any]:
|
||||
"""Test an API endpoint and return the response"""
|
||||
url = f"{BASE_URL}{endpoint}"
|
||||
|
||||
try:
|
||||
if method.upper() == "GET":
|
||||
response = requests.get(url, timeout=10)
|
||||
elif method.upper() == "POST":
|
||||
response = requests.post(url, json=data or {}, timeout=10)
|
||||
else:
|
||||
raise ValueError(f"Unsupported method: {method}")
|
||||
|
||||
print(f"\n{method} {endpoint}")
|
||||
print(f"Status: {response.status_code}")
|
||||
|
||||
if response.headers.get('content-type', '').startswith('application/json'):
|
||||
result = response.json()
|
||||
print(f"Response: {json.dumps(result, indent=2)}")
|
||||
return result
|
||||
else:
|
||||
print(f"Response: {response.text}")
|
||||
return {"text": response.text}
|
||||
|
||||
except requests.exceptions.ConnectionError:
|
||||
print(f"❌ Connection failed - API server not running at {BASE_URL}")
|
||||
return {"error": "connection_failed"}
|
||||
except requests.exceptions.Timeout:
|
||||
print(f"❌ Request timeout")
|
||||
return {"error": "timeout"}
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
return {"error": str(e)}
|
||||
|
||||
def main():
|
||||
"""Test camera recovery API endpoints"""
|
||||
print("🔧 Testing Camera Recovery API Endpoints")
|
||||
print("=" * 50)
|
||||
|
||||
# Test basic endpoints first
|
||||
print("\n📋 BASIC API TESTS")
|
||||
test_endpoint("GET", "/health")
|
||||
test_endpoint("GET", "/cameras")
|
||||
|
||||
# Test camera recovery endpoints
|
||||
print("\n🔧 CAMERA RECOVERY TESTS")
|
||||
|
||||
camera_names = ["camera1", "camera2"]
|
||||
|
||||
for camera_name in camera_names:
|
||||
print(f"\n--- Testing {camera_name} ---")
|
||||
|
||||
# Test connection
|
||||
test_endpoint("POST", f"/cameras/{camera_name}/test-connection")
|
||||
|
||||
# Test reconnect
|
||||
test_endpoint("POST", f"/cameras/{camera_name}/reconnect")
|
||||
|
||||
# Test restart grab
|
||||
test_endpoint("POST", f"/cameras/{camera_name}/restart-grab")
|
||||
|
||||
# Test reset timestamp
|
||||
test_endpoint("POST", f"/cameras/{camera_name}/reset-timestamp")
|
||||
|
||||
# Test full reset
|
||||
test_endpoint("POST", f"/cameras/{camera_name}/full-reset")
|
||||
|
||||
# Test reinitialize
|
||||
test_endpoint("POST", f"/cameras/{camera_name}/reinitialize")
|
||||
|
||||
time.sleep(0.5) # Small delay between tests
|
||||
|
||||
print("\n✅ Camera recovery API tests completed!")
|
||||
print("\nNote: Some operations may fail if cameras are not connected,")
|
||||
print("but the API endpoints should respond with proper error messages.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
168
camera-management-api/tests/api/test_mqtt_events_api.py
Normal file
168
camera-management-api/tests/api/test_mqtt_events_api.py
Normal file
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script for MQTT events API endpoint
|
||||
|
||||
This script tests the new MQTT events history functionality by:
|
||||
1. Starting the system components
|
||||
2. Simulating MQTT messages
|
||||
3. Testing the API endpoint to retrieve events
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
import requests
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
# Test configuration
|
||||
API_BASE_URL = "http://localhost:8000"
|
||||
MQTT_EVENTS_ENDPOINT = f"{API_BASE_URL}/mqtt/events"
|
||||
|
||||
def test_api_endpoint():
|
||||
"""Test the MQTT events API endpoint"""
|
||||
print("🧪 Testing MQTT Events API Endpoint")
|
||||
print("=" * 50)
|
||||
|
||||
try:
|
||||
# Test basic endpoint
|
||||
print("📡 Testing GET /mqtt/events (default limit=5)")
|
||||
response = requests.get(MQTT_EVENTS_ENDPOINT)
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
print(f"✅ API Response successful")
|
||||
print(f"📊 Total events: {data.get('total_events', 0)}")
|
||||
print(f"📋 Events returned: {len(data.get('events', []))}")
|
||||
|
||||
if data.get('events'):
|
||||
print(f"🕐 Last updated: {data.get('last_updated')}")
|
||||
print("\n📝 Recent events:")
|
||||
for i, event in enumerate(data['events'], 1):
|
||||
timestamp = datetime.fromisoformat(event['timestamp']).strftime('%H:%M:%S')
|
||||
print(f" {i}. [{timestamp}] {event['machine_name']}: {event['payload']} -> {event['normalized_state']}")
|
||||
else:
|
||||
print("📭 No events found")
|
||||
|
||||
else:
|
||||
print(f"❌ API Error: {response.status_code}")
|
||||
print(f" Response: {response.text}")
|
||||
|
||||
except requests.exceptions.ConnectionError:
|
||||
print("❌ Connection Error: API server not running")
|
||||
print(" Start the system first: python -m usda_vision_system.main")
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
|
||||
print()
|
||||
|
||||
# Test with custom limit
|
||||
try:
|
||||
print("📡 Testing GET /mqtt/events?limit=10")
|
||||
response = requests.get(f"{MQTT_EVENTS_ENDPOINT}?limit=10")
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
print(f"✅ API Response successful")
|
||||
print(f"📋 Events returned: {len(data.get('events', []))}")
|
||||
else:
|
||||
print(f"❌ API Error: {response.status_code}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
|
||||
def test_system_status():
|
||||
"""Test system status to verify API is running"""
|
||||
print("🔍 Checking System Status")
|
||||
print("=" * 50)
|
||||
|
||||
try:
|
||||
response = requests.get(f"{API_BASE_URL}/system/status")
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
print(f"✅ System Status: {'Running' if data.get('system_started') else 'Not Started'}")
|
||||
print(f"🔗 MQTT Connected: {'Yes' if data.get('mqtt_connected') else 'No'}")
|
||||
print(f"📡 Last MQTT Message: {data.get('last_mqtt_message', 'None')}")
|
||||
print(f"⏱️ Uptime: {data.get('uptime_seconds', 0):.1f} seconds")
|
||||
return True
|
||||
else:
|
||||
print(f"❌ System Status Error: {response.status_code}")
|
||||
return False
|
||||
|
||||
except requests.exceptions.ConnectionError:
|
||||
print("❌ Connection Error: API server not running")
|
||||
print(" Start the system first: python -m usda_vision_system.main")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
return False
|
||||
|
||||
def test_mqtt_status():
|
||||
"""Test MQTT status"""
|
||||
print("📡 Checking MQTT Status")
|
||||
print("=" * 50)
|
||||
|
||||
try:
|
||||
response = requests.get(f"{API_BASE_URL}/mqtt/status")
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
print(f"🔗 MQTT Connected: {'Yes' if data.get('connected') else 'No'}")
|
||||
print(f"🏠 Broker: {data.get('broker_host')}:{data.get('broker_port')}")
|
||||
print(f"📋 Subscribed Topics: {len(data.get('subscribed_topics', []))}")
|
||||
print(f"📊 Message Count: {data.get('message_count', 0)}")
|
||||
print(f"❌ Error Count: {data.get('error_count', 0)}")
|
||||
|
||||
if data.get('subscribed_topics'):
|
||||
print("📍 Topics:")
|
||||
for topic in data['subscribed_topics']:
|
||||
print(f" - {topic}")
|
||||
|
||||
return True
|
||||
else:
|
||||
print(f"❌ MQTT Status Error: {response.status_code}")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
return False
|
||||
|
||||
def main():
|
||||
"""Main test function"""
|
||||
print("🧪 MQTT Events API Test")
|
||||
print("=" * 60)
|
||||
print(f"🎯 API Base URL: {API_BASE_URL}")
|
||||
print(f"📡 Events Endpoint: {MQTT_EVENTS_ENDPOINT}")
|
||||
print()
|
||||
|
||||
# Test system status first
|
||||
if not test_system_status():
|
||||
print("\n❌ System not running. Please start the system first:")
|
||||
print(" python -m usda_vision_system.main")
|
||||
return
|
||||
|
||||
print()
|
||||
|
||||
# Test MQTT status
|
||||
if not test_mqtt_status():
|
||||
print("\n❌ MQTT not available")
|
||||
return
|
||||
|
||||
print()
|
||||
|
||||
# Test the events API
|
||||
test_api_endpoint()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("🎯 Test Instructions:")
|
||||
print("1. Make sure the system is running")
|
||||
print("2. Turn machines on/off to generate MQTT events")
|
||||
print("3. Run this test again to see the events")
|
||||
print("4. Check the admin dashboard to see events displayed")
|
||||
print()
|
||||
print("📋 API Usage:")
|
||||
print(f" GET {MQTT_EVENTS_ENDPOINT}")
|
||||
print(f" GET {MQTT_EVENTS_ENDPOINT}?limit=10")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user