Compare commits

...

8 Commits

21 changed files with 5265 additions and 951 deletions

View File

@@ -477,6 +477,17 @@ export function getTaskPath(params) {
})
}
//下载 机器属性模板
export function downloadDeviceTemplate(params) {
return request({
url: '/iot/deviceRunParam/downloadTemplate',
method: 'get',
params,
responseType: 'blob', // 关键!告诉axios返回二进制
})
}

31
src/api/mapEdit.ts Normal file
View File

@@ -0,0 +1,31 @@
import request from './request';
export function saveSiteMapInfo(data) {
return request({
url: `/system/siteMapInfo/save`,
method: 'post',
data,
});
}
//返回休息区
export function backToRestPointCommand(data) {
return request({
url: `/iot/deviceTask/backToRestPoint`,
method: 'post',
data,
});
}
/// 下发区域绑定任务/iot/deviceTask/createRegionDefaultTask
export function createRegionDefaultTask(data) {
return request({
url: `/iot/deviceTask/createRegionDefaultTask`,
method: 'post',
data,
});
}

View File

@@ -49,6 +49,17 @@ export function getStationRegions(params) {
});
}
//根据场站获取地图配置
export function getSiteMapInfo(params) {
return request({
url: '/system/siteMapInfo/selectBySiteId',
method: 'get',
params
});
}
//新增分区
export function saveRegion(data) {
return request({

View File

@@ -1,4 +1,4 @@
import React, { useEffect, useRef, useState, useMemo, useImperativeHandle, forwardRef, useCallback } from 'react';
import React, { useEffect, useRef, useState, useMemo, useImperativeHandle, forwardRef, useCallback, useLayoutEffect } from 'react';
import carImg from '../assets/images/carplane.png';
import inspectImg from "../assets/images/inspectCar.png"
import planeImg from '../assets/images/planeicon.png';
@@ -10,6 +10,8 @@ import iotImg from '../assets/images/iot.png';
import envConfig from '../../env';
import { TracePoint, TPAction, TPMode } from '../lib/TracePoint/tracePoint';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';
import { getSiteMapInfo, getStationRegions } from '../api/stationManage';
const CYAN_ALARM_COLOR = new window.Cesium.Color(
@@ -27,7 +29,7 @@ const CYAN_GLOW_COLOR = new window.Cesium.Color(
);
window.Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmNjk0NjI1MC0wZGYyLTQ1YzItYjJmZi0wY2M5ODEwODllYzIiLCJpZCI6Mzk3MTQxLCJpYXQiOjE3NzI1MjkwMjV9.U6qmakhDgXJVXwLFyWzSxAUOFZRrDkIsRUPP6CCdnKg";
const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, finishPoint, drawRealTime, realtimePosition, realtimeType, pathPoints = [], devices = [], onCameraClick, focusLocation, points = [], markedPoints = [], onPathChange, from, onClearDraw, onMarkPoint, routeMode = '', polyPoints, mapLayer }, ref) => {
const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, finishPoint, drawRealTime, realtimePosition, realtimeType, pathPoints = [], devices = [], onCameraClick, focusLocation, points = [], markedPoints = [], onPathChange, from, onClearDraw, onMarkPoint, routeMode = '', polyPoints, mapLayer, activeType, overlayRefreshKey = 0, focusOverlay = null }, ref) => {
const containerRef = useRef(null);
const viewerRef = useRef(null);
const tooltipRef = useRef(null);
@@ -41,10 +43,20 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
const navLineRef = useRef(null); // 完成点实时轨迹
const markedPointsRef = useRef([]); // 标记点实体
const markedLineRef = useRef(null); // 标记点连线实体
const lastMarkedPointsRef = useRef([]); // 上次渲染的标记点数据,用于增量更新
const onMarkPointRef = useRef(onMarkPoint); // 总是指向最新的 onMarkPoint,避免闭包滞后
const onCameraClickRef = useRef(onCameraClick); // 同样处理,避免闭包滞后
const { t } = useTranslation();
// 场站已配置的返航点 / 分区叠加显示
const stationId = useSelector((state) => state?.station?.stationId || state?.station?.currentStation?.id);
const [stationOverlay, setStationOverlay] = useState({ returnPoints: [], regions: [] });
const stationOverlayIdsRef = useRef([]);
const returnPointPinUrlRef = useRef(null);
// 被点击聚焦的返航点 id / 图例高亮类型
const [highlightReturnPointId, setHighlightReturnPointId] = useState('');
const [legendHighlight, setLegendHighlight] = useState('');
const realtimeEntityRef = useRef(null);
const realtimeLineRef = useRef(null);
@@ -679,63 +691,94 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
}
}, [points]);
// 渲染标记点 + 连线(唯一系统,避免重复标记)
// 渲染标记点 + 连线(增量更新:只增删改真正变化的点)
const drawMarkedPoints = (points) => {
const viewer = viewerRef.current;
if (!viewer) return;
// 先清空之前的标记点与连线
markedPointsRef.current.forEach(id => {
viewer.entities.removeById(id);
});
markedPointsRef.current = [];
const newPoints = points || [];
const prevPoints = lastMarkedPointsRef.current || [];
if (markedLineRef.current) {
try {
viewer.entities.remove(markedLineRef.current);
} catch (e) { }
markedLineRef.current = null;
const nextIds = new Set(newPoints.map((p, i) => `marked-point-${p.id ?? i}`));
// 1) 删除不在新列表中的旧 entity
markedPointsRef.current = markedPointsRef.current.filter(id => {
if (!nextIds.has(id)) {
viewer.entities.removeById(id);
return false;
}
return true;
});
// 2) 新增或更新标记点 entity
newPoints.forEach((p, i) => {
const id = `marked-point-${p.id ?? i}`;
const entity = viewer.entities.getById(id);
const position = window.Cesium.Cartesian3.fromDegrees(Number(p.lon), Number(p.lat));
const labelText = `${i + 1}`;
if (entity) {
// 只更新位置和 label,避免销毁重建
entity.position = position;
if (entity.label) entity.label.text = labelText;
} else {
viewer.entities.add({
id,
position,
point: {
color: window.Cesium.Color.GREEN,
pixelSize: 15,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
label: {
text: labelText,
font: '14px sans-serif',
pixelOffset: new window.Cesium.Cartesian2(0, -20),
fillColor: window.Cesium.Color.WHITE,
outlineColor: window.Cesium.Color.BLACK,
outlineWidth: 2,
style: window.Cesium.LabelStyle.FILL_AND_OUTLINE,
}
});
markedPointsRef.current.push(id);
}
});
// 3) 连线:只有坐标/数量真正变化时才重建
if (activeType !== "routeGen") {
viewer.scene.requestRender();
return;
}
const lineChanged = newPoints.length !== prevPoints.length ||
newPoints.some((p, i) => {
const pp = prevPoints[i];
return !pp || Number(pp.lon) !== Number(p.lon) || Number(pp.lat) !== Number(p.lat);
});
if (lineChanged) {
if (markedLineRef.current) {
try { viewer.entities.remove(markedLineRef.current); } catch (e) { }
markedLineRef.current = null;
}
if (newPoints.length >= 2) {
const linePositions = newPoints.map(p =>
window.Cesium.Cartesian3.fromDegrees(Number(p.lon), Number(p.lat))
);
markedLineRef.current = viewer.entities.add({
polyline: {
positions: linePositions,
width: 4,
material: window.Cesium.Color.SKYBLUE,
clampToGround: true,
}
});
}
}
if (!points || points.length === 0) return;
lastMarkedPointsRef.current = newPoints.map(p => ({ ...p }));
// 先绘制连线:有 2 个及以上打点才连线
if (points.length >= 2) {
const linePositions = points.map(p =>
window.Cesium.Cartesian3.fromDegrees(Number(p.lon), Number(p.lat))
);
markedLineRef.current = viewer.entities.add({
polyline: {
positions: linePositions,
width: 4,
material: window.Cesium.Color.SKYBLUE,
clampToGround: true,
}
});
}
points.forEach((p, i) => {
const id = `marked-point-${i}`;
viewer.entities.add({
id,
position: window.Cesium.Cartesian3.fromDegrees(p.lon, p.lat),
point: {
color: window.Cesium.Color.GREEN,
pixelSize: 15,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
label: {
text: `${i + 1}`,
font: '14px sans-serif',
pixelOffset: new window.Cesium.Cartesian2(0, -20),
fillColor: window.Cesium.Color.WHITE,
outlineColor: window.Cesium.Color.BLACK,
outlineWidth: 2,
style: window.Cesium.LabelStyle.FILL_AND_OUTLINE,
}
});
markedPointsRef.current.push(id);
});
// 强制 Cesium 立即渲染(requestRenderMode=true 时必须手动触发)
viewer.scene.requestRender();
};
useEffect(() => {
@@ -834,6 +877,25 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
}
}
// 返航点悬浮提示:显示别名与该返航点绑定的机器
function showReturnPointTooltip(tooltip, position, point) {
if (!tooltip) return;
tooltip.style.display = "block";
tooltip.style.left = position.x + 12 + "px";
tooltip.style.top = position.y + 12 + "px";
tooltip.style.whiteSpace = "nowrap";
const boundDevice = devices.find(d => d?.serialNumber === point.bindDeviceId);
const deviceLabel = point.bindDeviceId
? (boundDevice?.deviceAlias || boundDevice?.deviceName || point.bindDeviceId)
: t('devices.mapEditor.unbound');
tooltip.innerHTML = `
<div style="font-weight:600;margin-bottom:4px;">📍 ${point.alias || '-'}</div>
<div>🤖 ${deviceLabel}</div>
`;
}
function fetchPublishedLayers() {
const baseUrl = envConfig.geoserver_url;
//const baseUrl = 'https://gis.caasrobot.com/geoserver';
@@ -1271,6 +1333,163 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
flyToLayer(mapLayer, envConfig.geoserver_url, 100);
}, [mapLayer]);
// 拉取当前场站已配置的返航点与分区
useEffect(() => {
if (!stationId) {
setStationOverlay({ returnPoints: [], regions: [] });
return;
}
let cancelled = false;
getSiteMapInfo({ siteId: stationId })
.then((res) => {
if (cancelled) return;
const pts = res?.code === 200 ? (res?.data?.restPoints || []) : [];
setStationOverlay(prev => ({ ...prev, returnPoints: Array.isArray(pts) ? pts : [] }));
})
.catch(() => { });
getStationRegions({ siteId: stationId })
.then((res) => {
if (cancelled) return;
const list = res?.code === 200 ? (res?.data || res?.rows || []) : [];
setStationOverlay(prev => ({ ...prev, regions: Array.isArray(list) ? list : [] }));
})
.catch(() => { });
return () => { cancelled = true; };
}, [stationId, overlayRefreshKey]);
// 在地图上叠加显示:返航点用标志图标,分区用小框
useEffect(() => {
const viewer = viewerRef.current;
const Cesium = window.Cesium;
if (!viewer || !Cesium) return;
// 清理上一次叠加实体
stationOverlayIdsRef.current.forEach(id => viewer.entities.removeById(id));
stationOverlayIdsRef.current = [];
// 返航点标志图标(PinBuilder 生成,失败则退化为圆点)
if (!returnPointPinUrlRef.current && Cesium.PinBuilder) {
try {
returnPointPinUrlRef.current = Cesium.PinBuilder.fromColor(Cesium.Color.fromCssColorString('#165DFF'), 36).toDataURL();
} catch (e) { /* ignore */ }
}
(stationOverlay.returnPoints || []).forEach((pt, idx) => {
const lon = Number(pt?.position?.lng ?? pt?.lng);
const lat = Number(pt?.position?.lat ?? pt?.lat);
if (!isFinite(lon) || !isFinite(lat) || lon === 0 || lat === 0) return;
const id = `station-return-point-${idx}`;
const isHighlighted = id === highlightReturnPointId;
viewer.entities.add({
id,
returnPointData: {
alias: pt?.alias || '',
bindDeviceId: pt?.bindDeviceId || '',
},
position: Cesium.Cartesian3.fromDegrees(lon, lat, 0),
...(returnPointPinUrlRef.current
? {
billboard: {
image: returnPointPinUrlRef.current,
width: isHighlighted ? 36 : 24,
height: isHighlighted ? 48 : 32,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
}
}
: {
point: {
pixelSize: isHighlighted ? 16 : 10,
color: Cesium.Color.fromCssColorString(isHighlighted ? '#FA8C16' : '#165DFF'),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
}
}),
label: pt?.alias ? {
text: pt.alias,
font: 'bold 12px sans-serif',
fillColor: Cesium.Color.WHITE,
showBackground: true,
backgroundColor: Cesium.Color.fromCssColorString(isHighlighted ? '#FA8C16' : '#165DFF').withAlpha(0.8),
pixelOffset: new Cesium.Cartesian2(0, isHighlighted ? -48 : -34),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
} : undefined,
});
stationOverlayIdsRef.current.push(id);
});
// 分区:用小框(多边形)显示
(stationOverlay.regions || []).forEach((region, idx) => {
const scope = Array.isArray(region?.scope) ? region.scope : [];
const positions = scope
.map(p => {
const lon = Number(p?.lng ?? p?.lon);
const lat = Number(p?.lat);
if (!isFinite(lon) || !isFinite(lat) || lon === 0 || lat === 0) return null;
return Cesium.Cartesian3.fromDegrees(lon, lat, 0);
})
.filter(Boolean);
if (positions.length < 3) return;
const id = `station-region-${region?.id ?? idx}`;
viewer.entities.add({
id,
polygon: {
hierarchy: positions,
material: Cesium.Color.fromCssColorString('#13C2C2').withAlpha(0.18),
outline: true,
outlineColor: Cesium.Color.fromCssColorString('#13C2C2').withAlpha(0.9),
height: 0,
clampToGround: true,
},
label: region?.regionName ? {
text: region.regionName,
font: '12px sans-serif',
fillColor: Cesium.Color.WHITE,
showBackground: true,
backgroundColor: Cesium.Color.fromCssColorString('#13C2C2').withAlpha(0.8),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
} : undefined,
});
stationOverlayIdsRef.current.push(id);
});
viewer.scene.requestRender();
}, [stationOverlay, highlightReturnPointId]);
// 点击已配置列表:定位到对应返航点/分区;返航点额外高亮
useEffect(() => {
const viewer = viewerRef.current;
const Cesium = window.Cesium;
if (!viewer || !Cesium || !focusOverlay) return;
if (focusOverlay.type === 'returnPoint') {
const pt = (stationOverlay.returnPoints || [])[focusOverlay.index];
const lon = Number(pt?.position?.lng ?? pt?.lng);
const lat = Number(pt?.position?.lat ?? pt?.lat);
if (!isFinite(lon) || !isFinite(lat) || lon === 0 || lat === 0) return;
setLegendHighlight('returnPoint');
setHighlightReturnPointId(`station-return-point-${focusOverlay.index}`);
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(lon, lat, 500),
duration: 0.8,
});
} else if (focusOverlay.type === 'region') {
const region = (stationOverlay.regions || []).find(r => String(r.id) === String(focusOverlay.id));
const scope = Array.isArray(region?.scope) ? region.scope : [];
const lons = scope.map(p => Number(p?.lng ?? p?.lon)).filter(n => isFinite(n) && n !== 0);
const lats = scope.map(p => Number(p?.lat)).filter(n => isFinite(n) && n !== 0);
if (!lons.length || !lats.length) return;
setLegendHighlight('region');
setHighlightReturnPointId('');
viewer.camera.flyTo({
destination: Cesium.Rectangle.fromDegrees(
Math.min(...lons), Math.min(...lats), Math.max(...lons), Math.max(...lats)
),
duration: 0.8,
});
}
}, [focusOverlay, stationOverlay]);
useEffect(() => {
// 如果有 realtimePosition,不显示 focusEntity
@@ -1960,10 +2179,13 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
handler.setInputAction((movement) => {
const picked = viewer.scene.pick(movement.endPosition);
const pickedReturnPoint = (window.Cesium.defined(picked) && picked.id?.returnPointData) ? picked.id.returnPointData : null;
const pickedRobot = (window.Cesium.defined(picked) && picked.id?.properties?.robot) ? picked.id.properties.robot.getValue() : null;
// ✅ 只有拾取到设备实体,才显示tooltip,空白区域直接隐藏
if (pickedRobot) {
// 返航点优先显示「别名 + 绑定机器」,设备显示设备信息,空白区域隐藏
if (pickedReturnPoint) {
showReturnPointTooltip(tooltipRef.current, movement.endPosition, pickedReturnPoint);
} else if (pickedRobot) {
const { lon, lat } = getCursorLngLat(viewer, movement.endPosition);
showCoordinateTooltip(tooltipRef.current, movement.endPosition, t, lon, lat, pickedRobot);
} else {
@@ -2000,11 +2222,11 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
}
}
}
console.log('点击地图,拾取到设备', robot);
if (robot) {
onCameraClickRef.current?.(robot);
}
if (from !== "deviceStatus")
const _allowedFrom = ["mapEditor"];
if (!_allowedFrom.includes(from))
return;
const cartesian = viewer.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
if (!cartesian) return;
@@ -2596,6 +2818,66 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
whiteSpace: "nowrap",
}}
/>
{/* 图例:返航点 / 分区 */}
{(stationOverlay.returnPoints.length > 0 || stationOverlay.regions.length > 0) && (
<div
style={{
position: "absolute",
right: 12,
top: 12,
zIndex: 20,
background: "rgba(255,255,255,0.92)",
borderRadius: 6,
padding: "8px 10px",
fontSize: 12,
color: "#333",
lineHeight: "18px",
boxShadow: "0 2px 8px rgba(0,0,0,0.12)",
}}
>
<div style={{ fontWeight: 600, marginBottom: 6 }}>{t('devices.mapEditor.legend')}</div>
<div style={{
display: "flex",
alignItems: "center",
gap: 6,
padding: "2px 4px",
borderRadius: 4,
fontWeight: legendHighlight === "returnPoint" ? 600 : 400,
color: legendHighlight === "returnPoint" ? "#165DFF" : "#333",
background: legendHighlight === "returnPoint" ? "#e8f3ff" : "transparent",
}}>
<span style={{
display: "inline-block",
width: 10,
height: 10,
background: "#165DFF",
borderRadius: "50% 50% 50% 0",
transform: "rotate(-45deg)",
}} />
<span>{t('devices.mapEditor.returnPoint')}</span>
</div>
<div style={{
display: "flex",
alignItems: "center",
gap: 6,
marginTop: 4,
padding: "2px 4px",
borderRadius: 4,
fontWeight: legendHighlight === "region" ? 600 : 400,
color: legendHighlight === "region" ? "#13C2C2" : "#333",
background: legendHighlight === "region" ? "rgba(19,194,194,0.12)" : "transparent",
}}>
<span style={{
display: "inline-block",
width: 12,
height: 10,
border: "1px solid #13C2C2",
background: "rgba(19,194,194,0.18)",
}} />
<span>{t('devices.mapEditor.restArea')}</span>
</div>
</div>
)}
</div>
);

View File

@@ -23,6 +23,7 @@ import {
DisconnectOutlined,
UploadOutlined,
EditOutlined,
DownloadOutlined,
} from '@ant-design/icons';
import {
@@ -41,6 +42,7 @@ import { RootState } from '@/src/store';
import utils from '@/lib/utils';
import DeviceParamModal from '../devices/DeviceParamModal';
import { useTranslation } from 'react-i18next';
import { downloadDeviceTemplate } from '@/api/device';
interface SmartDeviceManagementProps {
allOrgOptions: any[];
@@ -195,6 +197,9 @@ export default function SmartDeviceManagement({
const params = {
deviceId: data.serialNumber,
};
setCurrentParamDevice(data);
setParamModalVisible(true);
return;
hasPermission(params).then(res => {
if (res.code == 200) {
if (res.data) {
@@ -383,6 +388,23 @@ export default function SmartDeviceManagement({
),
},
];
const downloadDeviceTemplatefn = async () => {
try {
const res = await downloadDeviceTemplate(); // 你的参数
// 从响应头拿文件名(后端要返回 Content-Disposition)
let fileName = '设备模板.xlsx';
const blob = new Blob([res]);
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = fileName;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(a.href);
} catch (err) {
console.error('下载失败', err);
}
}
const selectorgId = Form.useWatch('orgId', bindSmartForm);
const selectsiteId = Form.useWatch('siteId', bindSmartForm);
@@ -415,6 +437,10 @@ export default function SmartDeviceManagement({
<Upload customRequest={handleImportDevices} showUploadList={false} accept='.xlsx,.xls'>
<Button icon={<UploadOutlined />}>{t('common.import')}</Button>
</Upload>
<Button icon={<DownloadOutlined />} onClick={downloadDeviceTemplatefn}>
{t('common.download')}
</Button>
<Button disabled={selectedSmartKeys.length === 0} onClick={() => handleUnbindSmart(selectedSmartKeys, 1)}>{t('systemSetting.batchUnbindUser')}</Button>
<Button disabled={selectedSmartKeys.length === 0} onClick={() => handleUnbindSmart(selectedSmartKeys, 2)}>{t('systemSetting.batchUnbindStation')}</Button>
<Button disabled={selectedSmartKeys.length === 0} onClick={() => handleUnbindSmart(selectedSmartKeys, 3)}>{t('systemSetting.batchUnbindOrg')}</Button>

View File

@@ -1,178 +1,493 @@
import React, { useEffect, useRef, useState } from 'react';
import React, { useEffect, useRef } from 'react';
type GuideLineProps = {
/** 方向 forward前进 reverse倒车 */
direction: 'forward' | 'reverse';
/** 方向盘转角,单位°:左转负数,右转正数,范围建议 -45 ~ 45 */
steer: number;
/** 引导线底部(车尾端)两条线间距,默认为容器宽度的 40% */
/** 实时线速度(m/s):前进为正,后退为负。缺省时回退到 steer */
linearSpeed?: number;
/** 实时角速度(rad/s):左转为正,右转为负。缺省时回退到 steer */
angularSpeed?: number;
bottomGap?: number;
/** 引导线顶部(远端)两条线间距,默认为容器宽度的 20% */
topGap?: number;
/** 是否显示辅助线 */
visible?: boolean;
/** 中间绿色人字线是否闪烁,默认开启 */
chevronFlash?: boolean;
};
type Point = {
x: number;
y: number;
};
const CarReverseGuideLine: React.FC<GuideLineProps> = ({
direction,
steer,
linearSpeed,
angularSpeed,
bottomGap,
topGap,
visible = true,
chevronFlash = true,
}) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const [size, setSize] = useState({ width: 0, height: 0 });
// 监听容器大小变化
const steerRef = useRef(steer);
const linearSpeedRef = useRef(linearSpeed);
const angularSpeedRef = useRef(angularSpeed);
// 平滑后的转向量:> 0 右移,< 0 左移,0 为直行
const turnRef = useRef(0);
const directionRef = useRef(direction);
const flashRef = useRef(chevronFlash);
const gapRef = useRef({ bottomGap, topGap });
const visibleRef = useRef(visible);
// 更新参数,不触发 React 组件重新渲染
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();
}, []);
steerRef.current = steer;
linearSpeedRef.current = linearSpeed;
angularSpeedRef.current = angularSpeed;
directionRef.current = direction;
flashRef.current = chevronFlash;
gapRef.current = { bottomGap, topGap };
visibleRef.current = visible;
}, [
steer,
linearSpeed,
angularSpeed,
direction,
chevronFlash,
bottomGap,
topGap,
visible,
]);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas || size.width === 0 || size.height === 0 || !visible) return;
const container = containerRef.current;
if (!canvas || !container) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const { width, height } = size;
ctx.clearRect(0, 0, width, height);
let width = 0;
let height = 0;
let dpr = 1;
let rafId = 0;
let lastTime = 0;
let animationTime = 0;
// 基础参数计算
// 前向视角:下面宽(近处),上面窄(远处)
// 后向视角:上面宽(远处固定点),下面窄(近处转弯点)
let bGap = bottomGap || (direction === 'reverse' ? width * 0.25 : width * 0.45);
let tGap = topGap || (direction === 'reverse' ? width * 0.45 : width * 0.25);
const resize = () => {
const rect = container.getBoundingClientRect();
const maxWheelAngle = 45;
const wheelAngleRad = Math.max(-maxWheelAngle, Math.min(maxWheelAngle, steer)) * Math.PI / 180;
const step = 2;
width = rect.width;
height = rect.height;
// 迭代计算轨迹点函数
const getPathPoints = (side: 'left' | 'right'): [number, number][] => {
const points: [number, number][] = [];
const totalDist = direction === 'reverse' ? height * 0.75 : height * 0.7;
const stepCount = Math.floor(totalDist / step);
// 避免高分辨率车机屏幕上的辅助线模糊
dpr = Math.min(window.devicePixelRatio || 1, 2);
if (direction === 'forward') {
// 前视角:底部固定,向上延伸并转向
let x = width / 2;
let y = height - 20;
let angle = -Math.PI / 2;
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(height * dpr);
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;
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
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;
}
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
};
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(container);
resize();
/**
* 计算当前转向量(-1 左 … 0 直行 … +1 右)。
*
* 优先使用实时状态:曲率 κ = ω / v
* linear_speed : 前进为正,后退为负(只取大小参与曲率,方向由视角决定)
* angular_speed : 左转为正,右转为负
* 曲率 > 0(左转)对应画面左侧,因此转向量取负号;
* 静止 / 极低速时不产生行驶轨迹,按直行处理。
* 无实时数据时回退到方向盘转角 steer。
*/
const computeTurn = () => {
const v = linearSpeedRef.current;
const w = angularSpeedRef.current;
const hasRealtime =
typeof v === 'number' &&
Number.isFinite(v) &&
typeof w === 'number' &&
Number.isFinite(w);
if (!hasRealtime) {
const angle = Math.max(
-45,
Math.min(45, steerRef.current)
);
// 方向盘转角转换为曲率响应
return Math.tan((angle * Math.PI) / 180);
}
// 静止 / 极低速:没有行驶轨迹,保持直线
if (Math.abs(v) < 0.03) return 0;
// 低速时限制分母,避免曲率被放大到满量程
const speed = Math.max(Math.abs(v), 0.15);
// 曲率:ω / v,正值左转
const kappa = w / speed;
// 满量程曲率(约对应 1m 转弯半径)
const KAPPA_FULL_SCALE = 1.0;
const normalized = Math.max(
-1,
Math.min(1, kappa / KAPPA_FULL_SCALE)
);
// 左转为正 → 画面左侧为负偏移
return -normalized;
};
/**
* 计算转向后的车道中心。
*
* forward:
* 下方近端相对稳定,上方远端逐渐弯曲
*
* reverse:
* 上方远端相对稳定,下方近端逐渐弯曲
*/
const getCenterX = (progress: number) => {
// progress: 0 = 顶部远端,1 = 底部近端
let curveProgress: number;
if (directionRef.current === 'forward') {
// 前视:上方弯曲,下方稳定
curveProgress = 1 - progress;
} 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();
// 后视:下方弯曲,上方稳定
curveProgress = progress;
}
return points;
// 平滑曲率,避免轨迹弯曲突兀
const curveFactor = curveProgress * curveProgress;
// 转向最大横向偏移
const maxOffset = width * 0.40;
const offset =
turnRef.current *
maxOffset *
curveFactor;
return width / 2 + offset;
};
/**
* 计算左右车道线。
*/
/**
* 计算左右车道线
*
* forward:
* 近端下方宽,远端上方窄
*
* reverse:
* 远端上方宽,近端下方窄
*/
const getLanePoint = (
progress: number,
side: 'left' | 'right'
): Point => {
const {
bottomGap: customBottom,
topGap: customTop,
} = gapRef.current;
const isReverse = directionRef.current === 'reverse';
// 前进:底部宽,顶部窄
// 倒车:底部窄,顶部宽
const defaultBottomGap = width * (
isReverse ? 0.25 : 0.45
);
const defaultTopGap = width * (
isReverse ? 0.45 : 0.25
);
const bGap = customBottom ?? defaultBottomGap;
const tGap = customTop ?? defaultTopGap;
// progress: 0 = 远端顶部,1 = 近端底部
const gap =
tGap * (1 - progress) +
bGap * progress;
// 左右车道对称分布
const sideOffset =
side === 'left'
? -gap / 2
: gap / 2;
const centerX = getCenterX(progress);
// 前进、倒车都保持近端在下方
const y =
height * 0.12 +
progress * height * 0.76;
return {
x: centerX + sideOffset,
y,
};
};
// 绘制左右两条轨迹
const leftPath = getPathPoints('left');
const rightPath = getPathPoints('right');
/**
* 绘制一条平滑车道线。
*/
const drawLane = (side: 'left' | 'right') => {
const points: Point[] = [];
const count = 100;
for (let i = 0; i <= count; i++) {
const progress = i / count;
points.push(getLanePoint(progress, side));
}
if (points.length < 2) return;
const gradient = ctx.createLinearGradient(
0,
height * 0.95,
0,
height * 0.12
);
gradient.addColorStop(0, '#18D99A');
gradient.addColorStop(0.45, '#16C99A');
gradient.addColorStop(0.75, '#E4B83B');
gradient.addColorStop(1, '#FF7043');
const drawPath = (pts: [number, number][], color: string, dash: number[] = []) => {
if (pts.length < 2) return;
ctx.beginPath();
ctx.lineWidth = 4;
ctx.strokeStyle = color;
ctx.setLineDash(dash);
ctx.lineJoin = 'round';
ctx.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++) {
ctx.lineTo(points[i].x, points[i].y);
}
ctx.strokeStyle = gradient;
ctx.lineWidth = Math.max(3, width * 0.004);
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.lineJoin = 'round';
ctx.setLineDash([]);
ctx.stroke();
};
// 渐变色绘制
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)'); // 远处红色
/**
* 绘制中间动态绿色人字线。
*
* phase 为动画相位:
* 1. 亮度呼吸
* 2. 线条流动
*/
const drawChevron = (
progress: number,
phase: number,
opacity: number
) => {
const centerX = getCenterX(progress);
drawPath(leftPath, gradient);
drawPath(rightPath, gradient);
const isReverse = directionRef.current === 'reverse';
// ========== 横向距离标记虚线 ==========
ctx.lineWidth = 2;
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 || idx >= rightPath.length) continue;
const y =
height * 0.12 +
progress * height * 0.76;
const [lx, ly] = leftPath[idx];
const [rx, ry] = rightPath[idx];
const gap =
width *
(0.10 + progress * 0.06);
// 根据距离改变颜色
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)';
const size =
height *
(0.075 + progress * 0.035);
// 人字线整体跟随转向弯曲
const offset =
Math.tan(
(Math.max(-45, Math.min(45, steerRef.current)) *
Math.PI) /
180
) *
width *
0.04 *
progress;
const cx = getCenterX(progress);
// 绿色发光效果
ctx.save();
ctx.globalAlpha = opacity;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
// 外层柔和光晕
ctx.shadowColor = '#00FFAA';
ctx.shadowBlur = width * 0.012;
ctx.strokeStyle = 'rgba(0, 255, 170, 0.22)';
ctx.lineWidth = width * 0.018;
// 前视:人字线尖端朝下 ∨
// 倒车:人字线尖端朝上 ∧
const isForward = directionRef.current === 'forward';
const leftX = cx - gap;
const rightX = cx + gap;
// 前视时尖端在上方,倒车时尖端在下方
const tipY = isForward ? y - size : y;
const outerY = isForward ? y : y - size;
// 外层光晕
ctx.beginPath();
ctx.moveTo(lx, ly);
ctx.lineTo(rx, ry);
ctx.moveTo(leftX, outerY);
ctx.lineTo(cx, tipY);
ctx.lineTo(rightX, outerY);
ctx.stroke();
}
}, [direction, steer, size, bottomGap, topGap, visible]);
// 内层清晰线
ctx.beginPath();
ctx.moveTo(leftX, outerY);
ctx.lineTo(cx, tipY);
ctx.lineTo(rightX, outerY);
ctx.stroke();
// 内层清晰绿色线
ctx.shadowBlur = width * 0.004;
ctx.strokeStyle = '#17E6A1';
ctx.lineWidth = width * 0.008;
// 外层光晕
ctx.beginPath();
ctx.moveTo(leftX, outerY);
ctx.lineTo(cx, tipY);
ctx.lineTo(rightX, outerY);
ctx.stroke();
// 内层清晰线
ctx.beginPath();
ctx.moveTo(leftX, outerY);
ctx.lineTo(cx, tipY);
ctx.lineTo(rightX, outerY);
ctx.stroke();
ctx.restore();
};
/**
* 绘制横向距离标记。
*/
const drawDistanceMarks = () => {
const marks = [0.25, 0.45, 0.65, 0.85];
ctx.save();
ctx.lineWidth = 1.5;
ctx.setLineDash([8, 6]);
marks.forEach((progress) => {
const left = getLanePoint(progress, 'left');
const right = getLanePoint(progress, 'right');
ctx.strokeStyle =
progress < 0.35
? 'rgba(0, 255, 170, 0.55)'
: progress < 0.7
? 'rgba(255, 210, 50, 0.50)'
: 'rgba(255, 90, 50, 0.45)';
ctx.beginPath();
ctx.moveTo(left.x, left.y);
ctx.lineTo(right.x, right.y);
ctx.stroke();
});
ctx.restore();
};
/**
* 动画主循环
*/
const render = (time: number) => {
rafId = requestAnimationFrame(render);
if (!width || !height || !visibleRef.current) {
ctx.clearRect(0, 0, width, height);
return;
}
// 限制动画时间增量,避免后台恢复后跳变
const delta = lastTime
? Math.min((time - lastTime) / 1000, 0.05)
: 0;
lastTime = time;
animationTime += delta;
// 实时数据抖动较大,按帧平滑转向量,避免辅助线抖动
const targetTurn = computeTurn();
turnRef.current +=
(targetTurn - turnRef.current) *
Math.min(1, delta * 8);
ctx.clearRect(0, 0, width, height);
// 底层车道线
drawLane('left');
drawLane('right');
drawDistanceMarks();
// 绿色人字线独立闪烁
const flash = flashRef.current
? 0.5 + 0.5 * Math.sin(animationTime * 2.8)
: 1;
// 三组人字线,形成向远处延伸的效果
const chevrons = [
{ progress: 0.25, opacity: 0.38 },
{ progress: 0.48, opacity: 0.65 },
{ progress: 0.70, opacity: 1.0 },
];
chevrons.forEach((item, index) => {
// 不同人字线有轻微相位差
const phase =
animationTime * 2.8 - index * 0.8;
const opacity = flashRef.current
? 0.25 + 0.75 * (0.5 + 0.5 * Math.sin(phase))
: 1;
drawChevron(
item.progress,
phase,
opacity * item.opacity
);
});
};
rafId = requestAnimationFrame(render);
return () => {
cancelAnimationFrame(rafId);
resizeObserver.disconnect();
};
}, []);
return (
<div
@@ -184,14 +499,17 @@ const CarReverseGuideLine: React.FC<GuideLineProps> = ({
height: '100%',
pointerEvents: 'none',
zIndex: 5,
display: visible ? 'block' : 'none'
display: visible ? 'block' : 'none',
overflow: 'hidden',
}}
>
<canvas
ref={canvasRef}
width={size.width}
height={size.height}
style={{ width: '100%', height: '100%' }}
style={{
width: '100%',
height: '100%',
display: 'block',
}}
/>
</div>
);

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'))}

View File

@@ -434,12 +434,14 @@ export default function DeviceOverviewPage() {
const params = {
deviceId: data.serialNumber,
}
setCurrentParamDevice(data);
setParamModalOpen(true);
return;
hasPermission(params).then(res => {
if (res.code == 200) {
if (res.data) {
setCurrentParamDevice(data);
setParamModalOpen(true);
} else {
utils.message.error(t('devices.noPermission'));
}
@@ -635,7 +637,7 @@ export default function DeviceOverviewPage() {
<Col xs={24} lg={14}>
<Card title={<><EnvironmentOutlined />{t('devices.fixed2Equipment')}</>} extra={<Button type="text" icon={<SettingOutlined />} />} variant="borderless" style={{ borderRadius: 8, marginBottom: 8 }} styles={{ body: { padding: 0 } }}>
<div style={{ width: '100%', height: 350, borderRadius: 8, position: 'relative', overflow: 'hidden' }}>
<div style={{ position: 'absolute', zIndex: 9999, top: 12, left: 12, background: 'rgba(255,255,255,0.95)', borderRadius: 6, padding: 8 }}>
<div style={{ position: 'absolute', zIndex: 11, top: 12, left: 12, background: 'rgba(255,255,255,0.95)', borderRadius: 6, padding: 8 }}>
<div style={{ fontSize: 11, fontWeight: 60, marginBottom: 4 }}>{t('devices.s22')}</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 4, fontSize: 10 }}>
<div><span style={{ color: '#1890ff' }}>———</span>{t('devices.fixed2Inspection')}</div>

View File

@@ -9,6 +9,7 @@ import {
Checkbox,
Slider,
Spin,
Select,
} from 'antd';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
@@ -71,9 +72,8 @@ const GainSliderInput = ({ value, onChange, disabled, min = 0.1, max = 1, step =
);
};
const editableKeys = ['leftForwardGain', 'leftBackwardGain', 'rightForwardGain', 'rightBackwardGain'];
// 可编辑的增益滑块字段
const editableGainKeys = ['leftForwardGain', 'leftBackwardGain', 'rightForwardGain', 'rightBackwardGain'];
interface DeviceParamModalProps {
open: boolean;
@@ -89,17 +89,17 @@ interface DeviceParamModalProps {
onCancel: () => void;
onSuccess?: () => void;
}
const DeviceParamModal: React.FC<DeviceParamModalProps> = ({ open, device, onCancel, onSuccess }) => {
const { stationId, currentStation } = useSelector((state: RootState) => state.station);
const [paramForm] = Form.useForm();
const [paramData, setParamData] = useState<any>(null);
const [loading, setLoading] = useState(false);
const { t } = useTranslation();
const deviceId = device?.serialNumber || device?.device_sn || '';
const deviceName = device?.deviceAlias || device?.deviceName || device?.drone_callsign || device?.callsign || deviceId;
const userInfo = useSelector((state: RootState) => state.user.userInfo);
const isAdmin = userInfo?.roleKey === 'admin'
useEffect(() => {
if (open && deviceId) {
@@ -120,7 +120,6 @@ const DeviceParamModal: React.FC<DeviceParamModalProps> = ({ open, device, onCan
paramForm.setFieldsValue({ ...res.data });
} else {
utils.message.error(t('devices.fetchParamFail'));
setParamData(null);
paramForm.resetFields();
}
@@ -138,10 +137,7 @@ const DeviceParamModal: React.FC<DeviceParamModalProps> = ({ open, device, onCan
setLoading(true);
try {
const payload = {
leftForwardGain: Math.max(0.1, Math.min(1, values.leftForwardGain >= 10 ? values.leftForwardGain / 10 : values.leftForwardGain)),
leftBackwardGain: Math.max(0.1, Math.min(1, values.leftBackwardGain >= 10 ? values.leftBackwardGain / 10 : values.leftBackwardGain)),
rightForwardGain: Math.max(0.1, Math.min(1, values.rightForwardGain >= 10 ? values.rightForwardGain / 10 : values.rightForwardGain)),
rightBackwardGain: Math.max(0.1, Math.min(1, values.rightBackwardGain >= 10 ? values.rightBackwardGain / 10 : values.rightBackwardGain)),
...values,
deviceId,
siteId: stationId,
orgId: currentStation?.orgId,
@@ -167,63 +163,132 @@ const DeviceParamModal: React.FC<DeviceParamModalProps> = ({ open, device, onCan
paramForm.resetFields();
onCancel?.();
};
const paramFieldConfigs = [
{ key: 'leftForwardGain', label: t('devices.paramLeftForwardGain'), type: 'InputNumber', editable: true, min: 0, max: 1, step: 0.01 },
{ key: 'leftBackwardGain', label: t('devices.paramLeftBackwardGain'), type: 'InputNumber', editable: true, min: 0, max: 1, step: 0.01 },
{ key: 'rightForwardGain', label: t('devices.paramRightForwardGain'), type: 'InputNumber', editable: true, min: 0, max: 1, step: 0.01 },
{ key: 'rightBackwardGain', label: t('devices.paramRightBackwardGain'), type: 'InputNumber', editable: true, min: 0, max: 1, step: 0.01 },
{ key: 'runSpeed', label: t('devices.paramRunSpeed'), type: 'InputNumber', editable: true },
//hasHost: "hasHost",
//rtkMode: "rtkMode", cameraNum: "cameraNum", wheelType: "wheelType", engineType: "engineType", capabilityList: "capabilityList", powerType: "powerType",
{ key: 'hasHost', label: t('devices.hasHost'), type: 'Input', editable: false },
{ key: 'rtkMode', label: t('devices.rtkMode'), type: 'Input', editable: false },
{ key: 'cameraNum', label: t('devices.cameraNum'), type: 'Input', editable: false },
{ key: 'wheelType', label: t('devices.wheelType'), type: 'Input', editable: false },
{ key: 'engineType', label: t('devices.engineType'), type: 'Input', editable: false },
{ key: 'capabilityList', label: t('devices.capabilityList'), type: 'Input', editable: false },
{ key: 'chipUidSign', label: t('devices.paramChipUidSign'), type: 'InputNumber', editable: false },
{ key: 'chipUid', label: t('devices.paramChipUid'), type: 'Input', editable: false },
{ key: 'remoteConfig', label: t('devices.paramRemoteConfig'), type: 'InputNumber', editable: false },
{ key: 'knifeMotorMode', label: t('devices.paramKnifeMotorMode'), type: 'InputNumber', editable: false },
{ key: 'walkMotorMode', label: t('devices.paramWalkMotorMode'), type: 'InputNumber', editable: false },
{ key: 'leftMotorReverse', label: t('devices.paramLeftMotorReverse'), type: 'InputNumber', editable: false },
{ key: 'rightMotorReverse', label: t('devices.paramRightMotorReverse'), type: 'InputNumber', editable: false },
{ key: 'swapChannel', label: t('devices.paramSwapChannel'), type: 'InputNumber', editable: false },
{ key: 'use4G', label: t('devices.paramUse4G'), type: 'InputNumber', editable: false },
{ key: 'forwardSpeedLimit', label: t('devices.paramForwardSpeedLimit'), type: 'InputNumber', editable: false },
{ key: 'turnSpeedLimit', label: t('devices.paramTurnSpeedLimit'), type: 'InputNumber', editable: false },
{ key: 'knifePolarity', label: t('devices.paramKnifePolarity'), type: 'InputNumber', editable: false },
{ key: 'fanPolarity', label: t('devices.paramFanPolarity'), type: 'InputNumber', editable: false },
{ key: 'throttlePolarity', label: t('devices.paramThrottlePolarity'), type: 'InputNumber', editable: false },
{ key: 'liftProtectTime', label: t('devices.paramLiftProtectTime'), type: 'InputNumber', editable: false },
{ key: 'dualRtk', label: t('devices.paramDualRtk'), type: 'InputNumber', editable: false },
{ key: 'knifeChannel', label: t('devices.paramKnifeChannel'), type: 'InputNumber', editable: false },
{ key: 'fanChannel', label: t('devices.paramFanChannel'), type: 'InputNumber', editable: false },
{ key: 'throttleChannel', label: t('devices.paramThrottleChannel'), type: 'InputNumber', editable: false },
{ key: 'remoteType', label: t('devices.paramRemoteType'), type: 'InputNumber', editable: false },
{ key: 'relayBoard', label: t('devices.paramRelayBoard'), type: 'Checkbox', editable: false },
{ key: 'liftChannel', label: t('devices.paramLiftChannel'), type: 'InputNumber', editable: false },
{ key: 'chassisChannel', label: t('devices.paramChassisChannel'), type: 'InputNumber', editable: false },
{ key: 'armChannel', label: t('devices.paramArmChannel'), type: 'InputNumber', editable: false },
{ key: 'fuelPumpChannel', label: t('devices.paramFuelPumpChannel'), type: 'InputNumber', editable: false },
{ key: 'wifiName', label: t('devices.paramWifiName'), type: 'Input', editable: false },
{ key: 'wifiPassword', label: t('devices.paramWifiPassword'), type: 'Input', editable: false },
{ key: 'batteryType', label: t('devices.paramBatteryType'), type: 'InputNumber', editable: false },
{ key: 'driveType', label: t('devices.paramDriveType'), type: 'InputNumber', editable: false },
{ key: 'gearRatio', label: t('devices.paramGearRatio'), type: 'InputNumber', editable: false, step: 0.01 },
{ key: 'robotLength', label: t('devices.paramRobotLength'), type: 'InputNumber', editable: false, step: 0.01 },
{ key: 'robotWidth', label: t('devices.paramRobotWidth'), type: 'InputNumber', editable: false, step: 0.01 },
{ key: 'robotHeight', label: t('devices.paramRobotHeight'), type: 'InputNumber', editable: false, step: 0.01 },
{ key: 'knifeWidth', label: t('devices.paramKnifeWidth'), type: 'InputNumber', editable: false, step: 0.01 },
{ key: 'tyreSize', label: t('devices.paramTyreSize'), type: 'InputNumber', editable: false, step: 0.01 },
{ key: 'firmwareVersion', label: t('devices.paramFirmwareVersion'), type: 'Input', editable: false },
{ key: 'crc16', label: 'CRC16', type: 'InputNumber', editable: false },
{ key: 'tail1', label: 'tail1', type: 'InputNumber', editable: false },
{ key: 'tail2', label: 'tail2', type: 'InputNumber', editable: false },
{ key: 'remark', label: t('roles.remark'), type: 'Input', editable: false },
{ key: 'delFlag', label: t('devices.paramDelFlag'), type: 'Checkbox', editable: false },
];
// ========== 按你后端Java实体顺序重新整理字段配置 ==========
// 枚举取值参考设备参数规范:设备类型 M/I/U、车轮 W/T、动力 E/H、RTK N/B、发动机 H/L/Z 等
const paramFieldConfigs: any[] = [
// 【可编辑】增益滑块 + runSpeed
//{ key: 'leftForwardGain', label: t('devices.paramLeftForwardGain'), type: 'GainSlider', editable: true, min: 0.1, max: 1, step: 0.01 },
//{ key: 'leftBackwardGain', label: t('devices.paramLeftBackwardGain'), type: 'GainSlider', editable: true, min: 0.1, max: 1, step: 0.01 },
//{ key: 'rightForwardGain', label: t('devices.paramRightForwardGain'), type: 'GainSlider', editable: true, min: 0.1, max: 1, step: 0.01 },
//{ key: 'rightBackwardGain', label: t('devices.paramRightBackwardGain'), type: 'GainSlider', editable: true, min: 0.1, max: 1, step: 0.01 },
//{ key: 'runSpeed', label: t('devices.paramRunSpeed'), type: 'InputNumber', editable: true },
// 下面全部只读,和后端Excel实体顺序对齐
{ key: 'deviceId', label: t('devices.deviceId'), type: 'Input', editable: isAdmin },
{
key: 'productModel', label: t('devices.productModel'), type: 'Select', editable: isAdmin,
options: [
{ value: 'ST', label: 'ST' },
{ value: 'PL', label: 'PL' },
{ value: 'PR', label: 'PR' },
{ value: 'AI', label: 'AI' },
],
},
{
key: 'deviceType', label: t('devices.deviceType'), type: 'Select', editable: isAdmin,
options: [
{ value: 'M', label: t('devices.paramEnum.deviceTypeM') },
{ value: 'I', label: t('devices.paramEnum.deviceTypeI') },
{ value: 'U', label: t('devices.paramEnum.deviceTypeU') },
],
},
{
key: 'rtkMode', label: t('devices.rtkMode'), type: 'Select', editable: isAdmin,
options: [
{ value: 'N', label: t('devices.paramEnum.rtkModeN') },
{ value: 'B', label: t('devices.paramEnum.rtkModeB') },
],
},
{ key: 'cameraNum', label: t('devices.cameraNum'), type: 'InputNumber', editable: isAdmin, min: 0, max: 4, step: 1 },
{
key: 'powerType', label: t('devices.powerType'), type: 'Select', editable: isAdmin,
options: [
{ value: 'E', label: t('devices.paramEnum.powerTypeE') },
{ value: 'H', label: t('devices.paramEnum.powerTypeH') },
],
},
{
key: 'wheelType', label: t('devices.wheelType'), type: 'Select', editable: isAdmin,
options: [
{ value: 'W', label: t('devices.paramEnum.wheelTypeW') },
{ value: 'T', label: t('devices.paramEnum.wheelTypeT') },
],
},
{
key: 'engineType', label: t('devices.engineType'), type: 'Select', editable: isAdmin,
options: [
{ value: 'H', label: t('devices.paramEnum.engineTypeH') },
{ value: 'L', label: t('devices.paramEnum.engineTypeL') },
{ value: 'Z', label: t('devices.paramEnum.engineTypeZ') },
],
},
{
key: 'hasHost', label: t('devices.hasHost'), type: 'Select', editable: isAdmin,
options: [
{ value: 0, label: t('devices.paramEnum.hasHostNo') },
{ value: 1, label: t('devices.paramEnum.hasHostYes') },
],
},
{
key: 'batteryType', label: t('devices.batteryType'), type: 'Select', editable: isAdmin,
options: [
{ value: '铅酸', label: t('devices.paramEnum.batteryLeadAcid') },
{ value: '锂电', label: t('devices.paramEnum.batteryLithium') },
],
},
{
key: 'walkingDriveType', label: t('devices.walkingDriveType'), type: 'Select', editable: isAdmin,
options: [
{ value: 'FDK', label: 'FDK' },
{ value: 'SdBLdc', label: 'SdBLdc' },
{ value: 'SdFoc', label: 'SdFoc' },
],
},
{
key: 'cutterDriveType', label: t('devices.cutterDriveType'), type: 'Select', editable: isAdmin,
options: [
{ value: 'XLD', label: 'XLD' },
{ value: 'LH', label: 'LH' },
],
},
{
key: 'rtkAntennasNum', label: t('devices.rtkAntennasNum'), type: 'Select', editable: isAdmin,
options: [
{ value: 1, label: t('devices.paramEnum.rtkAntennaSingle') },
{ value: 2, label: t('devices.paramEnum.rtkAntennaDual') },
],
},
{
key: 'handleType', label: t('devices.handleType'), type: 'Select', editable: isAdmin,
options: [
{ value: 'SBUS', label: t('devices.paramEnum.handleSbus') },
{ value: '自定义', label: t('devices.paramEnum.handleCustom') },
],
},
{ key: 'pcbVersion', label: t('devices.pcbVersion'), type: 'Input', editable: isAdmin },
{ key: 'dimensions', label: t('devices.dimensions'), type: 'Input', editable: isAdmin },
{ key: 'bladeWidth', label: t('devices.bladeWidth'), type: 'Input', editable: isAdmin },
{ key: 'tyreSize', label: t('devices.tyreSize'), type: 'Input', editable: isAdmin },
{ key: 'speedRatio', label: t('devices.speedRatio'), type: 'Input', editable: isAdmin },
{ key: 'cellularInfo', label: t('devices.cellularInfo'), type: 'Input', editable: isAdmin },
{ key: 'wifiName', label: t('devices.paramWifiName'), type: 'Input', editable: isAdmin },
{ key: 'bluetoothName', label: t('devices.bluetoothName'), type: 'Input', editable: isAdmin },
{ key: 'hardwareIdentifiers', label: t('devices.hardwareIdentifiers'), type: 'Input', editable: isAdmin },
{ key: 'imuModel', label: t('devices.imuModel'), type: 'Input', editable: isAdmin },
{ key: 'tempHumiditySensor', label: t('devices.tempHumiditySensor'), type: 'Input', editable: isAdmin },
{ key: 'barometerPresent', label: t('devices.barometerPresent'), type: 'Input', editable: isAdmin },
{ key: 'ultrasonicPresent', label: t('devices.ultrasonicPresent'), type: 'Input', editable: isAdmin },
{ key: 'dacPresent', label: t('devices.dacPresent'), type: 'Input', editable: isAdmin },
{ key: 'operator', label: t('devices.operator'), type: 'Input', editable: isAdmin },
{ key: 'inspectionNo', label: t('devices.inspectionNo'), type: 'Input', editable: isAdmin },
{ key: 'firmwareVersion', label: t('devices.paramFirmwareVersion'), type: 'Input', editable: isAdmin },
{ key: 'dealer', label: t('devices.dealer'), type: 'Input', editable: isAdmin },
];
// 区分增益滑块组 和 其余普通字段组
const gainFields = paramFieldConfigs.filter(f => f.type === 'GainSlider');
const otherFields = paramFieldConfigs.filter(f => f.type !== 'GainSlider');
return (
<Modal
@@ -249,49 +314,33 @@ const DeviceParamModal: React.FC<DeviceParamModalProps> = ({ open, device, onCan
width={780}
destroyOnClose
>
{/* 加载时表单区域简单遮罩提示(打开弹窗拉取参数时的loading反馈) */}
<div style={{ maxHeight: '60vh', overflowY: 'auto', paddingRight: 8, position: 'relative' }}>
<Spin spinning={loading} tip={t('common.loading')}>
<Form form={paramForm} layout="vertical" onFinish={saveParam}>
{/* 增益滑块行 */}
<Row gutter={16}>
{editableKeys.map((key) => {
const field = paramFieldConfigs.find(f => f.key === key);
if (!field) return null;
const isGainSliderField = ['leftForwardGain', 'leftBackwardGain', 'rightForwardGain', 'rightBackwardGain'].includes(key);
{gainFields.map((field) => {
const disabled = !field.editable;
return (
<Col span={12} key={key}>
<Col span={12} key={field.key}>
<Form.Item
label={<span style={{ fontWeight: 500 }}>{field.label}</span>}
name={field.key}
>
{isGainSliderField ? (
<GainSliderInput
disabled={disabled}
min={field.min}
max={field.max}
step={0.01}
/>
) : (
<InputNumber
style={{ width: '100%' }}
disabled={disabled}
min={field.min}
max={field.max}
step={field.step}
placeholder={typeof field.min === 'number' ? `${field.min}~${field.max}` : ''}
/>
)}
<GainSliderInput
disabled={disabled}
min={field.min}
max={field.max}
step={field.step}
/>
</Form.Item>
</Col>
);
})}
</Row>
{/* runSpeed + 其余全部只读字段 */}
<Row gutter={16}>
{paramFieldConfigs.filter(f => !editableKeys.includes(f.key)).map((field) => {
{otherFields.map((field) => {
const disabled = !field.editable;
return (
<Col span={12} key={field.key}>
@@ -300,14 +349,24 @@ const DeviceParamModal: React.FC<DeviceParamModalProps> = ({ open, device, onCan
name={field.key}
valuePropName={field.type === 'Checkbox' ? 'checked' : undefined}
>
{field.type === 'InputNumber' ? (
{field.type === 'Select' ? (
<Select
style={{ width: '100%' }}
disabled={disabled}
allowClear
showSearch
optionFilterProp="label"
options={field.options}
placeholder={t('devices.noData')}
/>
) : field.type === 'InputNumber' ? (
<InputNumber
style={{ width: '100%' }}
disabled={disabled}
min={field.min}
max={field.max}
step={field.step}
placeholder={typeof field.min === 'number' ? `${field.min}~${field.max}` : ''}
placeholder={typeof field.min === 'number' ? `${field.min}~${field.max}` : t('devices.noData')}
/>
) : field.type === 'Checkbox' ? (
<Checkbox disabled={disabled} />
@@ -325,5 +384,4 @@ const DeviceParamModal: React.FC<DeviceParamModalProps> = ({ open, device, onCan
</Modal>
);
};
export default DeviceParamModal;

File diff suppressed because it is too large Load Diff

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,92 @@ 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: () => {};
sendAutoBack?: () => {};
}
const RobotFeatureButtons: React.FC<RobotFeatureButtonsProps> = ({
activeFeatures = [],
onToggle,
className = '',
showEmergencyStop = true,
sendFindCar,
sendAutoBack
}) => {
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?.();
}
if (feature === 'autoback') {
sendAutoBack?.();
}
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',
cursor: 'pointer',
}}
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

@@ -1,4 +1,4 @@
import React, { useState, useEffect, useRef, useMemo } from 'react';
import React, { useState, useEffect, useRef, useMemo } from 'react';
import {
Row, Col, Card, Button, Space, Table, Tag, Typography, Progress, Badge,
Tabs, Input, Switch, Divider, Tooltip, Timeline, Select, message, DatePicker,
@@ -62,8 +62,8 @@ export default function RobotTaskPage() {
const { userInfo } = useSelector((state: RootState) => state.user);
const { stationId, currentStation } = useSelector((state: RootState) => state.station);
const [excuteStatus, setExcuteStatus] = useState("stop"); //"stop" "running" "pause"
// 机器人实时位置
const [robotRealtimePosition, setRobotRealtimePosition] = useState(null);
// 全量设备实时状态(mapPush),实时数据统一从这里取
const [realtimeMap, setRealtimeMap] = useState<any>({});
const [execute, setExecute] = useState(false); // 是否执行任务
const [taskList, setTaskList] = useState([]);
const [arrivedPoint, setArrivedPoint] = useState(null);//完成点
@@ -266,7 +266,7 @@ export default function RobotTaskPage() {
setExecute(true);
setExecutingRobot(targetDevice);
setClearNavLine(v => v + 1); // 清空地图轨迹
if (isFirstConnect.current) { isFirstConnect.current = false; controllerRef.current?.connectDevice(targetDevice); } else { controllerRef.current?.switchDevice(targetDevice); }
//if (isFirstConnect.current) { isFirstConnect.current = false; controllerRef.current?.connectDevice(targetDevice); } else { controllerRef.current?.switchDevice(targetDevice); }
//setShowVideo(true);
};
@@ -274,10 +274,10 @@ export default function RobotTaskPage() {
useEffect(() => {
const controller = new DeviceController(userInfo, messageApi);
controller.onLocationInfoUpdate = setRobotRealtimePosition;
// 实时数据统一从全量设备状态(mapPush)获取,不再订阅单机 WS 的实时数据
controller.onIsFinished = handleFinish;
controller.onIsExecuting = handleRreshTask;
controller.handleArrivedPoint = handleFinishEdPoint;
// 处理路线点回调:taskId必须和当前选中任务一致
controller.onRoutePost = (msg) => {
console.log('收到 route_post 消息:', msg);
@@ -288,7 +288,6 @@ export default function RobotTaskPage() {
controller.init();
controllerRef.current = controller;
return () => {
if (controllerRef.current) {
@@ -301,6 +300,17 @@ export default function RobotTaskPage() {
}, []);
// 全量设备实时状态 WebSocket(mapPush):实时数据统一从这里获取,退出页面断开连接
useEffect(() => {
if (!userInfo || !stationId || !controllerRef.current) return;
const controller = controllerRef.current;
controller.siteId = stationId;
controller.initMapPush((rtMap: any) => setRealtimeMap(rtMap || {}));
return () => {
controller.closeMapPush?.();
};
}, [userInfo, stationId]);
// 监听任务列表和设备列表变化,自动连接正在执行中的机器人(仅在没有选择任务时)
useEffect(() => {
if (!taskPoolList || taskPoolList.length == 0) {
@@ -338,7 +348,7 @@ export default function RobotTaskPage() {
// 切换设备
console.log('🔄 检测到正在执行任务的新设备,开始连接', targetDevice);
if (isFirstConnect.current) { isFirstConnect.current = false; controllerRef.current?.connectDevice(targetDevice); } else { controllerRef.current?.switchDevice(targetDevice); }
//if (isFirstConnect.current) { isFirstConnect.current = false; controllerRef.current?.connectDevice(targetDevice); } else { controllerRef.current?.switchDevice(targetDevice); }
//setShowVideo(true);
}, [devices, taskPoolList, executingRobot, runningPoolTask]);
@@ -352,6 +362,29 @@ export default function RobotTaskPage() {
}, [runningPoolTask, proPoints]);
// 从全量设备状态(mapPush)里匹配当前设备
const pickRealtimeRecord = (rtMap: any, d: any) => {
for (const key of [d?.serialNumber, d?.device_sn, d?.sn, d?.id, d?.deviceId]) {
if (key == null || String(key) === '') continue;
const hit = rtMap?.[String(key)];
if (hit) return hit;
}
return null;
};
// 全量数据字段名归一(lng/lat/fixStatus → 页面原有字段名)
const robotRealtimePosition = useMemo(() => {
const rt = pickRealtimeRecord(realtimeMap, executingRobot);
if (!rt) return null;
return {
...rt,
longitude: rt.lng,
latitude: rt.lat,
fix_status: rt.fixStatus,
controlMode: rt.controlMode ?? executingRobot?.lastRunningStatus?.controlMode,
};
}, [realtimeMap, executingRobot]);
const realtimePosition = useMemo(() => {
let lon = robotRealtimePosition?.longitude;
let lat = robotRealtimePosition?.latitude;
@@ -582,7 +615,7 @@ export default function RobotTaskPage() {
setExecute(true);
setExecutingRobot(targetDevice);
setClearNavLine(v => v + 1); // 清空地图轨迹
if (isFirstConnect.current) { isFirstConnect.current = false; controllerRef.current?.connectDevice(targetDevice); } else { controllerRef.current?.switchDevice(targetDevice); }
//if (isFirstConnect.current) { isFirstConnect.current = false; controllerRef.current?.connectDevice(targetDevice); } else { controllerRef.current?.switchDevice(targetDevice); }
//setShowVideo(true);
}
}
@@ -664,7 +697,7 @@ export default function RobotTaskPage() {
fetchTaskList();
fetchTaskPoolList();
fetchTaskHistoryList();
if (isFirstConnect.current) { isFirstConnect.current = false; controllerRef.current?.connectDevice(selectedRobotForExecute); } else { controllerRef.current?.switchDevice(selectedRobotForExecute); }
//if (isFirstConnect.current) { isFirstConnect.current = false; controllerRef.current?.connectDevice(selectedRobotForExecute); } else { controllerRef.current?.switchDevice(selectedRobotForExecute); }
//setShowVideo(true); // 连接成功后自动打开视频
} else {
@@ -1734,22 +1767,11 @@ export default function RobotTaskPage() {
{route.workName || route.name || t('devices.unnamedRoute')}
</div>
<div style={{ fontSize: 12, color: '#86909C', marginTop: 4 }}>
ID: {route.id}
{t('devices.rtMode')}: {route.mode == "coverage" ? t('devices.coverageMode') : t('devices.singleMode')}
</div>
</div>
{/* 删除按钮 */}
<Tooltip title={t('devices.deleteRoute')}>
<Button
type="text"
icon={<DeleteOutlined style={{ color: '#F53F3F', fontSize: 20 }} />}
onClick={(e) => {
e.stopPropagation();
setSelectedPathWork(route);
// 替换为你的删除处理函数
handleDeleteRoute(route);
}}
/>
</Tooltip>
<Tooltip title={t('devices.createTask')}>
<Button
type="text"
@@ -2015,6 +2037,22 @@ const NewTaskModal = ({ isOpen, onClose, robots, selectedPathWork, handlGetTaskL
}, [selectedPathWork]);
// ====================== Tab / 返航任务 ======================
const [activeTab, setActiveTab] = useState('scheduled');
const [returnRoute, setReturnRoute] = useState(null);
const [returnDevice, setReturnDevice] = useState(null);
// 预设路径:仅保留单次任务路径
const singleRouteList = useMemo(
() => (routeList || []).filter(route => route.mode == 'single_point'),
[routeList]
);
const handleSaveReturnTask = () => {
// TODO: 返航任务保存接口待接入,暂时打印
console.log('新建返航任务', { route: returnRoute, device: returnDevice });
};
// ====================== 周/月选择 ======================
const weekDays = [
{ label: t('devices.wdSun'), value: 'SUNDAY' },
@@ -2137,144 +2175,208 @@ const NewTaskModal = ({ isOpen, onClose, robots, selectedPathWork, handlGetTaskL
>
<div className="space-y-4">
{/* 任务名称 */}
<div>
<label className="block mb-2 font-medium">{t('devices.taskName')}</label>
<Input
value={formData.planName}
onChange={(e) => setFormData({ ...formData, planName: e.target.value })}
placeholder={t('devices.inputTaskName')}
/>
</div>
{/*<Tabs
activeKey={activeTab}
onChange={setActiveTab}
items={[
{ key: 'scheduled', label: t('devices.scheduledTaskTab') },
{ key: 'return', label: t('devices.returnTaskTab') },
]}
/>*/}
{/* 执行路线 */}
<div>
<label className="block mb-2 font-medium">{t('devices.executeRouteLabel')}</label>
<Select
className="w-full"
placeholder={t('devices.selectRoute')}
onSelect={(_, option) => {
const route = routeList.find(r => r.id === option.value);
setFormData(prev => ({ ...prev, path: route }));
}}
value={formData.path?.id}
>
{routeList.map(route => (
<Select.Option
key={route.id}
value={route.id}
>
{route.workName || route.name}
</Select.Option>
))}
</Select>
</div>
{/* 选择设备 */}
<div className="relative">
<label className="block mb-2 font-medium">{t('video.selectDevice')}</label>
<Select
className="w-full"
placeholder={t('video.selectDevice')}
onSelect={(_, option) => {
const robot = robots.find(r => r.serialNumber === option.value);
setFormData(prev => ({ ...prev, device: robot }));
}}
value={formData.device?.serialNumber}
>
{robots.map(robot => (
<Select.Option
key={robot.serialNumber}
value={robot.serialNumber}
>
{robot.deviceAlias} ({robot.serialNumber})
</Select.Option>
))}
</Select>
</div>
{/* 重复计划 */}
<div>
<label className="block mb-2 font-medium">{t('devices.repeatPlan')}</label>
<Select
value={formData.repeatPlan}
onChange={(val) => setFormData({ ...formData, repeatPlan: val })}
className="w-full"
>
<Select.Option value="DAY">{t('devices.day')}</Select.Option>
<Select.Option value="WEEK">{t('devices.week')}</Select.Option>
<Select.Option value="MONTH">{t('devices.month')}</Select.Option>
</Select>
</div>
{/* 周选择 */}
{formData.repeatPlan === 'WEEK' && (
<div className="flex gap-1 flex-wrap">
{weekDays.map(day => (
<Button
key={day.value}
type={formData.days.includes(day.value) ? 'primary' : 'default'}
onClick={() => handleToggleDay(day.value)}
size="small"
shape="circle"
>
{day.label}
</Button>
))}
</div>
)}
{/* 月选择 */}
{formData.repeatPlan === 'MONTH' && (
<div className="grid grid-cols-7 gap-1">
{monthDays.map(day => (
<Button
key={day}
type={formData.dayOfMonth.includes(day) ? 'primary' : 'default'}
onClick={() => handleToggleMonthDay(day)}
size="small"
>
{day}
</Button>
))}
</div>
)}
{/* 按天:选择日期 */}
{formData.repeatPlan === 'DAY' && (
{activeTab === 'scheduled' ? (
<>
<label className="block mb-2 font-medium">{t('devices.execDate')}</label>
<DatePicker
onChange={handleDateChange}
{/* 任务名称 */}
<div>
<label className="block mb-2 font-medium">{t('devices.taskName')}</label>
<Input
value={formData.planName}
onChange={(e) => setFormData({ ...formData, planName: e.target.value })}
placeholder={t('devices.inputTaskName')}
/>
</div>
{/* 执行路线 */}
<div>
<label className="block mb-2 font-medium">{t('devices.executeRouteLabel')}</label>
<Select
className="w-full"
placeholder={t('devices.selectRoute')}
onSelect={(_, option) => {
const route = routeList.find(r => r.id === option.value);
setFormData(prev => ({ ...prev, path: route }));
}}
value={formData.path?.id}
>
{routeList.map(route => (
<Select.Option
key={route.id}
value={route.id}
>
{route.workName || route.name}
</Select.Option>
))}
</Select>
</div>
{/* 选择设备 */}
<div className="relative">
<label className="block mb-2 font-medium">{t('video.selectDevice')}</label>
<Select
className="w-full"
placeholder={t('video.selectDevice')}
onSelect={(_, option) => {
const robot = robots.find(r => r.serialNumber === option.value);
setFormData(prev => ({ ...prev, device: robot }));
}}
value={formData.device?.serialNumber}
>
{robots.map(robot => (
<Select.Option
key={robot.serialNumber}
value={robot.serialNumber}
>
{robot.deviceAlias} ({robot.serialNumber})
</Select.Option>
))}
</Select>
</div>
{/* 重复计划 */}
<div>
<label className="block mb-2 font-medium">{t('devices.repeatPlan')}</label>
<Select
value={formData.repeatPlan}
onChange={(val) => setFormData({ ...formData, repeatPlan: val })}
className="w-full"
>
<Select.Option value="DAY">{t('devices.day')}</Select.Option>
<Select.Option value="WEEK">{t('devices.week')}</Select.Option>
<Select.Option value="MONTH">{t('devices.month')}</Select.Option>
</Select>
</div>
{/* 周选择 */}
{formData.repeatPlan === 'WEEK' && (
<div className="flex gap-1 flex-wrap">
{weekDays.map(day => (
<Button
key={day.value}
type={formData.days.includes(day.value) ? 'primary' : 'default'}
onClick={() => handleToggleDay(day.value)}
size="small"
shape="circle"
>
{day.label}
</Button>
))}
</div>
)}
{/* 月选择 */}
{formData.repeatPlan === 'MONTH' && (
<div className="grid grid-cols-7 gap-1">
{monthDays.map(day => (
<Button
key={day}
type={formData.dayOfMonth.includes(day) ? 'primary' : 'default'}
onClick={() => handleToggleMonthDay(day)}
size="small"
>
{day}
</Button>
))}
</div>
)}
{/* 按天:选择日期 */}
{formData.repeatPlan === 'DAY' && (
<>
<label className="block mb-2 font-medium">{t('devices.execDate')}</label>
<DatePicker
onChange={handleDateChange}
className="w-full"
placeholder={t('devices.selectExecDate')}
/>
</>
)}
{/* 时间 */}
<label className="block mb-2 font-medium">{t('devices.execTime')}</label>
<TimePicker
format="HH:mm:ss"
onChange={handleTimeChange}
className="w-full"
placeholder={t('devices.selectExecDate')}
placeholder={t('devices.selectExecTime')}
/>
{/* 执行周期 */}
<label className="block mb-2 font-medium">{t('devices.executionCycle')}</label>
<RangePicker
onChange={handleCycleChange}
className="w-full"
placeholder={[t('devices.startDate'), t('devices.endDate')]}
showTime
format="YYYY-MM-DD HH:mm:ss"
/>
</>
) : (
<div className="space-y-4">
{/* 预设路径列表 */}
<div>
<label className="block mb-2 font-medium">{t('devices.presetRoutes')}</label>
<div className="max-h-64 overflow-y-auto space-y-2 pr-1">
{singleRouteList.length === 0 ? (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={t('devices.noReturnRoute')} />
) : (
singleRouteList.map(route => {
const selected = returnRoute?.id === route.id;
return (
<div
key={route.id}
onClick={() => setReturnRoute(route)}
className={`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${selected ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:border-blue-300'}`}
>
<div className="w-10 h-10 rounded overflow-hidden bg-gray-100 flex items-center justify-center shrink-0">
{route.imgUrl ? (
<img src={route.imgUrl} alt="" className="w-full h-full object-cover" />
) : (
<EyeOutlined className="text-gray-400" />
)}
</div>
<div className="flex-1 min-w-0 font-medium truncate">{route.workName || route.name}</div>
{selected && <CheckCircle2 size={18} className="text-blue-500 shrink-0" />}
</div>
);
})
)}
</div>
</div>
{/* 选择机器 */}
<div>
<label className="block mb-2 font-medium">{t('video.selectDevice')}</label>
<Select
className="w-full"
placeholder={t('video.selectDevice')}
allowClear
value={returnDevice?.serialNumber}
onChange={(val) => setReturnDevice((robots || []).find(r => r.serialNumber === val) || null)}
options={(robots || []).map(robot => ({
value: robot.serialNumber,
label: `${robot.deviceAlias ?? ''} ${robot.serialNumber}`,
}))}
/>
</div>
</div>
)}
{/* 时间 */}
<label className="block mb-2 font-medium">{t('devices.execTime')}</label>
<TimePicker
format="HH:mm:ss"
onChange={handleTimeChange}
className="w-full"
placeholder={t('devices.selectExecTime')}
/>
{/* 执行周期 */}
<label className="block mb-2 font-medium">{t('devices.executionCycle')}</label>
<RangePicker
onChange={handleCycleChange}
className="w-full"
placeholder={[t('devices.startDate'), t('devices.endDate')]}
showTime
format="YYYY-MM-DD HH:mm:ss"
/>
{/* 底部按钮 */}
<div className="flex justify-end gap-2 mt-6">
<Button onClick={onClose}>{t('common.cancel')}</Button>
<Button type="primary" onClick={handleSave}>{t('devices.saveTask')}</Button>
<Button type="primary" onClick={activeTab === 'scheduled' ? handleSave : handleSaveReturnTask}>{t('devices.saveTask')}</Button>
</div>
</div>
</Modal>

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;

View File

@@ -141,6 +141,7 @@ export default class DeviceController {
battery: it?.b !== undefined ? Number(it.b) : (it?.batteryLevel !== undefined ? Number(it.batteryLevel) : undefined),
hasAlarm: !!it?.ha || !!it?.hasAlarm,
updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
controlMode: it?.cm ?? it?.controlMode,
};
});
console.log('[DeviceController] 收到全量设备状态', next);

View File

@@ -286,7 +286,7 @@
idle: 'Idle',
busy: 'Busy',
error: 'Error',
deviceControl: 'Device Control',
deviceControl: 'Robot Control',
realtimeVideo: 'Live Video',
takeoff: 'Take Off',
land: 'Land',
@@ -378,7 +378,6 @@
rtkFixed: 'RTK Fixed',
networkLatency: 'Network Latency',
waterRiskWarning: 'Warning: Water accumulation risk in Area B, avoid it',
presetRoutes: 'Preset Routes',
all: 'All',
stop: 'Stop',
currentTask: 'Current Task',
@@ -450,6 +449,10 @@
selectExecDate: 'Select date',
execTime: 'Execution Time',
saveTask: 'Save Task',
scheduledTaskTab: 'Scheduled Task',
returnTaskTab: 'Return Task',
presetRoutes: 'Preset Routes',
noReturnRoute: 'No single-task routes available',
abMode: 'ab Mode',
activatedTime: 'Activated Time',
aiAction1: 'ai Action1',
@@ -632,6 +635,57 @@
landingDockSnLabel: 'Landing Dock Sn Label',
leftView: 'Left View',
leftWheelDrive: 'Left Wheel Drive',
gamepadControl: 'Gamepad Control',
steeringControl: 'Steering Control',
disconnectGamepadFirst: 'Please disconnect the gamepad first',
liveBadge: 'Live',
totalWorkArea: 'Total Work Area',
totalWorkDuration: 'Total Work Duration',
totalWorkDistance: 'Total Work Distance',
motionStatus: 'Motion Status',
motionMoving: 'Moving',
motionStopped: 'Stopped',
motionBlocked: 'Blocked',
rtEmergency: 'Emergency Stop',
estopTriggered: 'Triggered',
estopNormal: 'Normal',
rtLeftTargetRpm: 'Left Target RPM',
rtRightTargetRpm: 'Right Target RPM',
rtLeftMeasureRpm: 'Left Measured RPM',
rtRightMeasureRpm: 'Right Measured RPM',
rtLeftMotorRpm: 'Left Motor RPM',
rtRightMotorRpm: 'Right Motor RPM',
gamepad: {
leftStick: 'Left Stick',
leftStickDesc: 'Control direction',
rightStick: 'Right Stick',
rightStickDesc: 'Control arm',
aKey: 'A Key',
aKeyDesc: 'Raise chassis',
bKey: 'B Key',
bKeyDesc: 'Lower chassis',
xKey: 'X Key',
xKeyDesc: 'Cutter faster',
yKey: 'Y Key',
yKeyDesc: 'Cutter slower',
lbKey: 'LB',
lbDesc: 'Ignition',
rbKey: 'RB',
rbDesc: 'Shut Down',
},
steer: {
ignition: 'Ignition',
ignitionHint: 'Start engine',
shutdown: 'Shut Down',
shutdownHint: 'Stop engine',
chassisUp: 'Raise Chassis',
chassisUpHint: 'Chassis up',
chassisDown: 'Lower Chassis',
chassisDownHint: 'Chassis down',
cutterControl: 'Cutter Control',
cutterAccel: 'Cutter Faster',
cutterDecel: 'Cutter Slower',
},
features: {
title: 'Feature Control',
emergencyStop: 'Emergency Stop',
@@ -728,12 +782,14 @@
optionalEmpty: 'Optional Empty',
otherWebControlling: 'Other Web Controlling',
platformRequestControl: "{{platform}} platformRequestControl",
coverageMode: 'coverageMode',
singleMode: 'singleMode',
outDock: 'Out Dock',
outdoor: 'Outdoor',
panorama: 'Panorama',
paramArmChannel: 'Param Arm Channel',
paramBatteryType: 'Param Battery Type',
batteryType: ' Battery Type',
paramChassisChannel: 'Param Chassis Channel',
paramChipUid: 'Param Chip Uid',
paramChipUidSign: 'Param Chip Uid Sign',
@@ -772,7 +828,7 @@
paramThrottleChannel: 'Param Throttle Channel',
paramThrottlePolarity: 'Param Throttle Polarity',
paramTurnSpeedLimit: 'Param Turn Speed Limit',
paramTyreSize: 'Param Tyre Size',
tyreSize: 'Tyre Size',
paramUse4G: 'Param Use4G',
paramViewEditTitle: 'Param View Edit Title',
paramWalkMotorMode: 'Param Walk Motor Mode',
@@ -802,6 +858,94 @@
realtimePicture: 'Realtime Picture',
realtimePowerData: 'Realtime Power Data',
realtimeSpeed: 'Realtime Speed',
forwardSpeed: 'Forward Speed',
"deviceId": "Device ID",
"walkingDriveType": "Walking Drive Type",
"cutterDriveType": "Cutter Drive Type",
"rtkAntennasNum": "RTK Antennas Number",
"handleType": "Handle Type",
"pcbVersion": "PCB Version",
"dimensions": "Dimensions",
"bladeWidth": "Blade Width",
"speedRatio": "Speed Ratio",
"cellularInfo": "Cellular Info",
"bluetoothName": "Bluetooth Name",
"hardwareIdentifiers": "Hardware Identifiers",
"imuModel": "IMU Model",
"tempHumiditySensor": "Temp Humidity Sensor",
"barometerPresent": "Barometer Present",
"ultrasonicPresent": "Ultrasonic Present",
"dacPresent": "DAC Present",
"operator": "Operator",
"inspectionNo": "Inspection No",
"activeTime": "Active Time",
"dealer": "Dealer",
paramEnum: {
deviceTypeM: 'Mower',
deviceTypeI: 'Inspection',
deviceTypeU: 'UAV',
wheelTypeW: 'Wheel',
wheelTypeT: 'Track',
powerTypeE: 'Electric',
powerTypeH: 'Hybrid',
rtkModeN: 'Network',
rtkModeB: 'Base Station',
engineTypeH: 'Honda',
engineTypeL: 'Loncin',
engineTypeZ: 'None',
hasHostNo: 'No',
hasHostYes: 'Yes',
batteryLeadAcid: 'Lead-acid',
batteryLithium: 'Lithium',
rtkAntennaSingle: 'Single antenna',
rtkAntennaDual: 'Dual antenna',
handleSbus: 'SBUS',
handleCustom: 'Custom',
},
mapEditor: {
returnPoint: 'Return Point',
legend: 'Legend',
unbound: 'Unbound',
duplicateBindDevice: 'Duplicate Bind Device',
restArea: 'Region',
region: 'Region',
routeGen: 'Route Planning',
toolPoint: 'Click',
toolBox: 'Box',
routeTip: 'Click on map to drop points in order',
undo: 'Undo',
clearAll: 'Clear All',
mapClickHint: 'Click on map to add a marker',
routeClickHint: 'Click on map to add route points in order',
pointCount: 'Points',
routeGenTitle: 'Route Planning',
routeName: 'Route Name',
routeNamePlaceholder: 'Enter route name',
routeType: 'Route Type',
typeMowing: 'Mowing Task',
typeInspection: 'Inspection Task',
typeOther: 'Other',
remark: 'Remark',
remarkPlaceholder: 'Optional',
selectRobot: 'Select Robot',
pointSelect: 'Point Select',
selectRobotFirst: 'Please select a robot first',
robotPosNotReady: 'Robot real-time position is not ready, please wait',
unbind: 'Unbound',
returnPointList: 'Return Point List',
restAreaList: 'Region List',
regionList: 'Region List',
routePoints: 'Route Points',
pointEmptyHint: 'No markers yet. Click on map to add.',
routeEmptyHint: 'No route points yet. Click on map to add in order.',
save: 'Save',
saveSuccess: 'Saved successfully',
mapEditorTitle: 'Map Editor',
fillName: 'Please enter route name',
needAtLeast2Points: 'At least 2 points required',
}, turnSpeed: 'Turn Speed',
realtimeVideoMonitor: 'Realtime Video Monitor',
rechargeBtn: 'Recharge Btn',
rechargeCommandSent: 'Recharge Command Sent',
@@ -852,6 +996,7 @@
routeSavedLocal: 'Route Saved Local',
rtBattery: 'Battery',
rtHeadingAngle: 'rt Heading Angle',
rtRollAngle: 'rt Roll Angle',
rtHeadingStatus: 'rt Heading Status',
rtInitialized: 'rt Initialized',
rtLeftMotor: 'Left Motor',
@@ -3790,3 +3935,7 @@
};
export default en;

View File

@@ -301,7 +301,7 @@ const zh = {
idle: '空闲',
busy: '忙碌',
error: '故障',
deviceControl: '设备控制',
deviceControl: '机器人控制',
realtimeVideo: '实时视频',
takeoff: '起飞',
land: '降落',
@@ -466,6 +466,9 @@ const zh = {
selectExecDate: '选择执行日期',
execTime: '执行时间',
saveTask: '保存任务',
scheduledTaskTab: '定时任务',
returnTaskTab: '返航任务',
noReturnRoute: '暂无单次任务路径',
abMode: '自定义模式',
saveFail: '保存失败',
@@ -541,6 +544,8 @@ const zh = {
countUnit: '数量单位',
coverClosed: '已关闭',
coverOpen: '打开',
coverageMode: '覆盖模式',
singleMode: '单点模式',
coverageEquipment: '覆盖设备',
coverageValue: '{{types}}/{{units}}',
createSuccess: '创建成功',
@@ -657,6 +662,59 @@ const zh = {
leftWheelDrive: '左轮驱动',
locationUnknown: '定位未知',
gamepadControl: '手柄控制',
steeringControl: '方向盘控制',
disconnectGamepadFirst: '请先断开手柄',
liveBadge: '直播中',
totalWorkArea: '累计作业面积',
totalWorkDuration: '累计作业时长',
totalWorkDistance: '累计作业里程',
motionStatus: '运动状态',
motionMoving: '行进中',
motionStopped: '已停止',
motionBlocked: '受阻',
rtEmergency: '急停状态',
estopTriggered: '已触发',
estopNormal: '正常',
rtLeftTargetRpm: '左目标转速',
rtRightTargetRpm: '右目标转速',
rtLeftMeasureRpm: '左测量转速',
rtRightMeasureRpm: '右测量转速',
rtLeftMotorRpm: '左电机转速',
rtRightMotorRpm: '右电机转速',
forwardSpeed: '前进速度',
turnSpeed: '转向速度',
gamepad: {
leftStick: '左摇杆',
leftStickDesc: '控制行进方向',
rightStick: '右摇杆',
rightStickDesc: '控制左右',
aKey: 'A 键',
aKeyDesc: '升底盘',
bKey: 'B 键',
bKeyDesc: '降底盘',
xKey: 'X 键',
xKeyDesc: '割刀加速',
yKey: 'Y 键',
yKeyDesc: '割刀减速',
lbKey: 'LB 键',
lbDesc: '点火',
rbKey: 'RB 键',
rbDesc: '熄火',
},
steer: {
ignition: '点火',
ignitionHint: '发动机启动',
shutdown: '熄火',
shutdownHint: '关闭发动机',
chassisUp: '底盘升起',
chassisUpHint: '底盘上升',
chassisDown: '底盘下降',
chassisDownHint: '底盘下降',
cutterControl: '割刀控制',
cutterAccel: '割刀加速',
cutterDecel: '割刀减速',
},
features: {
title: '功能控制',
emergencyStop: '急停',
@@ -757,7 +815,7 @@ const zh = {
outdoor: '室外',
panorama: '全景',
paramArmChannel: '布防渠道',
paramBatteryType: '电量类型',
batteryType: '电池类型',
paramChassisChannel: '底盘渠道',
paramChipUid: '芯片UID',
paramChipUidSign: '芯片UID标识',
@@ -796,7 +854,7 @@ const zh = {
paramThrottleChannel: '油门渠道',
paramThrottlePolarity: '油门极性',
paramTurnSpeedLimit: '转向速度限制',
paramTyreSize: '轮胎大小',
tyreSize: '轮胎尺寸',
paramUse4G: '4G',
paramViewEditTitle: '参数查看编辑',
paramWalkMotorMode: '行走电机模式',
@@ -882,16 +940,17 @@ const zh = {
rtHeadingAngle: '航向角度',
rtHeadingStatus: '航向状态',
rtInitialized: '已初始化',
rtLeftMotor: '左电机',
rtLeftMotor: '左电机电流',
rtLeftSpeed: '左速度',
rtLeftTemp: '左温度',
rtMainTemp: '主温度',
rtLeftTemp: '左电机温度',
rtMainTemp: '芯片温度',
rtMode: '模式',
rtPitchAngle: '俯仰角度',
rtRollAngle: '翻滚角度',
rtPositioning: '定位',
rtRightMotor: '右电机',
rtRightMotor: '右电机电流',
rtRightSpeed: '右速度',
rtRightTemp: '右温度',
rtRightTemp: '右电机温度',
rtSatellites: '卫星数量',
rtVoltage: '电压',
rthMode: '返航模式',
@@ -920,7 +979,7 @@ const zh = {
selectWayline: '选择航线',
selectedWaylineColon: '已选航线',
signalSatellite: '信号卫星',
situationMap: '态势地图',
situationMap: '地图',
smartAssign: '智能分配',
standbyCount: '待机数量',
startBtn: '开始按钮',
@@ -1395,8 +1454,120 @@ const zh = {
UnitsRobot: "台",
UnitsDrone: "架",
platformRequestControl: "{{platform}} 正在请求控制权限",
controlFailed: "controlFailed",
controlFailed: "控制失败",
"deviceId": "设备序列号",
"walkingDriveType": "行走驱动类型",
"cutterDriveType": "割刀驱动类型",
"rtkAntennasNum": "RTK天线数",
"handleType": "手柄类型",
"pcbVersion": "PCB硬件版本",
"dimensions": "长宽高",
"bladeWidth": "割刀宽度",
"speedRatio": "转速比",
"cellularInfo": "蜂窝网络通信信息",
"bluetoothName": "蓝牙广播名",
"hardwareIdentifiers": "硬件标识信息",
"imuModel": "IMU型号",
"tempHumiditySensor": "温湿度传感器",
"barometerPresent": "气压计在位",
"ultrasonicPresent": "超声波在位",
"dacPresent": "DAC在位",
"operator": "质检员",
"inspectionNo": "检测报告号",
"activeTime": "激活时间",
"dealer": "经销商",
paramEnum: {
deviceTypeM: '割草机',
deviceTypeI: '巡检',
deviceTypeU: '无人机',
wheelTypeW: '轮式',
wheelTypeT: '履带',
powerTypeE: '纯电',
powerTypeH: '混动',
rtkModeN: '网络',
rtkModeB: '基站',
engineTypeH: '本田',
engineTypeL: '隆鑫',
engineTypeZ: '无',
hasHostNo: '无',
hasHostYes: '有',
batteryLeadAcid: '铅酸',
batteryLithium: '锂电',
rtkAntennaSingle: '单天线',
rtkAntennaDual: '双天线',
handleSbus: 'SBUS',
handleCustom: '自定义',
},
mapEditor: {
returnPoint: '返航点',
restArea: '分区',
legend: '图例',
unbound: '未绑定',
region: '分区',
routeGen: '路径生成',
toolPoint: '点选',
toolBox: '框选',
routeTip: '点击地图依次打点生成路径',
undo: '撤销',
clearAll: '清空',
mapClickHint: '点击地图添加标记点',
routeClickHint: '点击地图依次打点生成路径',
pointCount: '点数',
routeGenTitle: '路径生成',
routeName: '路径名称',
routeNamePlaceholder: '请输入路径名称',
routeType: '路径规划类型',
typeMowing: '割草任务',
typeInspection: '巡检任务',
typeOther: '其他类型',
remark: '备注',
remarkPlaceholder: '选填',
selectRobot: '选择机器人',
pointSelect: '点选',
selectRobotFirst: '请先选择机器人',
robotPosNotReady: '机器人实时位置尚未获取,请稍候',
unbind: '未绑定',
returnPointList: '返航点列表',
restAreaList: '分区列表',
regionList: '分区列表',
routePoints: '路径点',
pointEmptyHint: '暂无标记点,请在地图上点击添加',
routeEmptyHint: '暂无路径点,请在地图上依次点击打点',
duplicateBindDevice: '重复绑定设备',
bindUpdateSuccess: '绑定设备已更新',
save: '保存',
saveSuccess: '保存成功',
mapEditorTitle: '地图编辑',
fillName: '请填写路径名称',
needAtLeast2Points: '路径至少需要 2 个点',
// 已配置列表
configuredReturnPoints: '已配置返航点',
configuredRegions: '已配置分区',
noConfiguredReturnPoints: '暂无已配置返航点',
noConfiguredRegions: '暂无已配置分区',
unnamed: '未命名',
regionCode: '分区编码',
scopeCount: '范围点数',
mode: '模式',
noPresetRoutes: '暂无预设路径',
confirmDeleteRoute: '确定删除该预设路径?',
// 分区保存 Modal
saveRegion: '保存分区',
editRegion: '编辑分区',
regionName: '分区名称',
regionNamePlaceholder: '请输入分区名称',
regionNameRequired: '请填写分区名称',
regionCodePlaceholder: '请输入分区编码(选填)',
defaultRoute: '默认线路',
selectRoutePlaceholder: '请选择默认线路',
bindRoutes: '绑定线路',
selectRoutesPlaceholder: '请选择绑定的预设路径',
currentScopePoints: '当前区域范围点数',
},
},
video: {
onlineVideo: '在线视频',
@@ -3848,3 +4019,6 @@ const zh = {
};
export default zh;

View File

@@ -26,7 +26,7 @@ export default function DeviceIndexPage() {
const menuItems = [
{ key: 'overview', label: t('devices.equipmentOverview'), icon: <AppstoreOutlined /> },
{ key: 'status', label: t('devices.deviceStatus'), icon: <SettingOutlined /> },
{ key: 'status', label: t('devices.deviceControl'), icon: <SettingOutlined /> },
{ key: 'wayLineTask', label: t('devices.waylineTask'), icon: <AimOutlined /> },
{ key: 'robotTask', label: t('devices.robotTask'), icon: <BranchesOutlined /> },
];

View File

@@ -48,10 +48,11 @@ export default function StationDashboard() {
const el = powerTrendCardRef.current;
if (!el) return;
try {
if (!document.fullscreenElement) {
await el.requestFullscreen();
} else {
// 只有当前全屏的是本卡片时才退出,否则请求卡片全屏(兼容页面整体全屏)
if (document.fullscreenElement === el) {
await document.exitFullscreen();
} else {
await el.requestFullscreen();
}
} catch (err) {
console.error('全屏切换异常:', err);
@@ -65,7 +66,8 @@ export default function StationDashboard() {
useEffect(() => {
const onFullScreenChange = () => {
setIsPowerCardFullscreen(!!document.fullscreenElement);
// 只有发电趋势卡片本身全屏时才拉伸,页面整体全屏时保持原有尺寸
setIsPowerCardFullscreen(document.fullscreenElement === powerTrendCardRef.current);
};
document.addEventListener('fullscreenchange', onFullScreenChange);
return () => {
@@ -326,7 +328,7 @@ export default function StationDashboard() {
<UniversalLineChart
data={powerTrendData}
xKey="time"
height={isPowerCardFullscreen ? window.innerHeight : 200}
height={isPowerCardFullscreen ? 'calc(100vh - 96px)' : 200}
smooth
dot
backgroundColor="transparent"

View File

@@ -1,4 +1,4 @@
import React, { lazy, Suspense } from 'react';
import React, { lazy, Suspense } from 'react';
import type { RouteObject } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
@@ -30,6 +30,7 @@ const Profile = lazy(() => import('../pages/Profile'));
const DeviceStatus = lazy(() => import('../components/devices/DeviceStatusPage'));
const WayLineTask = lazy(() => import('../components/devices/WayLinePage'));
const RobotTask = lazy(() => import('../components/devices/RobotTaskPage'));
const MapEditorPage = lazy(() => import('../components/devices/MapEditorPage'));
const DevicesOverview = lazy(() => import('../components/devices/DeviceOverviewPage'));
const BasicSettings = lazy(() => import('../components/SystemSetting/BasicSettings'));
@@ -124,6 +125,10 @@ export const routes: RouteObject[] = [
path: 'devices/robotTask',
element: withSuspense(RobotTask)
},
{
path: 'devices/mapEdit',
element: withSuspense(MapEditorPage)
},
{
path: 'video',
element: withSuspense(Video)