Files
web-Iot/src/components/devices/XboxController.tsx

194 lines
8.3 KiB
TypeScript

import React, { useEffect, useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
const XboxController = ({ onGamepadUpdate, onConnectionChange }) => {
const { t } = useTranslation();
const [gamepadState, setGamepadState] = useState<{
buttons: boolean[];
axes: number[];
connected: boolean;
}>({
buttons: new Array(17).fill(false),
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),
axes: gp.axes.map(normalizeAxis),
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
) {
onGamepadUpdateRef.current(state); // ✅ 只有这里才发
lastSendRef.current = now;
lastPayloadRef.current = payload;
}
}
if (!gp) {
// 不要在这里停 RAF
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割刀加减速 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">
<svg viewBox="0 0 400 300" className="w-full h-full drop-shadow-[0_0_20px_rgba(34,211,238,0.15)]">
{/* Main Body */}
<path
d="M100 80 Q50 80 40 130 L30 220 Q25 270 80 280 L140 250 L260 250 L320 280 Q375 270 370 220 L360 130 Q350 80 300 80 Z"
fill="#1e293b"
stroke={connected ? "#22d3ee" : "#334155"}
strokeWidth="3"
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
cx="280"
cy="200"
r="35"
fill="#0f172a"
stroke="#22d3ee"
strokeWidth="1"
strokeDasharray="2 2"
/>
<g style={getAxisStyle(axes[2] || 0, axes[3] || 0)}>
<circle
cx="280"
cy="200"
r="28"
fill="#1e293b"
stroke="#22d3ee"
strokeWidth="2"
/>
<circle
cx="280"
cy="200"
r="12"
fill={buttons[11] ? "#22d3ee" : "transparent"}
stroke="#22d3ee"
strokeWidth="1"
/>
</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" />
<path d="M0 -25 L0 -10" stroke={buttons[12] ? "#22d3ee" : "#64748b"} strokeWidth="12" strokeLinecap="round" />
<path d="M0 25 L0 10" stroke={buttons[13] ? "#22d3ee" : "#64748b"} strokeWidth="12" strokeLinecap="round" />
<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) + 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 */}
<text x="0" y="24" textAnchor="middle" fill={buttons[0] ? "#fff" : "#22c55e"} fontSize="14" fontWeight="bold">A</text>
<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;