Jaguar_Project / frontend /src /pages /ControlPanel.js
xenecode's picture
Claude Opus 5.5
Translate frontend and backend text to English
6c68d01
Raw History Blame Contribute Delete
14.8 kB
import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import io from 'socket.io-client';
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { apiService } from '../services/api.service';
import { INTERVALS, API_BASE_URL } from '../constants/api';
import ScanTrace from '../components/ScanTrace';
import ThreeDTrace from '../components/3DTrace';
// If robot_status doesn't arrive within this time, the data on screen is considered "stale"
const STALE_AFTER_MS = 3000;
// If the robot doesn't move for this long and there is no scan, the 3D view switches to the demo motion
const IDLE_DEMO_AFTER_MS = 4000;
const JOINT_MOVE_EPSILON = 0.05; // degrees; don't count controller noise as movement
const JOINT_KEYS = ['j1', 'j2', 'j3', 'j4', 'j5', 'j6'];
const TONE = {
ok: { dot: 'bg-hmi-ok', text: 'text-hmi-ok', border: 'border-hmi-ok' },
err: { dot: 'bg-hmi-err', text: 'text-hmi-err', border: 'border-hmi-err' },
warn: { dot: 'bg-hmi-warn', text: 'text-hmi-warn', border: 'border-hmi-warn' },
accent: { dot: 'bg-hmi-accent', text: 'text-hmi-accent', border: 'border-hmi-accent' },
neutral: { dot: 'bg-hmi-muted', text: 'text-hmi-text', border: 'border-hmi-line' },
};
const POSE_FIELDS = [
{ key: 'x', label: 'X', unit: 'mm' },
{ key: 'y', label: 'Y', unit: 'mm' },
{ key: 'z', label: 'Z', unit: 'mm' },
{ key: 'rx', label: 'RX', unit: '°' },
{ key: 'ry', label: 'RY', unit: '°' },
{ key: 'rz', label: 'RZ', unit: '°' },
];
const BUTTON_BASE =
'flex items-center justify-center gap-2 border-2 px-4 font-semibold uppercase tracking-[0.08em] ' +
'select-none touch-manipulation transition-colors active:translate-y-px disabled:cursor-not-allowed disabled:active:translate-y-0 ' +
'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-hmi-accent';
const OVERLAY_LABEL = 'text-[10px] font-medium uppercase tracking-[0.12em] text-hmi-muted';
const PanelTitle = ({ children, aside }) => (
<div className="flex items-center justify-between px-3 py-2">
<span className="text-xs font-semibold uppercase tracking-[0.14em] text-hmi-muted">{children}</span>
{aside}
</div>
);
const StatusItem = ({ label, value, tone = 'neutral', dimmed = false }) => (
<div className={`flex min-w-0 items-center gap-2 border-l border-hmi-line px-4 first:border-l-0 ${dimmed ? 'opacity-40' : ''}`}>
<span className={`h-2.5 w-2.5 shrink-0 ${TONE[tone].dot}`} aria-hidden="true" />
<span className="whitespace-nowrap text-[11px] font-medium uppercase tracking-[0.12em] text-hmi-muted">{label}</span>
<span className={`truncate font-mono text-sm font-semibold uppercase ${TONE[tone].text}`}>{value}</span>
</div>
);
const formatValue = (value) =>
typeof value === 'number' ? value.toFixed(1) : '—';
const ControlPanel = () => {
const [loading, setLoading] = useState(true);
const [status, setStatus] = useState({});
const [socketConnected, setSocketConnected] = useState(false);
const [lastUpdate, setLastUpdate] = useState(null);
const [lastMove, setLastMove] = useState(0);
const [now, setNow] = useState(Date.now());
const containerRef = useRef();
const readoutRef = useRef();
const lastJointsRef = useRef(null);
// ?demo=0 fully disables the demo motion (e.g. the operator screen on the floor),
// ?demo=1 forces the demo even if the robot is moving (e.g. recording a promo video)
const demoParam = useMemo(
() => new URLSearchParams(window.location.search).get('demo'),
[]
);
// API reachability (used to close the initial loading screen)
const checkApi = useCallback(async () => {
try {
await apiService.getHelloMessage();
} catch (error) {
// Connection status is shown via the socket
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
checkApi();
const intervalId = setInterval(checkApi, INTERVALS.HELLO_MESSAGE);
return () => clearInterval(intervalId);
}, [checkApi]);
// Recalculate data age once per second
useEffect(() => {
const tick = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(tick);
}, []);
// WebSocket connection
useEffect(() => {
const socket = io(API_BASE_URL, {
timeout: 5000,
reconnectionAttempts: 5,
reconnectionDelay: 1000,
transports: ['websocket', 'polling'],
});
socket.on('robot_status', (data) => {
const joints = data?.JOINTS;
const prev = lastJointsRef.current;
if (joints && prev && JOINT_KEYS.some((key) => Math.abs((joints[key] ?? 0) - (prev[key] ?? 0)) > JOINT_MOVE_EPSILON)) {
setLastMove(Date.now());
}
if (joints) lastJointsRef.current = joints;
setStatus(data);
setLastUpdate(Date.now());
setLoading(false);
});
socket.on('connect', () => {
setSocketConnected(true);
toast.dismiss('socket-error');
});
socket.on('connect_error', (err) => {
console.error('WebSocket connection error:', err);
// Don't open a new notification on every retry
toast.error(`Connection error: ${err.message}`, { toastId: 'socket-error' });
setSocketConnected(false);
setLoading(false);
});
socket.on('disconnect', () => {
setSocketConnected(false);
});
return () => {
socket.disconnect();
};
}, []);
const handleStartScan = useCallback(async (altButton = false) => {
try {
const response = await apiService.controlScan({
message: 'START',
alt_button: altButton,
});
if (response.status === 200) {
toast.success(response.data.message);
setStatus((prev) => ({ ...prev, scan_active: true }));
}
} catch (error) {
toast.error(error.message || 'Error occurred while starting the scan');
}
}, []);
const handleStopScan = useCallback(async () => {
try {
await apiService.controlScan({ message: 'STOP' });
setStatus((prev) => ({ ...prev, scan_active: false }));
toast.success('Scan stopped.');
} catch (error) {
toast.error('Error occurred while stopping the scan.');
}
}, []);
if (loading) {
return (
<div className="flex h-[calc(100dvh-3rem)] flex-col items-center justify-center gap-5 bg-hmi-bg font-hmi text-hmi-text">
<div className="h-10 w-10 animate-spin border-4 border-hmi-line border-t-hmi-accent" />
<span className="text-sm font-semibold uppercase tracking-[0.14em] text-hmi-muted">System starting</span>
</div>
);
}
const hasData = lastUpdate !== null;
const ageSeconds = hasData ? Math.max(0, Math.floor((now - lastUpdate) / 1000)) : null;
const live = socketConnected && hasData && now - lastUpdate < STALE_AFTER_MS;
const barrierBlocked = hasData && (!status.DI14 || !status.DI15);
const scanActive = Boolean(status?.scan_active);
const tcp = status?.TCP;
const demo =
demoParam === '1' ||
(demoParam !== '0' && !scanActive && now - lastMove > IDLE_DEMO_AFTER_MS);
let connection;
if (live) {
connection = { value: 'Live', tone: 'ok' };
} else if (!hasData) {
connection = socketConnected
? { value: 'Waiting for data', tone: 'warn' }
: { value: 'No connection', tone: 'err' };
} else {
connection = {
value: `${socketConnected ? 'No data coming in' : 'No connection'} · ${ageSeconds} s`,
tone: 'err',
};
}
let viewMode;
if (demo) {
viewMode = { label: 'Demo motion', tone: 'accent' };
} else if (live && tcp) {
viewMode = { label: 'Live · from robot', tone: 'ok' };
} else {
viewMode = { label: 'No robot data', tone: 'err' };
}
const modeBadge = (
<span className={`inline-flex items-center gap-2 border bg-hmi-bg/80 px-2.5 py-1 font-mono text-xs font-semibold uppercase ${TONE[viewMode.tone].border} ${TONE[viewMode.tone].text}`}>
<span className={`h-2 w-2 ${TONE[viewMode.tone].dot} ${demo || live ? 'animate-pulse' : ''}`} aria-hidden="true" />
{viewMode.label}
</span>
);
return (
<div className="flex min-h-[calc(100dvh-3rem)] flex-col gap-2 bg-hmi-bg px-2 pb-2 pt-2 font-hmi text-hmi-text md:h-[calc(100dvh-3rem)] md:overflow-hidden">
{/* Light barrier: doesn't cover the whole screen, Stop button stays accessible */}
{barrierBlocked && (
<div role="alert" className="flex items-center gap-4 border-2 border-red-400 bg-red-600 px-5 py-3 text-white">
<span className="animate-pulse text-4xl font-black leading-none" aria-hidden="true">⚠</span>
<div>
<div className="text-2xl font-bold uppercase tracking-wide">Light barrier interrupted</div>
<div className="text-base">There is an obstruction in front of the light barrier. Remove the obstruction.</div>
</div>
</div>
)}
{/* Status strip */}
<div className="flex min-h-[44px] flex-wrap items-center gap-y-2 border border-hmi-line bg-hmi-panel py-2">
<StatusItem label="Connection" value={connection.value} tone={connection.tone} />
<StatusItem label="Robot data" value={tcp ? 'Yes' : 'No'} tone={tcp ? 'ok' : 'err'} dimmed={!live} />
<StatusItem label="Part" value={!status?.DI0 ? 'Yes' : 'No'} tone={!status?.DI0 ? 'ok' : 'neutral'} dimmed={!live} />
<StatusItem label="Mode" value={status?.MODE === 0 ? 'Automatic' : 'Manual'} tone={status?.MODE === 0 ? 'accent' : 'warn'} dimmed={!live} />
<StatusItem label="Scan" value={scanActive ? 'Active' : 'Standby'} tone={scanActive ? 'warn' : 'neutral'} dimmed={!live} />
</div>
<div className="grid min-h-0 flex-1 grid-cols-1 gap-2 md:grid-cols-[minmax(0,1fr)_minmax(320px,40%)]">
{/* 3D robot view: the page's main element, so it's clear at a glance this is a robot project */}
<section className="relative h-[60vh] min-h-[320px] overflow-hidden border border-hmi-line bg-hmi-panel md:h-auto">
<div ref={containerRef} className="absolute inset-0" />
<ThreeDTrace
containerRef={containerRef}
joints={status.JOINTS}
demo={demo}
scanActive={scanActive}
partHeld={scanActive && live && !status?.DI0}
readoutRef={readoutRef}
/>
{/* Title */}
<div className="pointer-events-none absolute left-0 top-0 px-4 py-4 sm:px-5">
<div className="mb-1 hidden text-[11px] font-semibold uppercase tracking-[0.18em] text-hmi-accent sm:block">3D robot view</div>
{/* Brand name: capitalized by hand so Turkish uppercasing doesn't turn it into "FAİRİNO" */}
<div lang="en" className="text-3xl font-bold leading-none tracking-[0.06em] md:text-4xl">FAIRINO FR5</div>
<div className="mt-2 max-w-[16rem] text-sm text-hmi-muted sm:max-w-sm">
6-axis collaborative robot · part scanning and measurement with a Mech-Eye LNX-8080 laser profile sensor
</div>
<div className="mt-3 sm:hidden">{modeBadge}</div>
</div>
{/* View status */}
{/* On narrow screens the badge drops below the title, not over the brand name */}
<div className="pointer-events-none absolute right-0 top-0 hidden flex-col items-end gap-1.5 px-4 py-4 sm:flex">
{modeBadge}
<span className="hidden text-[11px] text-hmi-muted [@media(hover:hover)]:block">
Drag: rotate · Wheel: zoom
</span>
</div>
{/* Joint angles (from the visible model) and TCP (from the controller) */}
<div className="pointer-events-none absolute inset-x-0 bottom-0 border-t border-hmi-line bg-hmi-bg/85 font-mono">
<div ref={readoutRef} className="grid grid-cols-6">
{JOINT_KEYS.map((key) => (
<div key={key} className="min-w-0 border-l border-hmi-line px-1.5 py-1.5 first:border-l-0 sm:px-3">
<div className={OVERLAY_LABEL}>{key.toUpperCase()} °</div>
<div data-joint={key} className="truncate text-xs font-semibold tabular-nums sm:text-sm md:text-base">—</div>
</div>
))}
</div>
{demo ? (
<div className="border-t border-hmi-line px-3 py-1.5 font-hmi text-xs text-hmi-muted">
Robot idle: playing demo scan (pick up part, pass through laser, put back). Switches to the live robot once scanning starts.
</div>
) : (
<dl className={`grid grid-cols-6 border-t border-hmi-line ${live ? '' : 'opacity-50'}`}>
{POSE_FIELDS.map(({ key, label, unit }) => (
<div key={key} className="min-w-0 border-l border-hmi-line px-1.5 py-1.5 first:border-l-0 sm:px-3">
<dt className={`${OVERLAY_LABEL} truncate`}>
<span className="hidden sm:inline">TCP </span>{label} {unit}
</dt>
<dd className="truncate text-xs font-semibold tabular-nums sm:text-sm md:text-base">{formatValue(tcp?.[key])}</dd>
</div>
))}
</dl>
)}
</div>
</section>
<div className="flex min-h-0 flex-col gap-2">
{/* Controls */}
<section className="border border-hmi-line bg-hmi-panel">
<PanelTitle>Controls</PanelTitle>
<div className="grid grid-cols-2 gap-2 px-3 pb-3">
<button
type="button"
onClick={() => handleStartScan(true)}
disabled={scanActive}
className={`${BUTTON_BASE} min-h-[64px] border-hmi-ok bg-hmi-ok text-base text-hmi-bg [@media(hover:hover)]:hover:brightness-110 disabled:border-hmi-line disabled:bg-transparent disabled:text-hmi-muted disabled:hover:brightness-100`}
>
<span aria-hidden="true">▶</span> Start
</button>
<button
type="button"
onClick={handleStopScan}
disabled={!scanActive}
className={`${BUTTON_BASE} min-h-[64px] border-red-600 bg-red-600 text-base text-white [@media(hover:hover)]:hover:bg-red-500 disabled:border-dashed disabled:border-hmi-line disabled:bg-transparent disabled:text-hmi-muted`}
>
<span className="h-3.5 w-3.5 bg-current" aria-hidden="true" /> Stop
</button>
</div>
</section>
{/* Scan grid */}
<section className="h-[calc(100vw+96px)] min-h-0 border border-hmi-line bg-hmi-panel md:h-auto md:flex-1">
<ScanTrace />
</section>
</div>
</div>
</div>
);
};
export default ControlPanel;