Compare commits
3 Commits
4e1356b8af
...
236023733e
| Author | SHA1 | Date | |
|---|---|---|---|
| 236023733e | |||
| fe0847ac35 | |||
| 652dbdcc78 |
@@ -191,7 +191,7 @@ class WebSocketManager {
|
||||
console.log('WebSocket not connected, cannot send message');
|
||||
return false;
|
||||
}
|
||||
console.log('WebSocket send message');
|
||||
console.log('WebSocket send message', JSON.stringify(data));
|
||||
this.ws.send(JSON.stringify(data));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,132 +1,200 @@
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
|
||||
type GuideLineProps = {
|
||||
/** 方向 forward前进 reverse倒车 */
|
||||
direction: 'forward' | 'reverse';
|
||||
/** 方向盘转角,单位°:左转负数,右转正数,范围建议 -45 ~ 45 */
|
||||
steer: number;
|
||||
/** 画布宽度 */
|
||||
width?: number;
|
||||
/** 画布高度 */
|
||||
height?: number;
|
||||
/** 引导线底部(车尾端)两条线间距 */
|
||||
/** 引导线底部(车尾端)两条线间距,默认为容器宽度的 40% */
|
||||
bottomGap?: number;
|
||||
/** 引导线顶部(远端)两条线间距 */
|
||||
/** 引导线顶部(远端)两条线间距,默认为容器宽度的 20% */
|
||||
topGap?: number;
|
||||
/** 是否显示辅助线 */
|
||||
visible?: boolean;
|
||||
};
|
||||
|
||||
const CarReverseGuideLine: React.FC<GuideLineProps> = ({
|
||||
direction,
|
||||
steer,
|
||||
width = 640,
|
||||
height = 480,
|
||||
bottomGap = 100,
|
||||
topGap = 160,
|
||||
bottomGap,
|
||||
topGap,
|
||||
visible = true,
|
||||
}) => {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [size, setSize] = useState({ width: 0, height: 0 });
|
||||
|
||||
// 监听容器大小变化
|
||||
useEffect(() => {
|
||||
if (!containerRef.current) return;
|
||||
const resizeObserver = new ResizeObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
const { width, height } = entry.contentRect;
|
||||
setSize({ width, height });
|
||||
}
|
||||
});
|
||||
resizeObserver.observe(containerRef.current);
|
||||
return () => resizeObserver.disconnect();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return;
|
||||
if (!canvas || size.width === 0 || size.height === 0 || !visible) return;
|
||||
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
|
||||
const { width, height } = size;
|
||||
ctx.clearRect(0, 0, width, height);
|
||||
// 车尾中心点(画布底部)
|
||||
const baseX = width / 2;
|
||||
const baseY = height - 20;
|
||||
const totalDist = direction === 'reverse' ? height * 0.82 : height * 0.68;
|
||||
|
||||
// 基础参数计算
|
||||
// 前向视角:下面宽(近处),上面窄(远处)
|
||||
// 后向视角:上面宽(远处固定点),下面窄(近处转弯点)
|
||||
let bGap = bottomGap || (direction === 'reverse' ? width * 0.25 : width * 0.45);
|
||||
let tGap = topGap || (direction === 'reverse' ? width * 0.45 : width * 0.25);
|
||||
|
||||
const maxWheelAngle = 45;
|
||||
// 限制车轮转角范围
|
||||
const wheelAngleRad = Math.max(-maxWheelAngle, Math.min(maxWheelAngle, steer)) * Math.PI / 180;
|
||||
const step = 2; // 步长,越小曲线越平滑
|
||||
const step = 2;
|
||||
|
||||
// 迭代计算轨迹点函数
|
||||
const getPathPoints = (side: 'left' | 'right'): [number, number][] => {
|
||||
const points: [number, number][] = [];
|
||||
let x = baseX;
|
||||
let y = baseY;
|
||||
let angle = -Math.PI / 2; // 初始朝向:向上(画布Y减小方向)
|
||||
const totalDist = direction === 'reverse' ? height * 0.75 : height * 0.7;
|
||||
const stepCount = Math.floor(totalDist / step);
|
||||
points.push([x, y]);
|
||||
for (let i = 0; i < stepCount; i++) {
|
||||
// 当前进度 0~1,0=底部起点,1=最远顶部
|
||||
const progress = i / stepCount;
|
||||
// 线性插值:从底部gap过渡到顶部gap
|
||||
const currentGap = bottomGap * (1 - progress) + topGap * progress;
|
||||
const sideOffset = side === 'left' ? -currentGap / 2 : currentGap / 2;
|
||||
|
||||
if (Math.abs(wheelAngleRad) < 0.001) {
|
||||
// 回正:直线向上
|
||||
y -= step;
|
||||
} else {
|
||||
// 有转向:改变朝向,再前进一小步
|
||||
const turnStepRad = step * Math.tan(wheelAngleRad) / 240;
|
||||
// 分母240:控制转弯曲率,调大转弯更平缓;调小弯更急
|
||||
angle += turnStepRad;
|
||||
x += Math.cos(angle) * step;
|
||||
y += Math.sin(angle) * step;
|
||||
if (direction === 'forward') {
|
||||
// 前视角:底部固定,向上延伸并转向
|
||||
let x = width / 2;
|
||||
let y = height - 20;
|
||||
let angle = -Math.PI / 2;
|
||||
|
||||
for (let i = 0; i <= stepCount; i++) {
|
||||
const progress = i / stepCount;
|
||||
const currentGap = bGap * (1 - progress) + tGap * progress;
|
||||
const sideOffset = side === 'left' ? -currentGap / 2 : currentGap / 2;
|
||||
|
||||
if (Math.abs(wheelAngleRad) > 0.001) {
|
||||
// 恢复前视转向灵敏度:使用固定曲率
|
||||
const curvature = height * 0.5;
|
||||
const turnStepRad = (step * Math.tan(wheelAngleRad)) / curvature;
|
||||
angle += turnStepRad;
|
||||
x += Math.cos(angle) * step;
|
||||
y += Math.sin(angle) * step;
|
||||
} else {
|
||||
y -= step;
|
||||
}
|
||||
points.push([x + sideOffset, y]);
|
||||
if (y < 0) break;
|
||||
}
|
||||
// 叠加当前侧边偏移
|
||||
const px = x + sideOffset;
|
||||
const py = y;
|
||||
points.push([px, py]);
|
||||
// 超出画布提前停止绘制
|
||||
if (py < 0 || px < 0 || px > width) break;
|
||||
} else {
|
||||
// 后视角:顶部固定点,向下延伸至底部并随转向摆动
|
||||
// 我们从顶部 (width/2, height - totalDist) 开始向下画
|
||||
let x = width / 2;
|
||||
let startY = height - totalDist - 20;
|
||||
let y = startY;
|
||||
let angle = Math.PI / 2; // 向下
|
||||
|
||||
for (let i = 0; i <= stepCount; i++) {
|
||||
const progress = i / stepCount; // 0 是顶部,1 是底部
|
||||
// 后视角透视:progress=0(顶部)时使用 tGap,progress=1(底部)时使用 bGap
|
||||
const currentGap = tGap * (1 - progress) + bGap * progress;
|
||||
const sideOffset = side === 'left' ? currentGap / 2 : -currentGap / 2;
|
||||
|
||||
if (Math.abs(wheelAngleRad) > 0.001) {
|
||||
// 转向逻辑:从顶部向下走,底部随 steer 摆动
|
||||
// steer 为负(左打)时,底部应该向左摆动(x减小)
|
||||
const curvature = height * 0.5; // 与前视角保持一致的曲率灵敏度
|
||||
const turnStepRad = (step * Math.tan(wheelAngleRad)) / curvature;
|
||||
angle -= turnStepRad; // 后视角向下绘制,减去增量以实现正确的左右转向
|
||||
x += Math.cos(angle) * step;
|
||||
y += Math.sin(angle) * step;
|
||||
} else {
|
||||
y += step;
|
||||
}
|
||||
points.push([x + sideOffset, y]);
|
||||
}
|
||||
// 后视角的点是从上往下的,为了统一绘制逻辑(从下往上渐变),我们翻转数组
|
||||
points.reverse();
|
||||
}
|
||||
|
||||
return points;
|
||||
};
|
||||
|
||||
// 绘制左右两条轨迹
|
||||
ctx.lineWidth = 3;
|
||||
ctx.strokeStyle = '#0f0';
|
||||
ctx.setLineDash([]);
|
||||
const leftPath = getPathPoints('left');
|
||||
const rightPath = getPathPoints('right');
|
||||
const drawPath = (pts: [number, number][]) => {
|
||||
|
||||
const drawPath = (pts: [number, number][], color: string, dash: number[] = []) => {
|
||||
if (pts.length < 2) return;
|
||||
ctx.beginPath();
|
||||
pts.forEach(([px, py], idx) => {
|
||||
if (idx === 0) ctx.moveTo(px, py);
|
||||
else ctx.lineTo(px, py);
|
||||
});
|
||||
ctx.lineWidth = 4;
|
||||
ctx.strokeStyle = color;
|
||||
ctx.setLineDash(dash);
|
||||
ctx.lineJoin = 'round';
|
||||
ctx.lineCap = 'round';
|
||||
|
||||
ctx.moveTo(pts[0][0], pts[0][1]);
|
||||
for (let i = 1; i < pts.length; i++) {
|
||||
ctx.lineTo(pts[i][0], pts[i][1]);
|
||||
}
|
||||
ctx.stroke();
|
||||
ctx.beginPath(); // 强制清空当前路径缓存!重点!
|
||||
};
|
||||
drawPath(leftPath);
|
||||
drawPath(rightPath);
|
||||
|
||||
// 渐变色绘制
|
||||
const gradient = ctx.createLinearGradient(0, height, 0, 0);
|
||||
gradient.addColorStop(0, 'rgba(0, 255, 0, 0.8)'); // 近处绿色
|
||||
gradient.addColorStop(0.5, 'rgba(255, 255, 0, 0.8)'); // 中间黄色
|
||||
gradient.addColorStop(1, 'rgba(255, 0, 0, 0.8)'); // 远处红色
|
||||
|
||||
drawPath(leftPath, gradient);
|
||||
drawPath(rightPath, gradient);
|
||||
|
||||
// ========== 横向距离标记虚线 ==========
|
||||
ctx.strokeStyle = '#ff0';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.setLineDash([8, 6]);
|
||||
const markCount = 3;
|
||||
ctx.setLineDash([10, 8]);
|
||||
const markCount = 4;
|
||||
for (let m = 1; m <= markCount; m++) {
|
||||
const ratio = m / (markCount + 1);
|
||||
const idx = Math.floor(leftPath.length * ratio);
|
||||
if (idx >= leftPath.length) continue;
|
||||
if (idx >= leftPath.length || idx >= rightPath.length) continue;
|
||||
|
||||
const [lx, ly] = leftPath[idx];
|
||||
const [rx, ry] = rightPath[idx];
|
||||
|
||||
// 根据距离改变颜色
|
||||
ctx.strokeStyle = ratio < 0.3 ? 'rgba(0, 255, 0, 0.6)' :
|
||||
ratio < 0.7 ? 'rgba(255, 255, 0, 0.6)' : 'rgba(255, 0, 0, 0.6)';
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(lx, ly);
|
||||
ctx.lineTo(rx, ry);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
// ========== 车身底部框 ==========
|
||||
//ctx.setLineDash([]);
|
||||
//ctx.strokeStyle = '#0ff';
|
||||
//ctx.lineWidth = 2;
|
||||
//ctx.beginPath();
|
||||
//ctx.rect(baseX - bottomGap / 2, baseY - 30, bottomGap, 30);
|
||||
//ctx.stroke();
|
||||
}, [direction, steer, width, height, bottomGap, topGap]);
|
||||
}, [direction, steer, size, bottomGap, topGap, visible]);
|
||||
|
||||
return (
|
||||
<div style={{ position: 'relative', width, height }}>
|
||||
{/* 背景倒车画面,可以替换 video / img */}
|
||||
<div
|
||||
ref={containerRef}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
inset: 0,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
pointerEvents: 'none',
|
||||
zIndex: 5,
|
||||
display: visible ? 'block' : 'none'
|
||||
}}
|
||||
>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={width}
|
||||
height={height}
|
||||
style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}
|
||||
width={size.width}
|
||||
height={size.height}
|
||||
style={{ width: '100%', height: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default CarReverseGuideLine;
|
||||
|
||||
@@ -39,8 +39,16 @@ const DPadControl: React.FC<DPadControlProps> = ({ onGamepadUpdate, onSpeedChang
|
||||
// 用 ref 存储最新状态,避免 setInterval 闭包捕获旧值
|
||||
const pressedRef = useRef<Record<string, boolean>>({});
|
||||
const speedRef = useRef(0.5);
|
||||
// 始终指向最新的 emit,保证「按住持续发送」不受旧闭包影响
|
||||
const emitRef = useRef<((overrides?: Record<string, boolean>) => void) | null>(null);
|
||||
// 记录当前按下的键盘按键,避免 keydown 重复触发
|
||||
const activeKeysRef = useRef<Set<string>>(new Set());
|
||||
// 用 ref 存储外部回调,避免 emit/startPress/endPress 因回调引用变化而重建,
|
||||
// 进而触发 useEffect 清理把持续发送的定时器清掉
|
||||
const onGamepadUpdateRef = useRef(onGamepadUpdate);
|
||||
onGamepadUpdateRef.current = onGamepadUpdate;
|
||||
const onSpeedChangeRef = useRef(onSpeedChange);
|
||||
onSpeedChangeRef.current = onSpeedChange;
|
||||
|
||||
// 构建状态:只传输 xy 坐标(axes),buttons 全部为 false
|
||||
const buildState = useCallback(
|
||||
@@ -51,14 +59,15 @@ const DPadControl: React.FC<DPadControlProps> = ({ onGamepadUpdate, onSpeedChang
|
||||
let axisX = 0;
|
||||
let axisY = 0;
|
||||
const spd = speedRef.current;
|
||||
// 向右为正、向左为负;向上为正、向下为负
|
||||
if (btnMap.left) axisX -= spd;
|
||||
if (btnMap.right) axisX += spd;
|
||||
if (btnMap.up) axisY -= spd;
|
||||
if (btnMap.down) axisY += spd;
|
||||
if (btnMap.up) axisY += spd;
|
||||
if (btnMap.down) axisY -= spd;
|
||||
|
||||
return {
|
||||
buttons: new Array(17).fill(false),
|
||||
axes: [axisX, axisY, 0, 0],
|
||||
axes: [0, axisY, axisX, 0],
|
||||
connected: true,
|
||||
ts: Date.now(),
|
||||
};
|
||||
@@ -70,10 +79,11 @@ const DPadControl: React.FC<DPadControlProps> = ({ onGamepadUpdate, onSpeedChang
|
||||
(overrides?: Record<string, boolean>) => {
|
||||
if (disabled) return;
|
||||
const state = overrides ? buildState(overrides) : buildState();
|
||||
onGamepadUpdate?.(state);
|
||||
onGamepadUpdateRef.current?.(state);
|
||||
},
|
||||
[buildState, disabled, onGamepadUpdate],
|
||||
[buildState, disabled],
|
||||
);
|
||||
emitRef.current = emit;
|
||||
|
||||
const startPress = useCallback(
|
||||
(key: string) => {
|
||||
@@ -84,7 +94,7 @@ const DPadControl: React.FC<DPadControlProps> = ({ onGamepadUpdate, onSpeedChang
|
||||
// 持续发送(模拟手柄按住)
|
||||
if (pressTimer.current) window.clearInterval(pressTimer.current);
|
||||
pressTimer.current = window.setInterval(() => {
|
||||
emit();
|
||||
emitRef.current?.();
|
||||
}, 100);
|
||||
},
|
||||
[disabled, emit],
|
||||
@@ -202,7 +212,7 @@ const DPadControl: React.FC<DPadControlProps> = ({ onGamepadUpdate, onSpeedChang
|
||||
const v = parseFloat(e.target.value);
|
||||
setSpeed(v);
|
||||
speedRef.current = v;
|
||||
onSpeedChange?.(v);
|
||||
onSpeedChangeRef.current?.(v);
|
||||
}}
|
||||
className="w-full h-2.5 rounded-full appearance-none cursor-pointer bg-slate-700 accent-cyan-400"
|
||||
style={{
|
||||
|
||||
@@ -35,6 +35,7 @@ import envConfig from '../../../env';
|
||||
import utils from '@/lib/utils.ts';
|
||||
import { useUnitFormatter } from '@/lib/units';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { sendEmergencyStop } from './emergencyStopControl';
|
||||
|
||||
const { Content } = Layout;
|
||||
const { Text, Title } = Typography;
|
||||
@@ -543,7 +544,11 @@ export default function DeviceOverviewPage() {
|
||||
const handlePause = () => message.info(t('devices.taskPaused'));
|
||||
const handleReturn = () => message.info(t('devices.fixed2ReturnHomeFixed2CommandIssuedFixed2'));
|
||||
const handleRecharge = () => message.info(t('devices.commandIssuedFixed2'));
|
||||
const handleEmergencyStop = () => message.error(t('devices.s73'));
|
||||
// 急停:点击时直接下发 button7(绕过控制权限校验),并提示已触发
|
||||
const handleEmergencyStop = () => {
|
||||
sendEmergencyStop(userInfo);
|
||||
message.error(t('devices.s73'));
|
||||
};
|
||||
|
||||
const fix2 = (val) => {
|
||||
if (val === null || val === undefined || isNaN(val)) return '-';
|
||||
|
||||
@@ -96,10 +96,6 @@ export default function DeviceStatusPage() {
|
||||
const hasRequestedControlRef = useRef(false);
|
||||
const [messageApi, contextHolder] = message.useMessage();
|
||||
|
||||
const [direction, setDirection] = useState<'forward' | 'reverse'>('reverse');
|
||||
const [steer, setSteer] = useState(0);
|
||||
|
||||
|
||||
// 视频播放开关
|
||||
const [isVideoPlaying, setIsVideoPlaying] = useState(false);
|
||||
|
||||
@@ -671,18 +667,19 @@ export default function DeviceStatusPage() {
|
||||
}, [device, uavState, currentDroneData]);
|
||||
|
||||
const handleGamepadUpdate = useCallback((state) => {
|
||||
console.log('handleGamepadUpdate called with state:', isControlled);
|
||||
// 无控制权限时:不发送消息,且只发起一次权限申请(避免手柄/方向盘高频更新刷屏)
|
||||
if (!isControlled) {
|
||||
if (!hasRequestedControlRef.current && !connecting) {
|
||||
hasRequestedControlRef.current = true;
|
||||
handleControlModal();
|
||||
}
|
||||
return;
|
||||
}
|
||||
//if (!isControlled) {
|
||||
// //if (!hasRequestedControlRef.current && !connecting) {
|
||||
// // hasRequestedControlRef.current = true;
|
||||
// // handleControlModal();
|
||||
// //}
|
||||
// return;
|
||||
//}
|
||||
console.log('Gamepad state updated:', state);
|
||||
// 记录方向盘 xy 坐标,用于倒车影像叠加层
|
||||
if (state?.axes) {
|
||||
setSteerXY({ x: state.axes[0] || 0, y: state.axes[1] || 0 });
|
||||
setSteerXY({ x: state.axes[2] || 0, y: state.axes[1] || 0 });
|
||||
}
|
||||
controllerRef.current?.sendGamepad(state);
|
||||
}, [isControlled, connecting]);
|
||||
@@ -973,32 +970,6 @@ export default function DeviceStatusPage() {
|
||||
</div>
|
||||
|
||||
|
||||
{/*<div style={{ marginBottom: 16 }}>
|
||||
<button onClick={() => setDirection('reverse')} style={{ marginRight: 8 }}>倒车</button>
|
||||
<button onClick={() => setDirection('forward')}>前进</button>
|
||||
<div style={{ marginTop: 8 }}>
|
||||
方向盘转角:{steer}°
|
||||
<br />
|
||||
<input
|
||||
type="range"
|
||||
min={-45}
|
||||
max={45}
|
||||
value={steer}
|
||||
onChange={(e) => setSteer(Number(e.target.value))}
|
||||
/>
|
||||
<p>左滑:左转(负数)|右滑:右转(正数)</p>
|
||||
</div>
|
||||
</div>
|
||||
<CarReverseGuideLine
|
||||
direction="reverse"
|
||||
steer={steer}
|
||||
width={640}
|
||||
height={480}
|
||||
bottomGap={280} // 车尾端两条线间距
|
||||
topGap={100} // 远端顶部两条线间距
|
||||
/>*/}
|
||||
|
||||
|
||||
<div style={{ padding: 0 }}>
|
||||
{contextHolder}
|
||||
|
||||
@@ -1346,7 +1317,11 @@ export default function DeviceStatusPage() {
|
||||
<div style={{ position: 'relative', width: '100%', height: '100%' }}>
|
||||
{/*<AgrtcRoomRobot CHANNEL={device?.serialNumber || ''} />*/}
|
||||
<AgrtcRoomRobot CHANNEL={"41-thream03"} />
|
||||
|
||||
<CarReverseGuideLine
|
||||
direction="forward"
|
||||
steer={steerXY.x * 45}
|
||||
visible={isVideoPlaying}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ position: 'relative', width: '100%', height: '100%' }}>
|
||||
@@ -1362,19 +1337,17 @@ export default function DeviceStatusPage() {
|
||||
error={error}
|
||||
ready={ready}
|
||||
/>
|
||||
{mowerView === 'back' && (
|
||||
<CarReverseGuideLine
|
||||
direction="reverse"
|
||||
steer={steerXY.x * 45}
|
||||
visible={isVideoPlaying}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
|
||||
{/* 倒车影像叠加层:根据方向盘 xy 显示转向辅助线 */}
|
||||
{/*{isVideoPlaying && (*/}
|
||||
{/*<CarReverseGuideLine direction={direction} steer={steer} />*/}
|
||||
|
||||
|
||||
{/*<ReverseCameraOverlay x={steerXY.x} y={steerXY.y} visible={true} />*/}
|
||||
{/*//)}*/}
|
||||
|
||||
{/* 视频未加载 / 停止播放的占位 */}
|
||||
{!isVideoPlaying && (
|
||||
<div style={{
|
||||
width: '100%', height: '100%',
|
||||
@@ -1531,7 +1504,7 @@ export default function DeviceStatusPage() {
|
||||
{/* 权限状态标签 */}
|
||||
<Tag
|
||||
icon={connecting ? <LoadingOutlined /> : (isControlled ? <UnlockOutlined /> : <LockOutlined />)}
|
||||
color={connecting ? 'gold' : (isControlled ? 'green' : 'default')}
|
||||
color={connecting ? 'gold' : (isControlled ? 'green' : 'red')}
|
||||
style={{ margin: 0, fontSize: 12 }}
|
||||
>
|
||||
{connecting
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useSelector } from 'react-redux';
|
||||
import { RootState } from '@/store';
|
||||
import { sendEmergencyStop } from './emergencyStopControl';
|
||||
import {
|
||||
ShieldAlert,
|
||||
Zap,
|
||||
@@ -48,6 +51,7 @@ const RobotFeatureButtons: React.FC<RobotFeatureButtonsProps> = ({
|
||||
className = '',
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const { userInfo } = useSelector((state: RootState) => state.user);
|
||||
const [active, setActive] = useState<Set<RobotFeature>>(new Set(activeFeatures));
|
||||
|
||||
const handleClick = (feature: RobotFeature) => {
|
||||
@@ -56,6 +60,8 @@ const RobotFeatureButtons: React.FC<RobotFeatureButtonsProps> = ({
|
||||
if (next) nextSet.add(feature);
|
||||
else nextSet.delete(feature);
|
||||
setActive(nextSet);
|
||||
// 急停:点击时直接下发 button7(绕过控制权限校验)
|
||||
if (feature === 'emergencyStop') sendEmergencyStop(userInfo);
|
||||
onToggle?.(feature, next);
|
||||
};
|
||||
|
||||
|
||||
@@ -14,6 +14,9 @@ const XboxController = ({ onGamepadUpdate }) => {
|
||||
});
|
||||
|
||||
const requestRef = useRef<number>(null);
|
||||
// 用 ref 保存最新的回调,避免 RAF 循环闭包捕获旧 props 导致权限判断失效
|
||||
const onGamepadUpdateRef = useRef(onGamepadUpdate);
|
||||
onGamepadUpdateRef.current = onGamepadUpdate;
|
||||
const DEAD_ZONE = 0.08;
|
||||
|
||||
const normalizeAxis = (v: number) =>
|
||||
@@ -46,7 +49,7 @@ const XboxController = ({ onGamepadUpdate }) => {
|
||||
now - lastSendRef.current > SEND_INTERVAL
|
||||
// payload !== lastPayloadRef.current
|
||||
) {
|
||||
onGamepadUpdate(state); // ✅ 只有这里才发
|
||||
onGamepadUpdateRef.current(state); // ✅ 只有这里才发
|
||||
lastSendRef.current = now;
|
||||
lastPayloadRef.current = payload;
|
||||
}
|
||||
|
||||
28
src/components/devices/emergencyStopControl.ts
Normal file
28
src/components/devices/emergencyStopControl.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { wsManager } from '../WebSocketManager';
|
||||
|
||||
// 急停对应手柄 button7(buttons 数组下标 7)
|
||||
const EMERGENCY_STOP_BUTTON_INDEX = 7;
|
||||
|
||||
// 构建单帧遥控数据:仅急停位按下/松开,其余按键与摇杆轴保持空闲
|
||||
const buildFrame = (pressed: boolean) => {
|
||||
const buttons = new Array(17).fill(false);
|
||||
buttons[EMERGENCY_STOP_BUTTON_INDEX] = pressed;
|
||||
return { buttons, axes: [0, 0, 0, 0], connected: true, ts: Date.now() };
|
||||
};
|
||||
|
||||
/**
|
||||
* 单击急停:绕过控制权限校验,直接经 WebSocket 下发 button7;
|
||||
* 约 300ms 后自动补发一帧复位数据,模拟按下再松开。
|
||||
*/
|
||||
export const sendEmergencyStop = (userInfo?: any) => {
|
||||
const send = (pressed: boolean) =>
|
||||
wsManager.send({
|
||||
type: 'remoteControl',
|
||||
remoteData: buildFrame(pressed),
|
||||
token: userInfo?.token,
|
||||
userName: userInfo?.username,
|
||||
});
|
||||
|
||||
send(true);
|
||||
setTimeout(() => send(false), 300);
|
||||
};
|
||||
Reference in New Issue
Block a user