Spaces:
Running
Running
Download frontend/src/pages/DebugPanel.js from xenecode/Jaguar_Project: direct link, hf CLI and curl.
- Browser
- Download file 8.67 kB
-
https://huggingface.co/spaces/xenecode/Jaguar_Project/resolve/main/frontend/src/pages/DebugPanel.js
- Command line
-
hf download hf://spaces/xenecode/Jaguar_Project/frontend/src/pages/DebugPanel.js
-
curl -L -o DebugPanel.js https://huggingface.co/spaces/xenecode/Jaguar_Project/resolve/main/frontend/src/pages/DebugPanel.js
8.67 kB
| 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 <LoadingSpinner text="Loading robot status" />; | |
| } | |
| // Error state with retry button | |
| if (error) { | |
| return ( | |
| <div className="flex min-h-[calc(100dvh-3rem)] items-center justify-center bg-hmi-bg px-4 font-hmi text-hmi-text"> | |
| <div className="w-full max-w-lg border-2 border-hmi-err bg-hmi-panel px-6 py-6 text-center"> | |
| <div className="text-xl font-bold uppercase tracking-wide text-hmi-err">Error</div> | |
| <div className="mt-2 text-hmi-text">{error}</div> | |
| <Button | |
| text="Retry" | |
| onClick={() => window.location.reload()} | |
| type="primary" | |
| className="mt-5" | |
| /> | |
| </div> | |
| </div> | |
| ); | |
| } | |
| const barrierEmergency = status.DI14 === 0 || status.DI15 === 0; | |
| return ( | |
| <div className="min-h-[calc(100dvh-3rem)] bg-hmi-bg font-hmi text-hmi-text"> | |
| <ToastContainer | |
| position="bottom-right" | |
| autoClose={3000} | |
| theme="dark" | |
| closeButton={false} | |
| /> | |
| <div className="mx-auto flex max-w-6xl flex-col gap-4 px-4 py-4"> | |
| <div className="flex items-center justify-between"> | |
| <span className="text-lg font-bold uppercase tracking-[0.14em]">Robot diagnostics</span> | |
| <span className="flex items-center gap-2 text-sm"> | |
| <span className="h-2.5 w-2.5 bg-hmi-ok" aria-hidden="true" /> | |
| <span className="font-mono font-semibold uppercase text-hmi-ok">Connected</span> | |
| </span> | |
| </div> | |
| {/* Status Cards */} | |
| <div className="grid grid-cols-2 gap-2 md:grid-cols-3"> | |
| <StatusCard title="Stop (DI8)" value={status.DI8} /> | |
| <StatusCard title="Start (DI9)" value={status.DI9} /> | |
| <StatusCard title="Vacuum (DI0)" value={status.DI0 !== undefined ? 1 - status.DI0 : undefined} /> | |
| <StatusCard title="Scan active" value={status.scan_active} isBoolean={true} /> | |
| <StatusCard title="Monitor active" value={status.monitor_active} isBoolean={true} /> | |
| {/* Light barrier cards */} | |
| <StatusCard title="Light barrier 1 (DI14)" value={status.DI14} /> | |
| <StatusCard title="Light barrier 2 (DI15)" value={status.DI15} /> | |
| {/* Shared emergency card */} | |
| <StatusCard | |
| title="Light barrier emergency" | |
| value={barrierEmergency ? "EMERGENCY" : "OK"} | |
| tone={barrierEmergency ? 'err' : 'ok'} | |
| /> | |
| <StatusCard title="Metal detector (DI4)" value={status.DI4} /> | |
| </div> | |
| {/* Air Signal Button */} | |
| <div> | |
| <Button | |
| text={airSignalSent ? "Signal sent" : "Send air signal"} | |
| onClick={handleAirSignal} | |
| type={airSignalSent ? 'success' : 'primary'} | |
| disabled={airSignalSent} | |
| /> | |
| </div> | |
| {/* Log Display */} | |
| <section className="border border-hmi-line bg-hmi-panel"> | |
| <div className="flex items-center justify-between border-b border-hmi-line px-4 py-2"> | |
| <span className="text-sm font-semibold uppercase tracking-[0.14em]">Scan logs</span> | |
| <Button | |
| text="Refresh" | |
| onClick={handleRefresh} | |
| type="secondary" | |
| /> | |
| </div> | |
| {scanLog.length > 0 ? ( | |
| <pre | |
| id="log-container" | |
| className="max-h-80 overflow-y-auto bg-hmi-bg px-4 py-3 font-mono text-xs leading-relaxed" | |
| > | |
| {scanLog.map((log, index) => ( | |
| <div | |
| key={index} | |
| className={`whitespace-pre-wrap break-words ${getLogStyle(log)}`} | |
| > | |
| {log.trim()} | |
| </div> | |
| ))} | |
| </pre> | |
| ) : ( | |
| <div className="px-4 py-6 text-hmi-muted">No records</div> | |
| )} | |
| </section> | |
| <Config /> | |
| </div> | |
| </div> | |
| ); | |
| }; | |
| export default DebugPanel; | |