Spaces:
Running
Running
File size: 8,674 Bytes
fba4209 6c68d01 fba4209 6c68d01 fba4209 6c68d01 fba4209 b225f7d fba4209 6c68d01 fba4209 6c68d01 fba4209 6c68d01 fba4209 6c68d01 fba4209 b225f7d 6c68d01 b225f7d 6c68d01 b225f7d fba4209 b225f7d fba4209 b225f7d fba4209 b225f7d fba4209 b225f7d fba4209 b225f7d 6c68d01 b225f7d 6c68d01 fba4209 b225f7d 6c68d01 fba4209 6c68d01 fba4209 6c68d01 b225f7d 6c68d01 b225f7d 6c68d01 b225f7d fba4209 b225f7d fba4209 6c68d01 b225f7d fba4209 b225f7d 6c68d01 b225f7d 6c68d01 b225f7d fba4209 b225f7d fba4209 b225f7d fba4209 6c68d01 fba4209 b225f7d fba4209 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 | 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;
|