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 }) => (
{children} {aside}
); const StatusItem = ({ label, value, tone = 'neutral', dimmed = false }) => (
); 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 (
System starting
); } 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 = ( ); return (
{/* Light barrier: doesn't cover the whole screen, Stop button stays accessible */} {barrierBlocked && (
Light barrier interrupted
There is an obstruction in front of the light barrier. Remove the obstruction.
)} {/* Status strip */}
{/* 3D robot view: the page's main element, so it's clear at a glance this is a robot project */}
{/* Title */}
3D robot view
{/* Brand name: capitalized by hand so Turkish uppercasing doesn't turn it into "FAİRİNO" */}
FAIRINO FR5
6-axis collaborative robot · part scanning and measurement with a Mech-Eye LNX-8080 laser profile sensor
{modeBadge}
{/* View status */} {/* On narrow screens the badge drops below the title, not over the brand name */}
{modeBadge} Drag: rotate · Wheel: zoom
{/* Joint angles (from the visible model) and TCP (from the controller) */}
{JOINT_KEYS.map((key) => (
{key.toUpperCase()} °
—
))}
{demo ? (
Robot idle: playing demo scan (pick up part, pass through laser, put back). Switches to the live robot once scanning starts.
) : (
{POSE_FIELDS.map(({ key, label, unit }) => (
TCP {label} {unit}
{formatValue(tcp?.[key])}
))}
)}
{/* Controls */}
Controls
{/* Scan grid */}
); }; export default ControlPanel;