寻车功能 和返航按键 还有 任务excuting 推送 刷新功能 但是 没用,另一个电脑还没有 连接ws呢 难搞 加 另一个车道辅助线 组件实现

This commit is contained in:
mmc
2026-10-13 17:22:47 +08:00
parent 694a78ef9b
commit 51444b0142
9 changed files with 496 additions and 58 deletions

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 } from 'react';
import carImg from '../assets/images/carplane.png';
import inspectImg from "../assets/images/inspectCar.png"
import planeImg from '../assets/images/planeicon.png';
@@ -2554,7 +2554,28 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
// 暴露 ref 方法
useImperativeHandle(ref, () => ({
captureScreenshot
captureScreenshot,
// 寻车/定位:直接飞到指定经纬度,绕过飞行优先级系统,确保手动触发一定生效
flyToPosition: (position, options = {}) => {
const viewer = viewerRef.current;
if (!viewer || !position) return;
const { lon, lat } = position;
if (lon == null || lat == null || isNaN(Number(lon)) || isNaN(Number(lat))) return;
const Cesium = window.Cesium;
const height = options.height || 300;
const duration = options.duration ?? 1.5;
try { viewer.camera.cancelFlight(); } catch (e) { /* 忽略 */ }
lastFlightPriorityRef.current = -1;
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(Number(lon), Number(lat), height),
orientation: {
heading: Cesium.Math.toRadians(0.0),
pitch: Cesium.Math.toRadians(-90.0),
roll: 0.0,
},
duration,
});
},
}));
return (

View File

@@ -0,0 +1,132 @@
import React, { useEffect, useRef } from 'react';
type GuideLineProps = {
/** 方向 forward前进 reverse倒车 */
direction: 'forward' | 'reverse';
/** 方向盘转角,单位°:左转负数,右转正数,范围建议 -45 ~ 45 */
steer: number;
/** 画布宽度 */
width?: number;
/** 画布高度 */
height?: number;
/** 引导线底部(车尾端)两条线间距 */
bottomGap?: number;
/** 引导线顶部(远端)两条线间距 */
topGap?: number;
};
const CarReverseGuideLine: React.FC<GuideLineProps> = ({
direction,
steer,
width = 640,
height = 480,
bottomGap = 100,
topGap = 160,
}) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
ctx.clearRect(0, 0, width, height);
// 车尾中心点(画布底部)
const baseX = width / 2;
const baseY = height - 20;
const totalDist = direction === 'reverse' ? height * 0.82 : height * 0.68;
const maxWheelAngle = 45;
// 限制车轮转角范围
const wheelAngleRad = Math.max(-maxWheelAngle, Math.min(maxWheelAngle, steer)) * Math.PI / 180;
const step = 2; // 步长,越小曲线越平滑
// 迭代计算轨迹点函数
const getPathPoints = (side: 'left' | 'right'): [number, number][] => {
const points: [number, number][] = [];
let x = baseX;
let y = baseY;
let angle = -Math.PI / 2; // 初始朝向:向上(画布Y减小方向)
const stepCount = Math.floor(totalDist / step);
points.push([x, y]);
for (let i = 0; i < stepCount; i++) {
// 当前进度 0~1,0=底部起点,1=最远顶部
const progress = i / stepCount;
// 线性插值:从底部gap过渡到顶部gap
const currentGap = bottomGap * (1 - progress) + topGap * progress;
const sideOffset = side === 'left' ? -currentGap / 2 : currentGap / 2;
if (Math.abs(wheelAngleRad) < 0.001) {
// 回正:直线向上
y -= step;
} else {
// 有转向:改变朝向,再前进一小步
const turnStepRad = step * Math.tan(wheelAngleRad) / 240;
// 分母240:控制转弯曲率,调大转弯更平缓;调小弯更急
angle += turnStepRad;
x += Math.cos(angle) * step;
y += Math.sin(angle) * step;
}
// 叠加当前侧边偏移
const px = x + sideOffset;
const py = y;
points.push([px, py]);
// 超出画布提前停止绘制
if (py < 0 || px < 0 || px > width) break;
}
return points;
};
// 绘制左右两条轨迹
ctx.lineWidth = 3;
ctx.strokeStyle = '#0f0';
ctx.setLineDash([]);
const leftPath = getPathPoints('left');
const rightPath = getPathPoints('right');
const drawPath = (pts: [number, number][]) => {
ctx.beginPath();
pts.forEach(([px, py], idx) => {
if (idx === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
});
ctx.stroke();
ctx.beginPath(); // 强制清空当前路径缓存!重点!
};
drawPath(leftPath);
drawPath(rightPath);
// ========== 横向距离标记虚线 ==========
ctx.strokeStyle = '#ff0';
ctx.lineWidth = 2;
ctx.setLineDash([8, 6]);
const markCount = 3;
for (let m = 1; m <= markCount; m++) {
const ratio = m / (markCount + 1);
const idx = Math.floor(leftPath.length * ratio);
if (idx >= leftPath.length) continue;
const [lx, ly] = leftPath[idx];
const [rx, ry] = rightPath[idx];
ctx.beginPath();
ctx.moveTo(lx, ly);
ctx.lineTo(rx, ry);
ctx.stroke();
}
// ========== 车身底部框 ==========
//ctx.setLineDash([]);
//ctx.strokeStyle = '#0ff';
//ctx.lineWidth = 2;
//ctx.beginPath();
//ctx.rect(baseX - bottomGap / 2, baseY - 30, bottomGap, 30);
//ctx.stroke();
}, [direction, steer, width, height, bottomGap, topGap]);
return (
<div style={{ position: 'relative', width, height }}>
{/* 背景倒车画面,可以替换 video / img */}
<canvas
ref={canvasRef}
width={width}
height={height}
style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}
/>
</div>
);
};
export default CarReverseGuideLine;

View File

@@ -71,6 +71,8 @@ import { dataUrlToFile } from '@/lib/utils.ts';
import { useUnitFormatter } from '@/lib/units';
import { PauseOutlined, PlayCircleOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import CarReverseGuideLine from './CarReverseGuideLine';
const { RangePicker } = DatePicker;
const { Text } = Typography;
@@ -94,6 +96,9 @@ export default function DeviceStatusPage() {
const hasRequestedControlRef = useRef(false);
const [messageApi, contextHolder] = message.useMessage();
const [direction, setDirection] = useState<'forward' | 'reverse'>('reverse');
const [steer, setSteer] = useState(0);
// 视频播放开关
const [isVideoPlaying, setIsVideoPlaying] = useState(false);
@@ -463,25 +468,53 @@ export default function DeviceStatusPage() {
heading: currentDroneData.heading || 0,
};
}
// 无人机没有实时数据时,用 lastRunningStatus 兜底
const baseLon = device?.lastRunningStatus?.longitude || device?.longitude;
const baseLat = device?.lastRunningStatus?.latitude || device?.latitude;
if (baseLon && baseLat) {
return {
lon: Number(baseLon),
lat: Number(baseLat),
heading: device?.lastRunningStatus?.heading || 0,
};
}
return null;
}
// 2. 机器人:从 wsDeviceInfo / runningStatus 取实时经纬度
const robotLon = runningStatus?.longitude || wsDeviceInfo?.longitude;
const robotLat = runningStatus?.latitude || wsDeviceInfo?.latitude;
// 2. 机器人:优先从 wsDeviceInfo / runningStatus / locationInfo 取实时经纬度
let robotLon = runningStatus?.longitude || wsDeviceInfo?.longitude || locationInfo?.longitude;
let robotLat = runningStatus?.latitude || wsDeviceInfo?.latitude || locationInfo?.latitude;
// 3. 没有实时经纬度时,从 lastRunningStatus 兜底
if ((!robotLon || !robotLat) && (device?.lastRunningStatus || device?.locationMessage)) {
robotLon = robotLon || device?.lastRunningStatus?.longitude || device?.locationMessage?.longitude;
robotLat = robotLat || device?.lastRunningStatus?.latitude || device?.locationMessage?.latitude;
}
// 4. 最终兜底:设备静态经纬度
if ((!robotLon || !robotLat) && device) {
robotLon = robotLon || device.longitude;
robotLat = robotLat || device.latitude;
}
if (robotLon && robotLat) {
return {
lon: robotLon,
lat: robotLat,
//heading: -98
heading: runningStatus?.yaw || wsDeviceInfo?.yaw || 0,
heading: runningStatus?.yaw || wsDeviceInfo?.yaw || locationInfo?.yaw || device?.lastRunningStatus?.heading || 0,
};
}
return null;
}, [isUAV, currentDroneData, runningStatus, wsDeviceInfo]);
}, [isUAV, currentDroneData, runningStatus, wsDeviceInfo, locationInfo, device]);
// 寻车:地图定位到当前设备位置
const handleFindCar = () => {
if (!realtimePosition) {
messageApi.warning(t('devices.locationUnknown'));
return;
}
mapRef.current?.flyToPosition?.(realtimePosition, { height: 300 });
};
useEffect(() => {
const controller = new DeviceController(userInfo, messageApi);
@@ -927,6 +960,8 @@ export default function DeviceStatusPage() {
}
return (
<div style={{ background: 'linear-gradient(180deg, #f0f4f8 0%, #e8eef5 100%)', minHeight: '100%', padding: 0 }}>
<style>{`
@@ -936,6 +971,34 @@ export default function DeviceStatusPage() {
<div style={{ padding: '4px 0px 8px' }}>
<Typography.Title level={4} style={{ margin: 0, fontSize: 'clamp(14px, 1.2vw, 18px)' }}>{t('devices.deviceStatus')}</Typography.Title>
</div>
{/*<div style={{ marginBottom: 16 }}>
<button onClick={() => setDirection('reverse')} style={{ marginRight: 8 }}>倒车</button>
<button onClick={() => setDirection('forward')}>前进</button>
<div style={{ marginTop: 8 }}>
方向盘转角:{steer}°
<br />
<input
type="range"
min={-45}
max={45}
value={steer}
onChange={(e) => setSteer(Number(e.target.value))}
/>
<p>左滑:左转(负数)|右滑:右转(正数)</p>
</div>
</div>
<CarReverseGuideLine
direction="reverse"
steer={steer}
width={640}
height={480}
bottomGap={280} // 车尾端两条线间距
topGap={100} // 远端顶部两条线间距
/>*/}
<div style={{ padding: 0 }}>
{contextHolder}
@@ -1096,6 +1159,14 @@ export default function DeviceStatusPage() {
}
extra={
<Space size={4}>
<Button
size="small"
type="primary"
icon={<EnvironmentOutlined />}
onClick={handleFindCar}
>
{t('devices.features.findCar')}
</Button>
<Button
size="small"
type="primary"
@@ -1297,7 +1368,10 @@ export default function DeviceStatusPage() {
{/* 倒车影像叠加层:根据方向盘 xy 显示转向辅助线 */}
{/*{isVideoPlaying && (*/}
<ReverseCameraOverlay x={steerXY.x} y={steerXY.y} visible={true} />
{/*<CarReverseGuideLine direction={direction} steer={steer} />*/}
{/*<ReverseCameraOverlay x={steerXY.x} y={steerXY.y} visible={true} />*/}
{/*//)}*/}
{/* 视频未加载 / 停止播放的占位 */}
@@ -1395,6 +1469,14 @@ export default function DeviceStatusPage() {
}
extra={
<Space size={4}>
<Button
size="small"
type="primary"
icon={<EnvironmentOutlined />}
onClick={handleFindCar}
>
{t('devices.features.findCar')}
</Button>
<Button
size="small"
type="primary"

View File

@@ -13,7 +13,10 @@ export type RobotFeature =
| 'response'
| 'obstacleAvoidance'
| 'lowBatteryReturn'
| 'tiltProtection';
| 'tiltProtection'
| 'findCar'
| 'autoback';
export interface FeatureConfig {
key: RobotFeature;
@@ -27,6 +30,10 @@ const FEATURES: FeatureConfig[] = [
{ 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' },
];
interface RobotFeatureButtonsProps {

View File

@@ -15,7 +15,8 @@ import {
DeleteOutlined,
CloseOutlined,
ReloadOutlined,
ExclamationCircleOutlined
ExclamationCircleOutlined,
EnvironmentOutlined
} from '@ant-design/icons';
import {
Car, Navigation, Wind, Thermometer, Droplets, Satellite,
@@ -147,6 +148,7 @@ export default function RobotTaskPage() {
const [messageApi, contextHolder] = message.useMessage();
const controllerRef = useRef<DeviceController | null>(null);
const isFirstConnect = useRef(true);
const mapRef = useRef(null);
const fixStatusMap: Record<string, string> = {
'no_fix': t('devices.noFix'),
'single': t('devices.single'),
@@ -274,6 +276,7 @@ export default function RobotTaskPage() {
controller.onLocationInfoUpdate = setRobotRealtimePosition;
controller.onIsFinished = handleFinish;
controller.onIsExecuting = handleRreshTask;
controller.handleArrivedPoint = handleFinishEdPoint;
// 处理路线点回调:taskId必须和当前选中任务一致
controller.onRoutePost = (msg) => {
@@ -350,13 +353,53 @@ export default function RobotTaskPage() {
const realtimePosition = useMemo(() => {
const data = {
lon: robotRealtimePosition?.longitude || 0,
lat: robotRealtimePosition?.latitude || 0,
heading: robotRealtimePosition?.yaw || 0,
let lon = robotRealtimePosition?.longitude;
let lat = robotRealtimePosition?.latitude;
// 没有实时经纬度时,从 lastRunningStatus 兜底
if ((!lon || !lat) && executingRobot?.lastRunningStatus) {
lon = lon || executingRobot.lastRunningStatus.longitude;
lat = lat || executingRobot.lastRunningStatus.latitude;
}
return data;
}, [robotRealtimePosition])
// 最终兜底:设备静态经纬度
if ((!lon || !lat) && executingRobot) {
lon = lon || executingRobot.longitude;
lat = lat || executingRobot.latitude;
}
if (!lon || !lat || isNaN(Number(lon)) || isNaN(Number(lat))) return null;
return {
lon: Number(lon),
lat: Number(lat),
heading: robotRealtimePosition?.yaw || executingRobot?.lastRunningStatus?.heading || 0,
};
}, [robotRealtimePosition, executingRobot])
// 寻车:地图定位到当前机器人位置
const handleFindCar = () => {
// 1. 优先使用实时经纬度(WebSocket 推送)
let lon = robotRealtimePosition?.longitude;
let lat = robotRealtimePosition?.latitude;
console.log('实时经纬度:', lon, lat, executingRobot);
// 2. 没有实时经纬度时,从 lastRunningStatus 兜底
if ((!lon || !lat) && (executingRobot?.lastRunningStatus || executingRobot?.locationMessage)) {
lon = lon || executingRobot?.lastRunningStatus?.longitude || executingRobot?.locationMessage?.longitude;
lat = lat || executingRobot?.lastRunningStatus?.latitude || executingRobot?.locationMessage?.latitude;
}
// 3. 最终兜底:设备静态经纬度
if ((!lon || !lat) && executingRobot) {
lon = lon || executingRobot.longitude;
lat = lat || executingRobot.latitude;
}
if (lon && lat && !isNaN(Number(lon)) && !isNaN(Number(lat))) {
mapRef.current?.flyToPosition?.({ lon: Number(lon), lat: Number(lat) }, { height: 300 });
} else {
messageApi.warning(t('devices.locationUnknown'));
}
};
//useEffect(() => {
// if (robotRealtimePosition && execute) {
// let warningMsg = '';
@@ -640,6 +683,12 @@ export default function RobotTaskPage() {
const handleTaskCreated = () => {
resetFiltersAndRefresh();
};
const handleRreshTask = (data) => {
fetchTaskList();
fetchTaskPoolList();
fetchTaskHistoryList();
}
// 获取任务池数据
const fetchTaskPoolList = async () => {
@@ -1240,6 +1289,8 @@ export default function RobotTaskPage() {
>
<div style={{ width: '100%', height: 420, background: '#e8f3ff center/cover', position: 'relative' }}>
<CesiumMap
ref={mapRef}
//devices={devices}
devices={devices.filter(d => d.onlineStatus == 1)}
points={points}
focusLocation={focusLocation}
@@ -1309,6 +1360,47 @@ export default function RobotTaskPage() {
/>
</span>
{/* 寻车按钮 */}
<span
onClick={handleFindCar}
style={{
display: 'flex',
alignItems: 'center',
gap: 4,
padding: '3px 10px',
background: 'rgba(255,255,255,0.18)',
borderRadius: 12,
cursor: 'pointer',
whiteSpace: 'nowrap',
transition: 'background 0.2s',
}}
onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.3)'}
onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.18)'}
>
<EnvironmentOutlined />
{t('devices.features.findCar')}
</span>
<span
style={{
display: 'flex',
alignItems: 'center',
gap: 4,
padding: '3px 10px',
background: 'rgba(255,255,255,0.18)',
borderRadius: 12,
cursor: 'pointer',
whiteSpace: 'nowrap',
transition: 'background 0.2s',
}}
onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.3)'}
onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.18)'}
>
<EnvironmentOutlined />
{t('devices.features.autoback')}
</span>
</div>
)}

View File

@@ -44,6 +44,7 @@ export default class DeviceController {
this.onPermissionRequest = null;
this.onRoutePost = null;
this.onIsFinished = null;
this.onIsExecuting = null;
this.handleArrivedPoint = null;
// 全量设备实时状态(mapPush)连接
@@ -446,8 +447,15 @@ export default class DeviceController {
}
case "device_task_change": {
if (msg.deviceId != this.connectedDeviceSn) return;
this.onIsFinished?.(true);
console.log('task change:', msg);
if (msg.status == "FINISH") {
this.onIsFinished?.(true);
}
if (msg.status == "EXECUTING") {
this.onIsExecuting?.(true);
}
break;
}
case "device_task_arrive_point": {

View File

@@ -1,4 +1,4 @@
const en = {
const en = {
common: {
save: 'Save',
saveChanges: 'Save Changes',
@@ -384,6 +384,7 @@ const en = {
currentTask: 'Current Task',
realtimePosition: 'Real-time Position',
taskCompleted: 'Task completed',
locationUnknown: 'Unknown location',
deviceSerialNumberMissing: 'Device serial number missing',
confirmExecuteRoute: 'Confirm to execute this route?',
targetDevice: 'Target Device',
@@ -638,6 +639,8 @@ const en = {
obstacleAvoidance: 'Obstacle Avoidance',
lowBatteryReturn: 'Low Battery Return',
tiltProtection: 'Tilt Protection',
findCar: 'Find Car',
autoback: 'Auto Back',
},
dpad: {
title: 'Direction Control',

View File

@@ -1,4 +1,4 @@
import WeatherRainy from "@/src/components/Weather/WeatherRainy";
import WeatherRainy from "@/src/components/Weather/WeatherRainy";
const zh = {
common: {
@@ -655,6 +655,8 @@ const zh = {
landingDockSnLabel: '降落停靠序列号标签',
leftView: '左视角',
leftWheelDrive: '左轮驱动',
locationUnknown: '定位未知',
features: {
title: '功能控制',
emergencyStop: '急停',
@@ -662,6 +664,9 @@ const zh = {
obstacleAvoidance: '避障',
lowBatteryReturn: '低电量自动返航',
tiltProtection: '倾斜保护',
findCar: '寻车',
autoback: '返航',
},
dpad: {
title: '方向控制',
@@ -1015,12 +1020,12 @@ const zh = {
trendFlat: '趋势持平',
trendYesterday: '较昨日 {{diff}}',
typeAIRecheck: '类型AI复检',
typeArrayMow: '类型阵列除草',
typeComponentClean: '类型组件清洗',
typeDroneHotspot: '类型无人机热斑',
typeFenceInspect: '类型围栏巡检',
typeHotspotInspect: '类型热斑巡检',
typeRecheck: '类型复检',
typeArrayMow: '阵列除草',
typeComponentClean: '组件清洗',
typeDroneHotspot: '无人机热斑',
typeFenceInspect: '围栏巡检',
typeHotspotInspect: '热斑巡检',
typeRecheck: '复检',
unitGe: '个',
unitJia: '架',
unitTai: '台',

View File

@@ -160,6 +160,7 @@ const RealTimeMonitorPage = () => {
// 连接逻辑统一封装在 DeviceController 中
// ============================================================
const controllerRef = useRef<any>(null);
const mapRef = useRef(null);
useEffect(() => {
if (!userInfo || !stationId) return;
@@ -430,6 +431,43 @@ const RealTimeMonitorPage = () => {
// ============================================================
// 点击设备:仅打开侧边栏 + 地图定位(不再连接单台设备 WebSocket)
// ============================================================
// 仅定位设备(不打开抽屉):用于点击表格行
const handleLocateDevice = (robot) => {
const dev = robot;
const isDroneDevice = dev?.type === 'plane' || !!dev?.gateway_sn;
// 1. 优先使用实时经纬度(realtimeMap)
const rt = pickRealtimeRecord(realtimeMap, dev);
let lon = rt?.lng;
let lat = rt?.lat;
// 2. 没有实时经纬度时,使用 lastRunningStatus 中的经纬度
if ((!lon || !lat) && dev?.lastRunningStatus?.longitude && dev?.lastRunningStatus?.latitude) {
lon = dev.lastRunningStatus.longitude;
lat = dev.lastRunningStatus.latitude;
}
// 3. 兜底:locationMessage / 静态经纬度
if ((!lon || !lat) && dev?.locationMessage?.longitude && dev?.locationMessage?.latitude) {
lon = dev.locationMessage.longitude;
lat = dev.locationMessage.latitude;
}
if ((!lon || !lat) && dev?.longitude && dev?.latitude) {
lon = dev.longitude;
lat = dev.latitude;
}
if (lon && lat && !isNaN(Number(lon)) && !isNaN(Number(lat))) {
setFocusLocation({
lon: Number(lon),
lat: Number(lat),
type: isDroneDevice ? 'plane' : 'robot',
name: dev.deviceAlias || dev.deviceName || dev.drone_callsign || dev.serialNumber || dev.device_sn,
sn: dev.serialNumber || dev.device_sn || dev.id,
});
}
};
const handleDeviceClick = (robot) => {
console.log('[RTMonitor] 点击设备:', robot);
const dev = robot;
@@ -440,15 +478,7 @@ const RealTimeMonitorPage = () => {
const isDroneDevice = dev?.type === 'plane' || !!dev?.gateway_sn;
// ---- 地图定位 ----
if ((dev?.lastRunningStatus?.longitude && dev?.lastRunningStatus?.latitude) || (dev?.locationMessage?.longitude && dev?.locationMessage?.latitude) || (dev?.longitude && dev?.latitude)) {
setFocusLocation({
lon: Number(dev.lastRunningStatus?.longitude || dev.locationMessage?.longitude || dev.longitude),
lat: Number(dev.lastRunningStatus?.latitude || dev.locationMessage?.latitude || dev.latitude),
type: isDroneDevice ? 'plane' : 'robot',
name: dev.deviceAlias || dev.deviceName || dev.drone_callsign || dev.serialNumber || dev.device_sn,
sn: dev.serialNumber || dev.device_sn || dev.id,
});
}
handleLocateDevice(dev);
// ---- 逆变器/模拟设备:仅地图定位,不打开抽屉 ----
if (isMockDevice) {
@@ -547,36 +577,37 @@ const RealTimeMonitorPage = () => {
{
title: t('devices.deviceName'), dataIndex: 'name', key: 'name',
render: (text, record) => (
<a onClick={() => handleDeviceClick(record.raw || record)} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<div style={{ width: 24, height: 24, background: '#f5f5f5', borderRadius: 4, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
{record.type?.includes?.('INV') ? <ThunderboltOutlined style={{ fontSize: 14 }} /> : getDeviceTypeIcon(record.type)}
</div>
<span style={{ fontSize: 13 }}>{text}</span>
</a>
</span>
)
},
{ title: t('common.type'), dataIndex: 'typeText', render: (t) => <span style={{ fontSize: 13, color: '#666' }}>{t}</span> },
{ title: t('workOrder.currentStatus'), dataIndex: 'feStatus', render: getStatusTag },
//{ title: t('page.fixed2RealtimePower'), dataIndex: 'data', render: (d) => <span style={{ fontSize: 13, fontWeight: 500 }}>{d}</span> },
//{
// title: t('page.statusFixed2'), dataIndex: 'communication',
// render: (c) => (
// <Space size={4}>
// <span style={{ fontSize: 13 }}>{c}</span>
// <RiseOutlined style={{ color: '#52c41a' }} />
// </Space>
// )
//},
//{
// title: t('common.action'), key: 'action', width: 80,
// render: (_, record) => (
// <Tooltip title={t('page.viewDeviceDetailAndTask')}>
// <Button type="link" size="small" onClick={() => handleDeviceClick(record.raw || record)} icon={<LockOutlined />}>
// {t('common.locate')}
// </Button>
// </Tooltip>
// )
//}
{
title: t('common.detail'),
key: 'action',
width: 80,
render: (_, record) => {
const isMockDevice = record?.isMock || ['INVERTER', 'COMBINER_BOX', 'WEATHER_STATION', 'METER'].includes(record?.type);
return (
<Button
type="link"
size="small"
onClick={(e) => {
e.stopPropagation();
handleDeviceClick(record.raw || record);
}}
disabled={isMockDevice}
>
{t('common.detail')}
</Button>
);
}
},
];
// 任务池(当前选中设备)
@@ -785,6 +816,55 @@ const RealTimeMonitorPage = () => {
}
};
// 寻车:定位到当前选中的设备
const handleFindCar = useCallback(async () => {
if (!selectedDevice) {
messageApi.warning(t('devices.selectExecuteDevice'));
return;
}
const isDroneDevice = selectedDevice?.type === 'plane' || !!selectedDevice?.gateway_sn;
// 无人机:调用接口获取实时位置
if (isDroneDevice) {
if (selectedDevice?.gateway_sn && selectedDevice?.device_sn) {
try {
const res = await getUAVState({ sn: selectedDevice.gateway_sn, droneSn: selectedDevice.device_sn });
const pos = res?.data;
if (pos && pos.longitude && pos.latitude) {
mapRef.current?.flyToPosition?.({ lon: Number(pos.longitude), lat: Number(pos.latitude) }, { height: 300 });
return;
}
} catch (err) {
console.error('[RTMonitor] 寻车获取无人机位置失败', err);
}
}
}
// 机器人/其他设备:优先实时经纬度 -> lastRunningStatus -> locationMessage -> 静态经纬度
const rt = pickRealtimeRecord(realtimeMap, selectedDevice);
let lon = rt?.lng;
let lat = rt?.lat;
if ((!lon || !lat) && selectedDevice.lastRunningStatus?.longitude && selectedDevice.lastRunningStatus?.latitude) {
lon = selectedDevice.lastRunningStatus.longitude;
lat = selectedDevice.lastRunningStatus.latitude;
}
if ((!lon || !lat) && selectedDevice.locationMessage?.longitude && selectedDevice.locationMessage?.latitude) {
lon = selectedDevice.locationMessage.longitude;
lat = selectedDevice.locationMessage.latitude;
}
if ((!lon || !lat) && selectedDevice.longitude && selectedDevice.latitude) {
lon = selectedDevice.longitude;
lat = selectedDevice.latitude;
}
if (lon && lat && !isNaN(Number(lon)) && !isNaN(Number(lat))) {
mapRef.current?.flyToPosition?.({ lon: Number(lon), lat: Number(lat) }, { height: 300 });
} else {
messageApi.warning(t('devices.locationUnknown'));
}
}, [selectedDevice, t, realtimeMap]);
// ============================================================
// 路径操作:执行/暂停/恢复/取消
// ============================================================
@@ -949,6 +1029,9 @@ const RealTimeMonitorPage = () => {
<span style={{ width: 6, height: 6, borderRadius: '50%', background: '#888' }}></span>{t('devices.offline')}
</span>
<Divider type="vertical" />
<Button size="small" type="primary" icon={<EnvironmentOutlined />} onClick={handleFindCar}>
{t('devices.features.findCar')}
</Button>
<Button size="small" icon={<DeleteOutlined />} onClick={() => setClearNavLine(c => c + 1)}>
{t('devices.clearRealtimeTrack')}
</Button>
@@ -963,6 +1046,7 @@ const RealTimeMonitorPage = () => {
>
<div style={{ height: '100%', background: '#111827', borderRadius: 8, width: '100%', overflow: 'hidden', position: 'relative' }}>
<CesiumMap
ref={mapRef}
from="devicesTask"
mapLayer={currentStation?.siteMapName}
devices={mapDevices}
@@ -1044,6 +1128,10 @@ const RealTimeMonitorPage = () => {
loading={loading}
pagination={false}
size="small"
onRow={(record) => ({
onClick: () => handleLocateDevice(record.raw || record),
style: { cursor: 'pointer' },
})}
/>
<div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12, alignItems: 'center' }}>
<span style={{ color: '#999', fontSize: 11 }}>{t('common.totalCount', { count: filteredDeviceList.length })}</span>
@@ -1176,7 +1264,7 @@ const RealTimeMonitorPage = () => {
width={560}
open={deviceDrawerOpen}
onClose={() => {
; setDeviceDrawerOpen(false); setMqttDrone(null);
setDeviceDrawerOpen(false); setMqttDrone(null);
}}
destroyOnClose
extra={(selectedDevice?.gateway_sn || selectedDevice?.type === 'plane') ? null : <Button size="small" icon={<SyncOutlined />} onClick={() => { fetchTaskPoolList(selectedDeviceSn); }}></Button>}