Files
Traffic-Intersection-Monito…/qt_app_pyside1/check_system_status.py
2025-08-26 13:24:53 -07:00

326 lines
14 KiB
Python

#!/usr/bin/env python3
"""
Complete Smart Intersection System Status Checker
Comprehensive status check for MQTT, InfluxDB, and Grafana
"""
import subprocess
import socket
import time
import json
from datetime import datetime
import sys
import os
class SmartIntersectionSystemChecker:
def __init__(self):
self.services = {
'mqtt': {'port': 1883, 'name': 'MQTT Broker (Mosquitto)', 'status': 'unknown'},
'influxdb': {'port': 8086, 'name': 'InfluxDB', 'status': 'unknown'},
'grafana': {'port': 3000, 'name': 'Grafana', 'status': 'unknown'}
}
self.system_status = {}
def check_port_listening(self, port, host='localhost'):
"""Check if a port is listening"""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
result = sock.connect_ex((host, port))
sock.close()
return result == 0
except:
return False
def check_process_running(self, process_names):
"""Check if any of the given processes are running"""
try:
if sys.platform == "win32":
# Windows
output = subprocess.check_output('tasklist', shell=True, text=True)
for process_name in process_names:
if process_name.lower() in output.lower():
return True
else:
# Linux/Unix
output = subprocess.check_output(['ps', 'aux'], text=True)
for process_name in process_names:
if process_name in output:
return True
return False
except:
return False
def get_system_info(self):
"""Get basic system information"""
try:
if sys.platform == "win32":
# Windows system info
hostname = subprocess.check_output('hostname', shell=True, text=True).strip()
os_info = subprocess.check_output('ver', shell=True, text=True).strip()
else:
# Linux system info
hostname = subprocess.check_output(['hostname'], text=True).strip()
os_info = subprocess.check_output(['uname', '-a'], text=True).strip()
self.system_status = {
'hostname': hostname,
'os_info': os_info,
'timestamp': datetime.now().isoformat(),
'platform': sys.platform
}
except:
self.system_status = {
'hostname': 'unknown',
'os_info': 'unknown',
'timestamp': datetime.now().isoformat(),
'platform': sys.platform
}
def check_service_status(self):
"""Check status of all services"""
print(f"🔍 CHECKING SERVICE STATUS...")
print(f"{'='*50}")
# Check MQTT
print(f"📡 Checking MQTT Broker (port 1883)...")
if self.check_port_listening(1883):
self.services['mqtt']['status'] = 'running'
print(f" ✅ MQTT Broker is RUNNING")
else:
self.services['mqtt']['status'] = 'stopped'
print(f" ❌ MQTT Broker is NOT RUNNING")
# Check InfluxDB
print(f"📊 Checking InfluxDB (port 8086)...")
if self.check_port_listening(8086):
self.services['influxdb']['status'] = 'running'
print(f" ✅ InfluxDB is RUNNING")
else:
self.services['influxdb']['status'] = 'stopped'
print(f" ❌ InfluxDB is NOT RUNNING")
# Check Grafana
print(f"📈 Checking Grafana (port 3000)...")
if self.check_port_listening(3000):
self.services['grafana']['status'] = 'running'
print(f" ✅ Grafana is RUNNING")
else:
self.services['grafana']['status'] = 'stopped'
print(f" ❌ Grafana is NOT RUNNING")
def check_service_processes(self):
"""Check if service processes are running"""
print(f"\n🔍 CHECKING SERVICE PROCESSES...")
print(f"{'='*40}")
process_checks = {
'MQTT': ['mosquitto', 'mosquitto.exe'],
'InfluxDB': ['influxd', 'influxd.exe', 'influxdb'],
'Grafana': ['grafana-server', 'grafana-server.exe', 'grafana']
}
for service_name, process_names in process_checks.items():
if self.check_process_running(process_names):
print(f"{service_name} process is running")
else:
print(f"{service_name} process not found")
def generate_service_urls(self):
"""Generate service access URLs"""
print(f"\n🌐 SERVICE ACCESS URLS:")
print(f"{'='*30}")
running_services = []
for service_key, service_info in self.services.items():
if service_info['status'] == 'running':
if service_key == 'mqtt':
print(f"📡 MQTT Broker: mqtt://localhost:1883")
print(f" - Use MQTT client to connect")
print(f" - Topics: smart-intersection/*")
running_services.append('MQTT')
elif service_key == 'influxdb':
print(f"📊 InfluxDB UI: http://localhost:8086")
print(f" - API: http://localhost:8086/api/v2")
print(f" - Organization: smart-intersection-org")
running_services.append('InfluxDB')
elif service_key == 'grafana':
print(f"📈 Grafana Dashboard: http://localhost:3000")
print(f" - Username: admin / Password: admin")
print(f" - API: http://localhost:3000/api")
running_services.append('Grafana')
return running_services
def check_service_connectivity(self):
"""Test connectivity to running services"""
print(f"\n🔗 TESTING SERVICE CONNECTIVITY:")
print(f"{'='*40}")
for service_key, service_info in self.services.items():
if service_info['status'] == 'running':
port = service_info['port']
name = service_info['name']
print(f"🔌 Testing {name}...")
# Test basic TCP connection
if self.check_port_listening(port):
print(f" ✅ TCP connection successful")
# Service-specific tests
if service_key == 'mqtt':
print(f" 📡 MQTT: Ready for pub/sub operations")
elif service_key == 'influxdb':
print(f" 📊 InfluxDB: HTTP API accessible")
elif service_key == 'grafana':
print(f" 📈 Grafana: Web interface accessible")
else:
print(f" ❌ TCP connection failed")
def provide_troubleshooting_tips(self):
"""Provide troubleshooting tips for failed services"""
print(f"\n🔧 TROUBLESHOOTING GUIDE:")
print(f"{'='*40}")
failed_services = [k for k, v in self.services.items() if v['status'] != 'running']
if not failed_services:
print(f"✅ All services are running properly!")
return
for service in failed_services:
if service == 'mqtt':
print(f"\n📡 MQTT Broker (Mosquitto) not running:")
print(f" 1. Start services: run 'start_services.bat'")
print(f" 2. Check if Mosquitto is installed")
print(f" 3. Check port 1883 is not blocked")
print(f" 4. Review Mosquitto logs")
elif service == 'influxdb':
print(f"\n📊 InfluxDB not running:")
print(f" 1. Start services: run 'start_services.bat'")
print(f" 2. Check if InfluxDB executable exists")
print(f" 3. Check port 8086 is not blocked")
print(f" 4. Review InfluxDB logs")
print(f" 5. Check disk space for database")
elif service == 'grafana':
print(f"\n📈 Grafana not running:")
print(f" 1. Start services: run 'start_services.bat'")
print(f" 2. Check if Grafana executable exists")
print(f" 3. Check port 3000 is not blocked")
print(f" 4. Review Grafana logs")
print(f" 5. Check configuration files")
def explain_system_architecture(self):
"""Explain how the components interact"""
print(f"\n🏗️ SYSTEM ARCHITECTURE OVERVIEW:")
print(f"{'='*50}")
print(f"""
🚦 Smart Intersection Traffic Monitoring System
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Qt Desktop │ │ MQTT Broker │ │ InfluxDB │
│ App │◄──►│ (Mosquitto) │◄──►│ (Time Series) │
│ │ │ │ │ │
│ • Video Analysis│ │ • Message Queue │ │ • Data Storage │
│ • Detection │ │ • Pub/Sub │ │ • Measurements │
│ • VLM Insights │ │ • Real-time │ │ • Retention │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
│ ┌─────────────────┐ │
└──────────────►│ Grafana │◄─────────────┘
│ (Dashboards) │
│ │
│ • Visualization │
│ • Alerts │
│ • Analytics │
└─────────────────┘
📊 DATA FLOW:
1. Qt App detects vehicles/violations → MQTT topics
2. MQTT Broker routes messages → InfluxDB via Telegraf
3. InfluxDB stores time-series data
4. Grafana queries InfluxDB → Real-time dashboards
📡 MQTT TOPICS:
• smart-intersection/camera-{id}/detection/vehicles
• smart-intersection/camera-{id}/violation/red-light
• smart-intersection/camera-{id}/performance/fps
• smart-intersection/camera-{id}/status/health
📊 INFLUXDB MEASUREMENTS:
• detection_events (vehicle counts, types)
• violation_events (red light, crosswalk)
• performance_metrics (fps, processing time)
• device_status (health, uptime)
""")
def run_comprehensive_check(self):
"""Run complete system status check"""
print(f"🚦 SMART INTERSECTION SYSTEM STATUS CHECKER")
print(f"{'='*60}")
print(f"Check Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
# Get system info
self.get_system_info()
print(f"Hostname: {self.system_status['hostname']}")
print(f"Platform: {self.system_status['platform']}")
# Check all services
self.check_service_status()
self.check_service_processes()
# Generate URLs for running services
running_services = self.generate_service_urls()
# Test connectivity
self.check_service_connectivity()
# Show architecture
self.explain_system_architecture()
# Provide troubleshooting
self.provide_troubleshooting_tips()
# Summary
print(f"\n📋 SYSTEM STATUS SUMMARY:")
print(f"{'='*40}")
total_services = len(self.services)
running_count = len([s for s in self.services.values() if s['status'] == 'running'])
print(f"🔢 Services Status: {running_count}/{total_services} running")
print(f"✅ Running: {', '.join(running_services) if running_services else 'None'}")
failed_services = [v['name'] for v in self.services.values() if v['status'] != 'running']
if failed_services:
print(f"❌ Failed: {', '.join(failed_services)}")
if running_count == total_services:
print(f"\n🎉 ALL SERVICES ARE HEALTHY!")
print(f"🚀 Your Smart Intersection system is ready!")
else:
print(f"\n⚠️ Some services need attention")
print(f"💡 Run 'start_services.bat' to start all services")
def main():
"""Main function"""
checker = SmartIntersectionSystemChecker()
checker.run_comprehensive_check()
print(f"\n🔧 QUICK COMMANDS:")
print(f"{'-'*25}")
print(f"Start all services:")
print(f" > cd services/scripts")
print(f" > start_services.bat")
print(f"")
print(f"Check individual components:")
print(f" > python check_mqtt_status.py")
print(f" > python check_influxdb_status.py")
print(f" > python check_grafana_status.py")
if __name__ == "__main__":
main()