机器状态页面 样式优化 对接新的 设备状态数据 ,xbox和 方向盘 需要 互斥控制 中英文优化,方向盘加入 点火熄火等功能,等待对接状态和远程控制和倒车影像

This commit is contained in:
mmc
2026-10-21 14:51:27 +08:00
parent 1034b6dbf8
commit 2758dd9643
8 changed files with 2312 additions and 617 deletions

View File

@@ -1,6 +1,6 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronUp, ChevronDown, ChevronLeft, ChevronRight, Circle } from 'lucide-react';
import { ChevronUp, ChevronDown, ChevronLeft, ChevronRight, Circle, ShieldAlert } from 'lucide-react';
export interface GamepadState {
buttons: boolean[];
@@ -13,6 +13,7 @@ interface DPadControlProps {
onGamepadUpdate?: (state: GamepadState) => void;
onSpeedChange?: (speed: number) => void;
disabled?: boolean;
onEmergencyStop?: () => void;
}
// 键盘按键映射
@@ -31,7 +32,7 @@ const KEY_MAP: Record<string, string> = {
D: 'right',
};
const DPadControl: React.FC<DPadControlProps> = ({ onGamepadUpdate, onSpeedChange, disabled = false }) => {
const DPadControl: React.FC<DPadControlProps> = ({ onGamepadUpdate, onSpeedChange, disabled = false, onEmergencyStop }) => {
const { t } = useTranslation();
const [pressed, setPressed] = useState<Record<string, boolean>>({});
const [speed, setSpeed] = useState(0.5);
@@ -181,6 +182,29 @@ const DPadControl: React.FC<DPadControlProps> = ({ onGamepadUpdate, onSpeedChang
</button>
);
const startEmergency = () => {
if (disabled) return;
pressedRef.current = { ...pressedRef.current, center: true };
setPressed(pressedRef.current);
onEmergencyStop?.();
window.setTimeout(() => {
pressedRef.current = { ...pressedRef.current, center: false };
setPressed(pressedRef.current);
}, 350);
};
const renderEmergency = () => (
<button
aria-label={t('devices.emergencyStop')}
disabled={disabled}
className={`${btnBase} ${pressed.center ? 'border-red-500 bg-red-500/40 text-white shadow-[0_0_16px_rgba(239,68,68,0.6)]' : 'border-red-500/70 bg-red-500/10 text-red-400 hover:bg-red-500/20'} ${disabled ? 'opacity-40 cursor-not-allowed' : 'cursor-pointer'}`}
onClick={() => startEmergency()}
onTouchStart={(e) => { e.preventDefault(); startEmergency(); }}
>
<ShieldAlert className="w-5 h-5" />
</button>
);
return (
<div className="flex flex-col items-center gap-1 w-full">
{/* 十字方向键 */}
@@ -189,7 +213,7 @@ const DPadControl: React.FC<DPadControlProps> = ({ onGamepadUpdate, onSpeedChang
{renderBtn('up', <ChevronUp className="w-6 h-6" />, t('devices.dpad.up'))}
<div />
{renderBtn('left', <ChevronLeft className="w-6 h-6" />, t('devices.dpad.left'))}
{renderBtn('center', <Circle className="w-5 h-5 fill-current" />, t('devices.dpad.center'))}
{onEmergencyStop ? renderEmergency() : renderBtn('center', <Circle className="w-5 h-5 fill-current" />, t('devices.dpad.center'))}
{renderBtn('right', <ChevronRight className="w-6 h-6" />, t('devices.dpad.right'))}
<div />
{renderBtn('down', <ChevronDown className="w-6 h-6" />, t('devices.dpad.down'))}

File diff suppressed because it is too large Load Diff

View File

@@ -20,7 +20,6 @@ export type RobotFeature =
| 'findCar'
| 'autoback';
export interface FeatureConfig {
key: RobotFeature;
icon: React.ReactNode;
@@ -28,71 +27,86 @@ export interface FeatureConfig {
inactiveColor: string;
}
// 功能方块:方块样式展示,不再包含急停(急停已移至方向盘中键)
const FEATURES: FeatureConfig[] = [
{ key: 'emergencyStop', icon: <ShieldAlert className="w-5 h-5" />, activeColor: '#ef4444', inactiveColor: '#94a3b8' },
{ key: 'obstacleAvoidance', icon: <Siren className="w-5 h-5" />, activeColor: '#3b82f6', inactiveColor: '#94a3b8' },
{ key: 'lowBatteryReturn', icon: <BatteryWarning className="w-5 h-5" />, activeColor: '#f59e0b', inactiveColor: '#94a3b8' },
{ key: 'tiltProtection', icon: <MoveVertical className="w-5 h-5" />, activeColor: '#10b981', inactiveColor: '#94a3b8' },
//{ key: 'findCar', icon: <Zap className="w-5 h-5" />, activeColor: '#22c55e', inactiveColor: '#c4158c' },
{ key: 'autoback', icon: <Zap className="w-5 h-5" />, activeColor: '#22c55e', inactiveColor: '#133c75' },
{ key: 'obstacleAvoidance', icon: <Siren className="w-6 h-6" />, activeColor: '#3b82f6', inactiveColor: '#94a3b8' },
{ key: 'lowBatteryReturn', icon: <BatteryWarning className="w-6 h-6" />, activeColor: '#f59e0b', inactiveColor: '#94a3b8' },
{ key: 'tiltProtection', icon: <MoveVertical className="w-6 h-6" />, activeColor: '#10b981', inactiveColor: '#94a3b8' },
{ key: 'autoback', icon: <Zap className="w-6 h-6" />, activeColor: '#22c55e', inactiveColor: '#94a3b8' },
{ key: 'findCar', icon: <ShieldAlert className="w-6 h-6" />, activeColor: '#ef4444', inactiveColor: '#94a3b8' },
];
// 急停方块(仅在 showEmergencyStop 时展示,兼容其他页面)
const EMERGENCY: FeatureConfig = {
key: 'emergencyStop',
icon: <ShieldAlert className="w-6 h-6" />,
activeColor: '#ef4444',
inactiveColor: '#ef4444',
};
interface RobotFeatureButtonsProps {
activeFeatures?: RobotFeature[];
onToggle?: (feature: RobotFeature, enabled: boolean) => void;
className?: string;
showEmergencyStop?: boolean;
sendFindCar: () => {}
}
const RobotFeatureButtons: React.FC<RobotFeatureButtonsProps> = ({
activeFeatures = [],
onToggle,
className = '',
showEmergencyStop = true,
sendFindCar,
}) => {
const { t } = useTranslation();
const { userInfo } = useSelector((state: RootState) => state.user);
const [active, setActive] = useState<Set<RobotFeature>>(new Set(activeFeatures));
const list = showEmergencyStop ? [EMERGENCY, ...FEATURES] : FEATURES;
const handleClick = (feature: RobotFeature) => {
// 急停:点击时直接下发 button7(绕过控制权限校验)
if (feature === 'emergencyStop') {
sendEmergencyStop(userInfo);
onToggle?.(feature, true);
return;
}
// 寻车:下发指令的同时,与其他功能一样切换选中状态(toggle 效果)
if (feature === 'findCar') {
sendFindCar?.();
}
const next = !active.has(feature);
const nextSet = new Set(active);
if (next) nextSet.add(feature);
else nextSet.delete(feature);
setActive(nextSet);
// 急停:点击时直接下发 button7(绕过控制权限校验)
if (feature === 'emergencyStop') sendEmergencyStop(userInfo);
onToggle?.(feature, next);
};
return (
<div className={`flex flex-wrap gap-2 ${className}`}>
{FEATURES.map((f) => {
<div className={`flex gap-2 w-full ${className}`}>
{list.map((f) => {
const isActive = active.has(f.key);
return (
<button
key={f.key}
onClick={() => handleClick(f.key)}
className={`flex items-center gap-1 px-1 py-1 rounded-lg border transition-all duration-200 select-none
${isActive
? 'border-current shadow-lg'
: 'border-slate-700 hover:border-slate-500'
}`}
className="flex flex-col items-center justify-center gap-1.5 rounded-lg border transition-all duration-200 select-none hover:shadow-md"
style={{
aspectRatio: '1 / 1',
height: 64,
color: isActive ? f.activeColor : f.inactiveColor,
backgroundColor: isActive ? `${f.activeColor}1a` : 'transparent',
backgroundColor: isActive ? `${f.activeColor}1a` : '#fafafa',
borderColor: isActive ? f.activeColor : '#e5e7eb',
boxShadow: isActive ? `0 0 12px ${f.activeColor}33` : 'none',
}}
title={t(`devices.features.${f.key}`)}
>
<span className="flex items-center justify-center">{f.icon}</span>
<span className="text-xs font-medium whitespace-nowrap">
<span className="text-xs font-medium text-center leading-tight px-1" style={{ color: isActive ? f.activeColor : '#595959' }}>
{t(`devices.features.${f.key}`)}
</span>
<span
className="ml-1 w-2 h-2 rounded-full transition-all"
style={{ backgroundColor: isActive ? f.activeColor : '#475569' }}
/>
</button>
);
})}

View File

@@ -0,0 +1,153 @@
import { useCallback, useEffect, useRef, useState } from 'react';
interface SteerButtonProps {
icon: React.ReactNode;
label: string;
color: string;
onPressStart?: () => void;
onPressEnd?: () => void;
interval?: number;
}
const SteerButton = ({
icon,
label,
color,
onPressStart,
onPressEnd,
interval = 100,
}: SteerButtonProps) => {
const [pressed, setPressed] = useState(false);
// 是否处于按下状态
const holdingRef = useRef(false);
// 定时发送句柄
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// 保存最新的回调,避免定时器使用过期闭包
const onPressStartRef = useRef(onPressStart);
const onPressEndRef = useRef(onPressEnd);
useEffect(() => {
onPressStartRef.current = onPressStart;
}, [onPressStart]);
useEffect(() => {
onPressEndRef.current = onPressEnd;
}, [onPressEnd]);
// 停止长按
const stopHold = useCallback(() => {
if (!holdingRef.current) return;
holdingRef.current = false;
if (timerRef.current !== null) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
setPressed(false);
// 只在有效按压结束时发送一次释放数据
onPressEndRef.current?.();
}, []);
// 开始长按
const startHold = useCallback(() => {
// 防止重复触发
if (holdingRef.current) return;
holdingRef.current = true;
setPressed(true);
// 立即发送第一帧
onPressStartRef.current?.();
// 持续发送
const scheduleNext = () => {
if (!holdingRef.current) return;
timerRef.current = setTimeout(() => {
if (!holdingRef.current) return;
onPressStartRef.current?.();
scheduleNext();
}, interval);
};
scheduleNext();
}, [interval]);
// 组件卸载时清理定时器
useEffect(() => {
return () => {
holdingRef.current = false;
if (timerRef.current !== null) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
};
}, []);
return (
<button
type="button"
aria-label={label}
aria-pressed={pressed}
onPointerDown={(e) => {
e.preventDefault();
e.stopPropagation();
// 仅响应鼠标左键,触摸和笔不受影响
if (e.pointerType === 'mouse' && e.button !== 0) return;
// 捕获指针,确保在按钮外松开也能收到事件
e.currentTarget.setPointerCapture(e.pointerId);
startHold();
}}
onPointerUp={(e) => {
e.preventDefault();
e.stopPropagation();
stopHold();
}}
onPointerCancel={stopHold}
onLostPointerCapture={stopHold}
onContextMenu={(e) => e.preventDefault()}
style={{
flex: '1 1 0',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
gap: 4,
minHeight: 46,
padding: '6px 4px',
borderRadius: 8,
background: pressed ? `${color}30` : '#1e293b',
border: `1px solid ${pressed ? color : `${color}55`}`,
color,
cursor: 'pointer',
userSelect: 'none',
touchAction: 'none',
transform: pressed ? 'scale(0.94)' : 'scale(1)',
boxShadow: pressed ? `0 0 14px ${color}66` : 'none',
transition:
'transform .08s, background .12s, border-color .12s, box-shadow .12s',
}}
>
<span style={{ display: 'inline-flex', fontSize: 16, lineHeight: 1 }}>
{icon}
</span>
<span style={{ fontSize: 11, fontWeight: 600, whiteSpace: 'nowrap' }}>
{label}
</span>
</button>
);
};
export default SteerButton;

View File

@@ -1,7 +1,6 @@
import React, { useEffect, useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
const XboxController = ({ onGamepadUpdate }) => {
const XboxController = ({ onGamepadUpdate, onConnectionChange }) => {
const { t } = useTranslation();
const [gamepadState, setGamepadState] = useState<{
buttons: boolean[];
@@ -12,22 +11,20 @@ const XboxController = ({ onGamepadUpdate }) => {
axes: [0, 0, 0, 0],
connected: false,
});
const requestRef = useRef<number>(null);
// 用 ref 保存最新的回调,避免 RAF 循环闭包捕获旧 props 导致权限判断失效
const onGamepadUpdateRef = useRef(onGamepadUpdate);
onGamepadUpdateRef.current = onGamepadUpdate;
const onConnectionChangeRef = useRef(onConnectionChange);
onConnectionChangeRef.current = onConnectionChange;
const DEAD_ZONE = 0.08;
const normalizeAxis = (v: number) =>
Math.abs(v) < DEAD_ZONE ? 0 : Number(v.toFixed(2));
const lastSendRef = useRef(0);
const SEND_INTERVAL = 1000 / 10; // 20Hz
const lastPayloadRef = useRef('');
const updateGamepad = () => {
const gp = navigator.getGamepads()[0];
if (gp) {
const state = {
buttons: gp.buttons.map(b => b.pressed),
@@ -35,16 +32,12 @@ const XboxController = ({ onGamepadUpdate }) => {
connected: true,
ts: Date.now(),
};
setGamepadState(state);
const payload = JSON.stringify({
buttons: state.buttons,
axes: state.axes,
});
const now = performance.now();
if (
now - lastSendRef.current > SEND_INTERVAL
// payload !== lastPayloadRef.current
@@ -59,74 +52,54 @@ const XboxController = ({ onGamepadUpdate }) => {
requestRef.current = requestAnimationFrame(updateGamepad);
return;
}
requestRef.current = requestAnimationFrame(updateGamepad);
};
useEffect(() => {
requestRef.current = requestAnimationFrame(updateGamepad);
const onFocus = () => {
// 页面重新获得焦点 → 立刻重拉一次
requestRef.current = requestAnimationFrame(updateGamepad);
};
window.addEventListener('focus', onFocus);
return () => {
if (requestRef.current) cancelAnimationFrame(requestRef.current);
window.removeEventListener('focus', onFocus);
};
}, []); // ✅ 空依赖
useEffect(() => {
setTimeout(() => {
window.focus();
navigator.getGamepads(); // 🔥 强制触发一次
}, 0);
}, [/* 页面切换依赖 */]);
useEffect(() => {
const handleConnect = (e: GamepadEvent) => {
console.log('🎮 Gamepad connected:', e.gamepad.id);
setGamepadState(prev => ({ ...prev, connected: true }));
};
const handleDisconnect = (e: GamepadEvent) => {
console.log('❌ Gamepad disconnected');
//handleControlModal({ control: false });
setGamepadState(prev => ({ ...prev, connected: false }));
};
window.addEventListener('gamepadconnected', handleConnect);
window.addEventListener('gamepaddisconnected', handleDisconnect);
return () => {
window.removeEventListener('gamepadconnected', handleConnect);
window.removeEventListener('gamepaddisconnected', handleDisconnect);
};
}, []);
// UI mapping for Xbox Gamepad
//点火熄火 上面俩 AB升降底盘 XY割刀加减速 button7急停
// Buttons: 0:A, 1:B, 2:X, 3:Y, 4:LB, 5:RB, 6:LT, 7:RT, 8:Back, 9:Start, 10:LS, 11:RS, 12:Up, 13:Down, 14:Left, 15:Right
//点火熄火 上面俩 AB升降底盘 XY割刀加减速 button8急停 BUTTON4点火 BUTTON5熄火
const { buttons, axes, connected } = gamepadState;
const getAxisStyle = (axisX: number, axisY: number) => ({
transform: `translate(${axisX * 6}px, ${axisY * 6}px)`,
});
useEffect(() => {
onConnectionChangeRef.current?.(gamepadState.connected);
}, [gamepadState.connected]);
return (
<div className="relative h-[252px] aspect-[4/3] flex items-center justify-center">
{/* 手柄硬件连接状态指示(仅表示物理手柄是否连接) */}
<div
className={`absolute top-0 right-0 px-2 py-0.5 rounded text-[8px] font-bold tracking-widest border ${connected
? 'bg-cyan-500/20 text-cyan-400 border-cyan-500/30'
: 'bg-slate-800 text-slate-500 border-white/5'
}`}
>
{connected ? t('devices.controllerConnected') : t('devices.controllerNotConnected')}
</div>
<svg viewBox="0 0 400 300" className="w-full h-full drop-shadow-[0_0_20px_rgba(34,211,238,0.15)]">
{/* Main Body */}
@@ -138,22 +111,23 @@ const XboxController = ({ onGamepadUpdate }) => {
transform="scale(1, 1.08)"
transformOrigin="200px 180px"
/>
{/* Triggers & Bumpers */}
<rect x="70" y="50" width="50" height="25" rx="5" fill={buttons[4] ? "#22d3ee" : "#0f172a"} stroke="#22d3ee" strokeWidth="1" opacity={buttons[4] ? 1 : 0.3} />
<text x="95" y="66" textAnchor="middle" fill={buttons[4] ? "#fff" : "#15414b"} fontSize="12" fontWeight="bold">LB</text>
<rect x="280" y="50" width="50" height="25" rx="5" fill={buttons[5] ? "#22d3ee" : "#0f172a"} stroke="#22d3ee" strokeWidth="1" opacity={buttons[5] ? 1 : 0.3} />
<text x="305" y="66" textAnchor="middle" fill={buttons[5] ? "#fff" : "#15414b"} fontSize="12" fontWeight="bold">RB</text>
{/* 左右耳朵标识:左=点火 右=熄火 */}
{/* LT / RT Indicators */}
<path d="M80 30 L110 30 Q115 45 95 50 L80 50 Z" fill={buttons[6] ? "#22d3ee" : "transparent"} stroke="#22d3ee" strokeWidth="1" opacity={buttons[6] ? 1 : 0.2} />
<path d="M320 30 L290 30 Q285 45 305 50 L320 50 Z" fill={buttons[7] ? "#22d3ee" : "transparent"} stroke="#22d3ee" strokeWidth="1" opacity={buttons[7] ? 1 : 0.2} />
{/* Left Stick Area */}
<circle cx="120" cy="140" r="35" fill="#0f172a" stroke="#22d3ee" strokeWidth="1" strokeDasharray="2 2" />
<g style={getAxisStyle(axes[0] || 0, axes[1] || 0)}>
<circle cx="120" cy="140" r="28" fill="#1e293b" stroke="#22d3ee" strokeWidth="2" />
<circle cx="120" cy="140" r="12" fill={buttons[10] ? "#22d3ee" : "transparent"} stroke="#22d3ee" strokeWidth="1" />
</g>
{/* Right Stick Area */}
<g transform="translate(0, 20)">
<circle
@@ -165,7 +139,6 @@ const XboxController = ({ onGamepadUpdate }) => {
strokeWidth="1"
strokeDasharray="2 2"
/>
<g style={getAxisStyle(axes[2] || 0, axes[3] || 0)}>
<circle
cx="280"
@@ -185,7 +158,6 @@ const XboxController = ({ onGamepadUpdate }) => {
/>
</g>
</g>
{/* D-Pad */}
<g transform="translate(130, 220)">
<path d="M0 -25 L0 25 M-25 0 L25 0" stroke="#334155" strokeWidth="15" strokeLinecap="round" />
@@ -194,21 +166,28 @@ const XboxController = ({ onGamepadUpdate }) => {
<path d="M-25 0 L-10 0" stroke={buttons[14] ? "#22d3ee" : "#64748b"} strokeWidth="12" strokeLinecap="round" />
<path d="M25 0 L10 0" stroke={buttons[15] ? "#22d3ee" : "#64748b"} strokeWidth="12" strokeLinecap="round" />
</g>
{/* Buttons (ABXY) */}
{/* Buttons (ABXY) + Text Label */}
<g transform="translate(280, 140)">
<circle cx="0" cy="20" r="12" fill={buttons[0] ? "#22c55e" : "#0f172a"} stroke="#22c55e" strokeWidth="1" opacity={buttons[0] ? 1 : 0.6} /> {/* A */}
<circle cx="20" cy="0" r="12" fill={buttons[1] ? "#ef4444" : "#0f172a"} stroke="#ef4444" strokeWidth="1" opacity={buttons[1] ? 1 : 0.6} /> {/* B */}
<circle cx="-20" cy="0" r="12" fill={buttons[2] ? "#3b82f6" : "#0f172a"} stroke="#3b82f6" strokeWidth="1" opacity={buttons[2] ? 1 : 0.6} /> {/* X */}
<circle cx="0" cy="-20" r="12" fill={buttons[3] ? "#eab308" : "#0f172a"} stroke="#eab308" strokeWidth="1" opacity={buttons[3] ? 1 : 0.6} /> {/* Y */}
</g>
<text x="0" y="24" textAnchor="middle" fill={buttons[0] ? "#fff" : "#22c55e"} fontSize="14" fontWeight="bold">A</text>
{/* Menu Buttons */}
<circle cx="20" cy="0" r="12" fill={buttons[1] ? "#ef4444" : "#0f172a"} stroke="#ef4444" strokeWidth="1" opacity={buttons[1] ? 1 : 0.6} /> {/* B */}
<text x="20" y="4" textAnchor="middle" fill={buttons[1] ? "#fff" : "#ef4444"} fontSize="14" fontWeight="bold">B</text>
<circle cx="-20" cy="0" r="12" fill={buttons[2] ? "#3b82f6" : "#0f172a"} stroke="#3b82f6" strokeWidth="1" opacity={buttons[2] ? 1 : 0.6} /> {/* X */}
<text x="-20" y="4" textAnchor="middle" fill={buttons[2] ? "#fff" : "#3b82f6"} fontSize="14" fontWeight="bold">X</text>
<circle cx="0" cy="-20" r="12" fill={buttons[3] ? "#eab308" : "#0f172a"} stroke="#eab308" strokeWidth="1" opacity={buttons[3] ? 1 : 0.6} /> {/* Y */}
<text x="0" y="-16" textAnchor="middle" fill={buttons[3] ? "#fff" : "#eab308"} fontSize="14" fontWeight="bold">Y</text>
</g>
{/* Menu Buttons + Text Label button8=急停, button9=Menu */}
<circle cx="180" cy="140" r="6" fill={buttons[8] ? "#22d3ee" : "#334155"} />
<text x="180" y="152" textAnchor="middle" fill={buttons[8] ? "#22d3ee" : "#64748b"} fontSize="9" fontWeight="bold">急停</text>
<circle cx="220" cy="140" r="6" fill={buttons[9] ? "#22d3ee" : "#334155"} />
<text x="220" y="152" textAnchor="middle" fill={buttons[9] ? "#22d3ee" : "#64748b"} fontSize="9" fontWeight="bold">Menu</text>
</svg>
</div>
);
};
export default XboxController;