import React, { useState, useEffect, useCallback } from 'react'; import { apiService } from '../services/api.service'; import { API_BASE_URL } from '../constants/api'; import StatusCard from '../components/StatusCard'; import LoadingSpinner from '../components/LoadingSpinner'; import Button from '../components/Button'; import io from 'socket.io-client'; import { toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import { ToastContainer } from 'react-toastify'; import Config from '../components/Config'; /** * DebugPanel - Component for monitoring and controlling robot systems * Displays real-time robot status and logs through WebSocket connection */ const DebugPanel = () => { // State management const [scanLog, setScanLog] = useState([]); const [status, setStatus] = useState({}); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [airSignalSent, setAirSignalSent] = useState(false); // Connect to WebSocket and fetch logs useEffect(() => { // Initialize socket connection with better error handling const socketConnection = io(API_BASE_URL, { timeout: 5000, // Connection timeout reconnectionAttempts: 5, reconnectionDelay: 1000 }); // Set timeout to exit loading state if no connection const loadingTimeout = setTimeout(() => { if (loading) { setLoading(false); setError("Connection timeout: the server may be unreachable"); } }, 7000); // Socket event handlers socketConnection.on('connect', () => { setError(null); setLoading(false); }); socketConnection.on('robot_status', (data) => { clearTimeout(loadingTimeout); setStatus(data); setLoading(false); setError(null); }); // Fetch scan logs with error handling and timeout const fetchScanLog = async () => { try { const response = await Promise.race([ apiService.getScanLog(), new Promise((_, reject) => setTimeout(() => reject(new Error("Fetch timeout")), 5000) ) ]); // Handle different response formats const logs = response?.logs || response?.data?.logs || []; setScanLog(logs); } catch (err) { console.error("Error fetching logs:", err); // Don't set error state here to avoid UI changes if socket is working } }; fetchScanLog(); // Cleanup function return () => { clearTimeout(loadingTimeout); if (socketConnection) { socketConnection.disconnect(); } }; }, [loading]); // Auto-scroll log container when new logs arrive useEffect(() => { const container = document.getElementById('log-container'); if (container) { container.scrollTop = container.scrollHeight; } }, [scanLog]); // Handle air signal button press with debounce const handleAirSignal = useCallback(async () => { if (airSignalSent) return; // Prevent multiple clicks try { setAirSignalSent(true); // Add timeout to prevent hanging on API call const timeoutPromise = new Promise((_, reject) => { setTimeout(() => reject(new Error("Air signal timeout")), 3000); }); await Promise.race([ apiService.sendAirSignal(), timeoutPromise ]); // Reset button after delay toast.success("Air signal sent"); setTimeout(() => setAirSignalSent(false), 1500); } catch (error) { console.error("Air signal error:", error); toast.error(`Could not send air signal: ${error.message || "Unknown error"}`); setAirSignalSent(false); } }, [airSignalSent]); // Determine log entry styling based on log level const getLogStyle = (logEntry) => { if (logEntry.includes(' - ERROR - ')) return 'text-hmi-err'; if (logEntry.includes(' - WARNING - ')) return 'text-hmi-warn'; return 'text-hmi-text'; }; // Health check function for server connectivity const checkServerHealth = async () => { try { await apiService.getHelloMessage(); return true; } catch (err) { toast.error("Could not communicate with the server. Check the connection."); return false; } }; // Handle manual refresh button const handleRefresh = async () => { const isHealthy = await checkServerHealth(); if (isHealthy) { try { const response = await apiService.getScanLog(); setScanLog(response?.logs || response?.data?.logs || []); toast.success("Logs refreshed"); } catch (err) { toast.error("Could not refresh logs: " + err.message); } } }; // Loading state if (loading) { return ; } // Error state with retry button if (error) { return (
Error
{error}
); } const barrierEmergency = status.DI14 === 0 || status.DI15 === 0; return (
Robot diagnostics
{/* Status Cards */}
{/* Light barrier cards */} {/* Shared emergency card */}
{/* Air Signal Button */}
{/* Log Display */}
Scan logs
{scanLog.length > 0 ? (
              {scanLog.map((log, index) => (
                
{log.trim()}
))}
) : (
No records
)}
); }; export default DebugPanel;