feat: 3d控制指令
This commit is contained in:
@@ -14,6 +14,42 @@
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.terrainSection {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-bottom: 16px;
|
||||
padding: 12px 16px;
|
||||
background: #fff;
|
||||
border-radius: 6px;
|
||||
border: 1px solid #d9d9d9;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
|
||||
.terrainSwitch {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
|
||||
.label {
|
||||
color: #666;
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.savedHeights {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
|
||||
.label {
|
||||
color: #666;
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.modelHeightInfo {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
@@ -44,6 +80,12 @@
|
||||
color: #52c41a;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.tipText {
|
||||
font-size: 12px;
|
||||
color: #999;
|
||||
font-style: italic;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+248
-33
@@ -1,5 +1,5 @@
|
||||
import React, { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { Modal, Spin, Alert, Typography, Descriptions, Tag, Slider, InputNumber, Button, Space, message } from 'antd';
|
||||
import { Modal, Spin, Alert, Typography, Descriptions, Tag, Slider, InputNumber, Button, Space, message, Radio, Divider } from 'antd';
|
||||
import { ThreeDModelVO, updateModel } from '@/services/threeDModel';
|
||||
import styles from './ModelPreviewModal.less';
|
||||
|
||||
@@ -34,6 +34,8 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [modelHeight, setModelHeight] = useState<number | null>(null); // 模型原始高度
|
||||
const [suggestedOffset, setSuggestedOffset] = useState<number>(0); // 建议的偏移值
|
||||
const [currentTerrainType, setCurrentTerrainType] = useState<string>('cesium_ion'); // 当前使用的地形类型
|
||||
const [terrainSwitching, setTerrainSwitching] = useState(false); // 是否正在切换地形
|
||||
|
||||
// 清理函数
|
||||
const cleanup = useCallback(() => {
|
||||
@@ -104,12 +106,39 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
|
||||
|
||||
setSaving(true);
|
||||
try {
|
||||
await updateModel({
|
||||
// 根据当前地形类型,保存到对应的高度字段
|
||||
const updateData: any = {
|
||||
id: model.id,
|
||||
modelName: model.modelName,
|
||||
offsetHeight: heightOffset,
|
||||
});
|
||||
message.success(`高度偏移已保存: ${heightOffset}米`);
|
||||
offsetHeight: heightOffset, // 同时更新通用高度字段
|
||||
terrainType: currentTerrainType,
|
||||
// 保留原有的 LOD 精度配置,避免被默认值覆盖
|
||||
maxScreenSpaceError: model.style?.maximumScreenSpaceError || 1,
|
||||
maxMemoryUsage: model.style?.maximumMemoryUsage || 2048,
|
||||
skipLod: model.style?.skipLevelOfDetail ? 1 : 0,
|
||||
preferLeaves: model.style?.preferLeaves ? 1 : 0,
|
||||
};
|
||||
|
||||
// 根据当前地形类型保存到对应字段
|
||||
if (currentTerrainType === 'cesium_ion') {
|
||||
updateData.cesiumHeight = heightOffset;
|
||||
// 保留已有的 ArcGIS 高度
|
||||
if (model.position?.arcgisHeight !== undefined) {
|
||||
updateData.arcgisHeight = model.position.arcgisHeight;
|
||||
}
|
||||
} else if (currentTerrainType === 'arcgis') {
|
||||
updateData.arcgisHeight = heightOffset;
|
||||
// 保留已有的 Cesium 高度
|
||||
if (model.position?.cesiumHeight !== undefined) {
|
||||
updateData.cesiumHeight = model.position.cesiumHeight;
|
||||
}
|
||||
}
|
||||
|
||||
await updateModel(updateData);
|
||||
|
||||
const terrainName = currentTerrainType === 'cesium_ion' ? 'Cesium Ion' :
|
||||
currentTerrainType === 'arcgis' ? 'ArcGIS' : '椭球';
|
||||
message.success(`高度偏移已保存: ${heightOffset}米 (${terrainName}地形)`);
|
||||
onHeightUpdated?.();
|
||||
} catch (err: any) {
|
||||
message.error('保存失败: ' + (err.message || '未知错误'));
|
||||
@@ -118,6 +147,63 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 切换地形类型
|
||||
* 重新加载指定类型的地形,并应用对应的高度偏移值
|
||||
*/
|
||||
const switchTerrain = useCallback(async (terrainType: string) => {
|
||||
if (!viewerRef.current || !Cesium || terrainSwitching) return;
|
||||
if (terrainType === currentTerrainType) return;
|
||||
|
||||
setTerrainSwitching(true);
|
||||
console.log('切换地形到:', terrainType);
|
||||
|
||||
try {
|
||||
let terrainProvider;
|
||||
|
||||
if (terrainType === 'cesium_ion') {
|
||||
terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
|
||||
requestVertexNormals: true,
|
||||
requestWaterMask: false,
|
||||
});
|
||||
console.log('地形切换成功: Cesium Ion');
|
||||
} else if (terrainType === 'arcgis') {
|
||||
terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
|
||||
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
|
||||
);
|
||||
console.log('地形切换成功: ArcGIS');
|
||||
} else {
|
||||
terrainProvider = new Cesium.EllipsoidTerrainProvider();
|
||||
console.log('地形切换成功: 椭球(无高程)');
|
||||
}
|
||||
|
||||
// 切换地形
|
||||
viewerRef.current.terrainProvider = terrainProvider;
|
||||
setCurrentTerrainType(terrainType);
|
||||
|
||||
// 切换到对应地形的高度偏移值
|
||||
let newHeight = model?.position?.height || 0;
|
||||
if (terrainType === 'cesium_ion' && model?.position?.cesiumHeight !== undefined && model?.position?.cesiumHeight !== null) {
|
||||
newHeight = model.position.cesiumHeight;
|
||||
} else if (terrainType === 'arcgis' && model?.position?.arcgisHeight !== undefined && model?.position?.arcgisHeight !== null) {
|
||||
newHeight = model.position.arcgisHeight;
|
||||
}
|
||||
setHeightOffset(newHeight);
|
||||
|
||||
// 应用新的高度偏移
|
||||
if (tilesetRef.current && originalCenterRef.current) {
|
||||
adjustHeight(newHeight);
|
||||
}
|
||||
|
||||
message.success(`已切换到 ${terrainType === 'cesium_ion' ? 'Cesium Ion' : terrainType === 'arcgis' ? 'ArcGIS' : '椭球'} 地形`);
|
||||
} catch (err: any) {
|
||||
console.error('切换地形失败:', err);
|
||||
message.error(`切换地形失败: ${err.message || '未知错误'}`);
|
||||
} finally {
|
||||
setTerrainSwitching(false);
|
||||
}
|
||||
}, [currentTerrainType, terrainSwitching, model, adjustHeight]);
|
||||
|
||||
// 初始化Viewer和加载模型
|
||||
const initViewer = useCallback(async () => {
|
||||
if (!model?.tilesetUrl || !containerRef.current) return;
|
||||
@@ -128,10 +214,6 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
// 初始化高度偏移为模型当前配置的值
|
||||
const initialHeight = model.position?.height || 0;
|
||||
setHeightOffset(initialHeight);
|
||||
|
||||
try {
|
||||
// 动态加载Cesium
|
||||
if (!Cesium) {
|
||||
@@ -139,15 +221,98 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
|
||||
Cesium = cesiumModule;
|
||||
const cesiumBaseUrl = process.env.CESIUM_BASE_URL || '/';
|
||||
Cesium.buildModuleUrl.setBaseUrl(`${cesiumBaseUrl}cesium/`);
|
||||
|
||||
// 设置 Cesium Ion Access Token(用于加载 Cesium World Terrain)
|
||||
const cesiumToken = process.env.REACT_APP_CESIUM_TOKEN;
|
||||
if (cesiumToken) {
|
||||
Cesium.Ion.defaultAccessToken = cesiumToken;
|
||||
}
|
||||
}
|
||||
|
||||
if (!containerRef.current) {
|
||||
throw new Error('容器未就绪');
|
||||
}
|
||||
|
||||
// 使用高程地形,让3D模型与地形配合显示
|
||||
// 如果模型已有记录的地形类型,优先使用该类型;否则按优先级尝试加载
|
||||
const savedTerrainType = model.position?.terrainType;
|
||||
let terrainProvider;
|
||||
let loadedTerrainType = 'ellipsoid';
|
||||
|
||||
// 根据保存的地形类型或默认优先级加载地形
|
||||
if (savedTerrainType === 'arcgis') {
|
||||
// 优先尝试 ArcGIS(如果之前用 ArcGIS 标定的)
|
||||
try {
|
||||
terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
|
||||
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
|
||||
);
|
||||
loadedTerrainType = 'arcgis';
|
||||
console.log('ModelPreview: 高程地形加载成功 (ArcGIS World Elevation - 根据保存的地形类型)');
|
||||
} catch (arcgisError) {
|
||||
console.warn('ModelPreview: ArcGIS 加载失败,尝试 Cesium Ion:', arcgisError);
|
||||
try {
|
||||
terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
|
||||
requestVertexNormals: true,
|
||||
requestWaterMask: false,
|
||||
});
|
||||
loadedTerrainType = 'cesium_ion';
|
||||
console.log('ModelPreview: 高程地形加载成功 (Cesium World Terrain - 备用)');
|
||||
message.warning('ArcGIS地形加载失败,已切换到Cesium Ion,高度可能需要重新调整');
|
||||
} catch (cesiumError) {
|
||||
console.warn('ModelPreview: Cesium Ion 也加载失败,使用椭球地形:', cesiumError);
|
||||
terrainProvider = new Cesium.EllipsoidTerrainProvider();
|
||||
loadedTerrainType = 'ellipsoid';
|
||||
message.warning('地形加载失败,使用椭球地形,高度需要重新调整');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 默认优先使用 Cesium Ion
|
||||
try {
|
||||
terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
|
||||
requestVertexNormals: true,
|
||||
requestWaterMask: false,
|
||||
});
|
||||
loadedTerrainType = 'cesium_ion';
|
||||
console.log('ModelPreview: 高程地形加载成功 (Cesium World Terrain)');
|
||||
} catch (cesiumError) {
|
||||
console.warn('ModelPreview: Cesium World Terrain 加载失败,尝试 ArcGIS:', cesiumError);
|
||||
try {
|
||||
terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
|
||||
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
|
||||
);
|
||||
loadedTerrainType = 'arcgis';
|
||||
console.log('ModelPreview: 高程地形加载成功 (ArcGIS World Elevation)');
|
||||
if (savedTerrainType === 'cesium_ion') {
|
||||
message.warning('Cesium Ion地形加载失败,已切换到ArcGIS,高度可能需要重新调整');
|
||||
}
|
||||
} catch (arcgisError) {
|
||||
console.warn('ModelPreview: ArcGIS 也加载失败,使用椭球地形:', arcgisError);
|
||||
terrainProvider = new Cesium.EllipsoidTerrainProvider();
|
||||
loadedTerrainType = 'ellipsoid';
|
||||
message.warning('地形加载失败,使用椭球地形,高度需要重新调整');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 记录当前加载的地形类型
|
||||
setCurrentTerrainType(loadedTerrainType);
|
||||
|
||||
// 根据实际加载的地形类型,选择对应的高度偏移值
|
||||
let initialHeight = model.position?.height || 0; // 默认使用通用高度
|
||||
if (loadedTerrainType === 'cesium_ion' && model.position?.cesiumHeight !== undefined && model.position?.cesiumHeight !== null) {
|
||||
initialHeight = model.position.cesiumHeight;
|
||||
console.log('使用 Cesium Ion 高度偏移:', initialHeight);
|
||||
} else if (loadedTerrainType === 'arcgis' && model.position?.arcgisHeight !== undefined && model.position?.arcgisHeight !== null) {
|
||||
initialHeight = model.position.arcgisHeight;
|
||||
console.log('使用 ArcGIS 高度偏移:', initialHeight);
|
||||
} else {
|
||||
console.log('使用通用高度偏移:', initialHeight);
|
||||
}
|
||||
setHeightOffset(initialHeight);
|
||||
|
||||
// 创建Viewer
|
||||
const viewer = new Cesium.Viewer(containerRef.current, {
|
||||
terrainProvider: new Cesium.EllipsoidTerrainProvider(),
|
||||
terrainProvider: terrainProvider,
|
||||
scene3DOnly: true,
|
||||
animation: false,
|
||||
timeline: false,
|
||||
@@ -169,7 +334,10 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
|
||||
creditContainer.style.display = 'none';
|
||||
}
|
||||
|
||||
// 添加影像图层
|
||||
// 启用地形深度测试,确保模型与地形正确交互
|
||||
viewer.scene.globe.depthTestAgainstTerrain = true;
|
||||
|
||||
// 添加 ArcGIS 高清卫星影像底图
|
||||
const arcgisImagery = new Cesium.UrlTemplateImageryProvider({
|
||||
url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
|
||||
minimumLevel: 0,
|
||||
@@ -194,17 +362,17 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
|
||||
// 保存原始中心点(用于高度调整计算)
|
||||
originalCenterRef.current = Cesium.Cartesian3.clone(tileset.boundingSphere.center);
|
||||
|
||||
// 计算模型的WGS84高度,并给出建议的偏移值
|
||||
// 计算模型的WGS84高度(海拔)
|
||||
const cartographic = Cesium.Cartographic.fromCartesian(tileset.boundingSphere.center);
|
||||
const heightInMeters = cartographic.height;
|
||||
setModelHeight(Math.round(heightInMeters));
|
||||
|
||||
// 建议的偏移值:取负值让模型下降到地面
|
||||
// 保留一点高度(约50米)避免模型陷入地面
|
||||
const suggested = -Math.round(heightInMeters) + 50;
|
||||
setSuggestedOffset(suggested);
|
||||
// 使用高程地形后,模型与地形的位置已经比较接近
|
||||
// 由于 Cesium World Terrain 精度约30m,与大疆模型可能存在一定偏差
|
||||
// 建议偏移值默认为 0,用户根据实际显示效果微调
|
||||
setSuggestedOffset(0);
|
||||
|
||||
console.log(`模型高度: ${heightInMeters.toFixed(2)}米, 建议偏移: ${suggested}米`);
|
||||
console.log(`模型海拔高度: ${heightInMeters.toFixed(2)}米,使用高程地形,建议微调偏移`);
|
||||
|
||||
// 如果有初始高度偏移,立即应用
|
||||
if (initialHeight !== 0) {
|
||||
@@ -302,26 +470,67 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
|
||||
{initialized && (
|
||||
<div className={styles.heightControl}>
|
||||
<div className={styles.heightControlTitle}>
|
||||
<span>🎚️ 高度调整(模型在空中飘着?向下调整;模型陷入地面?向上调整)</span>
|
||||
<span>高度偏移调整(微调模型高度以匹配地形,正值上移、负值下移)</span>
|
||||
</div>
|
||||
|
||||
{/* 地形切换和已保存高度信息 */}
|
||||
<div className={styles.terrainSection}>
|
||||
<div className={styles.terrainSwitch}>
|
||||
<span className={styles.label}>选择地形:</span>
|
||||
<Radio.Group
|
||||
value={currentTerrainType}
|
||||
onChange={(e) => switchTerrain(e.target.value)}
|
||||
disabled={terrainSwitching}
|
||||
optionType="button"
|
||||
buttonStyle="solid"
|
||||
size="small"
|
||||
>
|
||||
<Radio.Button value="cesium_ion">Cesium Ion</Radio.Button>
|
||||
<Radio.Button value="arcgis">ArcGIS</Radio.Button>
|
||||
</Radio.Group>
|
||||
{terrainSwitching && <Spin size="small" style={{ marginLeft: 8 }} />}
|
||||
</div>
|
||||
|
||||
<Divider type="vertical" style={{ height: 'auto', margin: '0 16px' }} />
|
||||
|
||||
<div className={styles.savedHeights}>
|
||||
<span className={styles.label}>已保存高度:</span>
|
||||
<Space size="middle">
|
||||
<span>
|
||||
<Tag color={currentTerrainType === 'cesium_ion' ? 'blue' : 'default'}>Cesium Ion</Tag>
|
||||
<span style={{ fontWeight: currentTerrainType === 'cesium_ion' ? 'bold' : 'normal' }}>
|
||||
{model?.position?.cesiumHeight !== undefined && model?.position?.cesiumHeight !== null
|
||||
? `${model.position.cesiumHeight}米`
|
||||
: '未设置'}
|
||||
</span>
|
||||
</span>
|
||||
<span>
|
||||
<Tag color={currentTerrainType === 'arcgis' ? 'green' : 'default'}>ArcGIS</Tag>
|
||||
<span style={{ fontWeight: currentTerrainType === 'arcgis' ? 'bold' : 'normal' }}>
|
||||
{model?.position?.arcgisHeight !== undefined && model?.position?.arcgisHeight !== null
|
||||
? `${model.position.arcgisHeight}米`
|
||||
: '未设置'}
|
||||
</span>
|
||||
</span>
|
||||
</Space>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 模型高度信息 */}
|
||||
{modelHeight !== null && (
|
||||
<div className={styles.modelHeightInfo}>
|
||||
<div className={styles.heightInfoItem}>
|
||||
<span className={styles.label}>模型原始高度:</span>
|
||||
<span className={styles.label}>模型海拔高度:</span>
|
||||
<span className={styles.value}>{modelHeight} 米</span>
|
||||
</div>
|
||||
<div className={styles.heightInfoItem}>
|
||||
<span className={styles.label}>建议偏移值:</span>
|
||||
<span className={styles.suggestedValue}>{suggestedOffset} 米</span>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
onClick={() => setHeightOffset(suggestedOffset)}
|
||||
>
|
||||
应用建议值
|
||||
</Button>
|
||||
<span className={styles.label}>当前偏移:</span>
|
||||
<span className={styles.suggestedValue}>{heightOffset} 米</span>
|
||||
</div>
|
||||
<div className={styles.heightInfoItem}>
|
||||
<span className={styles.tipText}>
|
||||
提示: 分别切换到两种地形调整并保存高度,这样两种地形服务都能正确显示模型
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -361,11 +570,17 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
|
||||
<Button size="small" onClick={() => setHeightOffset(0)}>
|
||||
重置为0
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() => setHeightOffset(suggestedOffset)}
|
||||
>
|
||||
应用建议值
|
||||
<Button size="small" onClick={() => setHeightOffset(heightOffset + 10)}>
|
||||
+10米
|
||||
</Button>
|
||||
<Button size="small" onClick={() => setHeightOffset(heightOffset - 10)}>
|
||||
-10米
|
||||
</Button>
|
||||
<Button size="small" onClick={() => setHeightOffset(heightOffset + 30)}>
|
||||
+30米
|
||||
</Button>
|
||||
<Button size="small" onClick={() => setHeightOffset(heightOffset - 30)}>
|
||||
-30米
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
|
||||
@@ -415,21 +415,79 @@ const TourismDeviceDetail: React.FC<TourismDeviceDetailProps> = (props) => {
|
||||
setSelectedDeviceSn(device.deviceSn || '');
|
||||
};
|
||||
|
||||
// 处理一键起飞
|
||||
// 一键起飞弹窗状态
|
||||
const [takeoffModalVisible, setTakeoffModalVisible] = useState(false);
|
||||
const [takeoffLoading, setTakeoffLoading] = useState(false);
|
||||
const [takeoffForm] = useState({
|
||||
targetLatitude: 0,
|
||||
targetLongitude: 0,
|
||||
targetHeight: 100,
|
||||
securityTakeoffHeight: 50,
|
||||
rthAltitude: 50,
|
||||
maxSpeed: 5,
|
||||
});
|
||||
|
||||
// 处理一键起飞 - 打开确认弹窗
|
||||
const handleTakeoff = () => {
|
||||
// 再次确认机库状态
|
||||
// 检查机库状态
|
||||
if (realtimeData?.rawData?.dockData?.mode_code === 1) {
|
||||
message.warning('机库正在执行任务,无法起飞');
|
||||
return;
|
||||
}
|
||||
|
||||
if (realtimeData?.rawData?.dockData?.drone_in_dock !== 1) {
|
||||
// 只有明确知道无人机不在库时才阻止(值为0时)
|
||||
if (realtimeData?.rawData?.dockData?.drone_in_dock === 0) {
|
||||
message.warning('无人机不在库,无法起飞');
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: 调用后端API执行一键起飞(会自动开机)
|
||||
message.info('一键起飞功能开发中');
|
||||
// 使用机库当前位置作为默认目标点
|
||||
const dockLatitude = realtimeData?.rawData?.dockData?.latitude || realtimeData?.gps?.latitude || 0;
|
||||
const dockLongitude = realtimeData?.rawData?.dockData?.longitude || realtimeData?.gps?.longitude || 0;
|
||||
const dockHeight = realtimeData?.rawData?.dockData?.height || realtimeData?.gps?.altitude || 0;
|
||||
|
||||
takeoffForm.targetLatitude = dockLatitude;
|
||||
takeoffForm.targetLongitude = dockLongitude;
|
||||
takeoffForm.targetHeight = dockHeight + 30; // 机库高度 + 30米
|
||||
|
||||
setTakeoffModalVisible(true);
|
||||
};
|
||||
|
||||
// 执行一键起飞(弹窗确认后调用)
|
||||
const doTakeoff = async () => {
|
||||
if (!selectedDeviceSn) {
|
||||
message.error('未选择设备');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!takeoffForm.targetLatitude || !takeoffForm.targetLongitude) {
|
||||
message.error('无法获取机库位置信息');
|
||||
return;
|
||||
}
|
||||
|
||||
setTakeoffLoading(true);
|
||||
try {
|
||||
const res = await deviceApi.takeoff({
|
||||
deviceSn: selectedDeviceSn,
|
||||
targetLatitude: takeoffForm.targetLatitude,
|
||||
targetLongitude: takeoffForm.targetLongitude,
|
||||
targetHeight: takeoffForm.targetHeight,
|
||||
securityTakeoffHeight: takeoffForm.securityTakeoffHeight,
|
||||
rthAltitude: takeoffForm.rthAltitude,
|
||||
maxSpeed: takeoffForm.maxSpeed,
|
||||
});
|
||||
|
||||
if (res.code === 0) {
|
||||
message.success('起飞命令已发送,无人机将自动开机并起飞');
|
||||
setTakeoffModalVisible(false);
|
||||
} else {
|
||||
message.error(res.msg || '起飞命令发送失败');
|
||||
}
|
||||
} catch (error: any) {
|
||||
message.error(error.message || '起飞命令发送失败');
|
||||
} finally {
|
||||
setTakeoffLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 初始加载
|
||||
@@ -718,8 +776,13 @@ const TourismDeviceDetail: React.FC<TourismDeviceDetailProps> = (props) => {
|
||||
disabled={
|
||||
// 机库正在工作中
|
||||
realtimeData?.rawData?.dockData?.mode_code === 1 ||
|
||||
// 无人机不在库
|
||||
realtimeData?.rawData?.dockData?.drone_in_dock !== 1
|
||||
// 无人机不在库(明确为0时禁用,undefined或1时允许)
|
||||
realtimeData?.rawData?.dockData?.drone_in_dock === 0
|
||||
}
|
||||
title={
|
||||
realtimeData?.rawData?.dockData?.sub_device?.device_online_status !== 1
|
||||
? '无人机未开机,点击后将自动开机并起飞'
|
||||
: '一键起飞'
|
||||
}
|
||||
>
|
||||
一键起飞
|
||||
@@ -1253,6 +1316,95 @@ const TourismDeviceDetail: React.FC<TourismDeviceDetailProps> = (props) => {
|
||||
</Col>
|
||||
</Row>
|
||||
</Modal>
|
||||
|
||||
{/* 一键起飞弹窗 */}
|
||||
<Modal
|
||||
title={
|
||||
<span style={{ color: '#1890ff' }}>
|
||||
<RocketOutlined style={{ marginRight: 8 }} />
|
||||
一键起飞设置
|
||||
{realtimeData?.rawData?.dockData?.sub_device?.device_online_status !== 1 && (
|
||||
<Tag color="orange" style={{ marginLeft: 8 }}>无人机将自动开机</Tag>
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
open={takeoffModalVisible}
|
||||
onCancel={() => setTakeoffModalVisible(false)}
|
||||
onOk={doTakeoff}
|
||||
confirmLoading={takeoffLoading}
|
||||
okText="确认起飞"
|
||||
cancelText="取消"
|
||||
width={500}
|
||||
>
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<Row gutter={[16, 16]}>
|
||||
<Col span={12}>
|
||||
<div style={{ marginBottom: 8 }}>目标纬度</div>
|
||||
<input
|
||||
type="number"
|
||||
value={takeoffForm.targetLatitude}
|
||||
onChange={(e) => takeoffForm.targetLatitude = parseFloat(e.target.value) || 0}
|
||||
style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: 4 }}
|
||||
step="0.000001"
|
||||
/>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<div style={{ marginBottom: 8 }}>目标经度</div>
|
||||
<input
|
||||
type="number"
|
||||
value={takeoffForm.targetLongitude}
|
||||
onChange={(e) => takeoffForm.targetLongitude = parseFloat(e.target.value) || 0}
|
||||
style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: 4 }}
|
||||
step="0.000001"
|
||||
/>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<div style={{ marginBottom: 8 }}>目标高度 (m)</div>
|
||||
<input
|
||||
type="number"
|
||||
value={takeoffForm.targetHeight}
|
||||
onChange={(e) => takeoffForm.targetHeight = parseInt(e.target.value) || 100}
|
||||
style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: 4 }}
|
||||
min={2}
|
||||
max={1500}
|
||||
/>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<div style={{ marginBottom: 8 }}>安全起飞高度 (m)</div>
|
||||
<input
|
||||
type="number"
|
||||
value={takeoffForm.securityTakeoffHeight}
|
||||
onChange={(e) => takeoffForm.securityTakeoffHeight = parseInt(e.target.value) || 50}
|
||||
style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: 4 }}
|
||||
min={20}
|
||||
max={1500}
|
||||
/>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<div style={{ marginBottom: 8 }}>返航高度 (m)</div>
|
||||
<input
|
||||
type="number"
|
||||
value={takeoffForm.rthAltitude}
|
||||
onChange={(e) => takeoffForm.rthAltitude = parseInt(e.target.value) || 50}
|
||||
style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: 4 }}
|
||||
min={2}
|
||||
max={1500}
|
||||
/>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<div style={{ marginBottom: 8 }}>最大飞行速度 (m/s)</div>
|
||||
<input
|
||||
type="number"
|
||||
value={takeoffForm.maxSpeed}
|
||||
onChange={(e) => takeoffForm.maxSpeed = parseInt(e.target.value) || 5}
|
||||
style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: 4 }}
|
||||
min={1}
|
||||
max={15}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
</div>
|
||||
</Modal>
|
||||
</PageContainer>
|
||||
);
|
||||
};
|
||||
|
||||
+635
-78
@@ -1,7 +1,6 @@
|
||||
import React from 'react';
|
||||
import React, { useMemo, useState, useCallback, useEffect, useRef } from 'react';
|
||||
import {
|
||||
CloseOutlined,
|
||||
RocketOutlined,
|
||||
VideoCameraOutlined,
|
||||
ArrowUpOutlined,
|
||||
ArrowDownOutlined,
|
||||
@@ -14,10 +13,20 @@ import {
|
||||
RotateRightOutlined,
|
||||
VerticalAlignTopOutlined,
|
||||
VerticalAlignBottomOutlined,
|
||||
DashboardOutlined,
|
||||
CompassOutlined
|
||||
CompassOutlined,
|
||||
WifiOutlined,
|
||||
LoadingOutlined,
|
||||
PlayCircleOutlined,
|
||||
PauseCircleOutlined,
|
||||
LinkOutlined,
|
||||
DisconnectOutlined,
|
||||
CaretRightOutlined,
|
||||
SwapOutlined,
|
||||
AimOutlined
|
||||
} from '@ant-design/icons';
|
||||
import { message } from 'antd';
|
||||
import { message, Tooltip, Modal, Switch, Tag } from 'antd';
|
||||
import { deviceApi } from '@/services/device';
|
||||
import { deviceControlWs } from '@/services/deviceControlWs';
|
||||
import styles from './LeftControlPanel.less';
|
||||
|
||||
interface LeftControlPanelProps {
|
||||
@@ -27,6 +36,18 @@ interface LeftControlPanelProps {
|
||||
realtimeData: any;
|
||||
}
|
||||
|
||||
// 飞行模式映射
|
||||
const FLIGHT_MODE_MAP: Record<number, string> = {
|
||||
0: '待机',
|
||||
1: '起飞',
|
||||
2: '降落',
|
||||
3: '悬停',
|
||||
4: '航点飞行',
|
||||
5: '返航',
|
||||
6: '手动控制',
|
||||
7: '紧急制动',
|
||||
};
|
||||
|
||||
const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
visible,
|
||||
onClose,
|
||||
@@ -34,26 +55,471 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
realtimeData
|
||||
}) => {
|
||||
const dockData = realtimeData?.rawData?.dockData;
|
||||
|
||||
// 模拟详细飞行数据 (Placeholder Data)
|
||||
const flightData = {
|
||||
pitch: -2.5,
|
||||
roll: 0.1,
|
||||
yaw: 125.4,
|
||||
hSpeed: 0.0,
|
||||
vSpeed: 0.0,
|
||||
altitude: realtimeData?.gps?.altitude?.toFixed(1) || '0.0',
|
||||
distance: 12.5, // 离家距离
|
||||
homeAlt: 0,
|
||||
satellites: dockData?.position_state?.gps_number || 12,
|
||||
rtkStatus: 'FIX',
|
||||
signal: 95,
|
||||
rcSignal: 100
|
||||
};
|
||||
const droneData = realtimeData?.rawData?.droneData;
|
||||
|
||||
const handleControl = (action: string) => {
|
||||
message.info(`发送指令: ${action}`);
|
||||
};
|
||||
// 从 droneData (msg_alarm) 获取无人机实时飞行数据
|
||||
// droneData 结构: 根级别有 latitude, longitude, height, attitude_pitch 等
|
||||
// 云台数据在 payload 索引下,如 droneData["98-0-0"]
|
||||
const flightData = useMemo(() => {
|
||||
// 调试日志 - 查看 droneData 的实际结构
|
||||
if (droneData) {
|
||||
console.log('[FlightData] droneData keys:', Object.keys(droneData));
|
||||
console.log('[FlightData] droneData.latitude:', droneData?.latitude);
|
||||
console.log('[FlightData] droneData.longitude:', droneData?.longitude);
|
||||
}
|
||||
|
||||
// 获取云台payload数据 - 遍历查找带有 gimbal_pitch 的子对象
|
||||
let gimbalPayload: any = {};
|
||||
if (droneData) {
|
||||
// 常见的 payload 索引
|
||||
const payloadKeys = ['98-0-0', '39-0-0', '42-0-0', '43-0-0', '52-0-0', '53-0-0', '165-0-0'];
|
||||
for (const key of payloadKeys) {
|
||||
if (droneData[key] && (droneData[key].gimbal_pitch !== undefined || droneData[key].gimbal_yaw !== undefined)) {
|
||||
gimbalPayload = droneData[key];
|
||||
console.log('[FlightData] 找到云台数据在 key:', key, gimbalPayload);
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 如果常见索引没找到,遍历所有数字格式的key
|
||||
if (!gimbalPayload.gimbal_pitch && !gimbalPayload.gimbal_yaw) {
|
||||
for (const key of Object.keys(droneData)) {
|
||||
if (/^\d+-\d+-\d+$/.test(key) && droneData[key]?.gimbal_pitch !== undefined) {
|
||||
gimbalPayload = droneData[key];
|
||||
console.log('[FlightData] 遍历找到云台数据在 key:', key);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const pitch = droneData?.attitude_pitch ?? 0;
|
||||
const roll = droneData?.attitude_roll ?? 0;
|
||||
const yaw = droneData?.attitude_head ?? 0;
|
||||
const hSpeed = droneData?.horizontal_speed ?? droneData?.ground_speed ?? 0;
|
||||
const vSpeed = droneData?.vertical_speed ?? 0;
|
||||
const altitude = droneData?.height ?? droneData?.elevation ?? realtimeData?.gps?.altitude ?? 0;
|
||||
const distance = droneData?.home_distance ?? 0;
|
||||
|
||||
// GPS/RTK卫星数据
|
||||
const satellites = droneData?.position_state?.gps_number ?? dockData?.position_state?.gps_number ?? 0;
|
||||
const rtkSatellites = droneData?.position_state?.rtk_number ?? dockData?.position_state?.rtk_number ?? 0;
|
||||
const isFixed = droneData?.position_state?.is_fixed ?? dockData?.position_state?.is_fixed ?? 0;
|
||||
const rtkStatus = isFixed === 2 ? 'FIX' : (isFixed === 1 ? 'FLOAT' : (rtkSatellites > 0 ? 'FLOAT' : 'NONE'));
|
||||
|
||||
// 电池数据
|
||||
const batteryPercent = droneData?.battery?.capacity_percent ?? realtimeData?.battery ?? 0;
|
||||
const batteryVoltage = droneData?.battery?.voltage ?? 0;
|
||||
const batteryTemp = droneData?.battery?.temperature ?? 0;
|
||||
const remainFlightTime = droneData?.battery?.remain_flight_time ?? 0;
|
||||
|
||||
// 信号强度
|
||||
const signal = dockData?.wireless_link?.dongle_number ?? dockData?.sdr?.upward_quality ?? 0;
|
||||
|
||||
// 飞行模式
|
||||
const modeCode = droneData?.mode_code ?? 0;
|
||||
const flightMode = FLIGHT_MODE_MAP[modeCode] || `模式${modeCode}`;
|
||||
|
||||
// 云台角度 - 优先从 payload 中获取,否则从根级别获取
|
||||
const gimbalPitch = gimbalPayload?.gimbal_pitch ?? droneData?.gimbal_pitch ?? 0;
|
||||
const gimbalYaw = gimbalPayload?.gimbal_yaw ?? droneData?.gimbal_yaw ?? 0;
|
||||
const windSpeed = droneData?.wind_speed ?? 0;
|
||||
|
||||
// 无人机实时经纬度 - 直接从 droneData 根级别获取
|
||||
const droneLat = droneData?.latitude ?? 0;
|
||||
const droneLng = droneData?.longitude ?? 0;
|
||||
|
||||
return {
|
||||
pitch: Number(pitch).toFixed(1),
|
||||
roll: Number(roll).toFixed(1),
|
||||
yaw: Number(yaw).toFixed(1),
|
||||
hSpeed: Number(hSpeed).toFixed(1),
|
||||
vSpeed: Number(vSpeed).toFixed(1),
|
||||
altitude: Number(altitude).toFixed(1),
|
||||
distance: Number(distance).toFixed(1),
|
||||
satellites,
|
||||
rtkSatellites,
|
||||
rtkStatus,
|
||||
signal,
|
||||
batteryPercent,
|
||||
batteryVoltage: (batteryVoltage / 1000).toFixed(2),
|
||||
batteryTemp,
|
||||
remainFlightTime: Math.floor(remainFlightTime / 60),
|
||||
flightMode,
|
||||
modeCode,
|
||||
gimbalPitch: Number(gimbalPitch).toFixed(1),
|
||||
gimbalYaw: Number(gimbalYaw).toFixed(1),
|
||||
windSpeed: Number(windSpeed).toFixed(1),
|
||||
// 无人机实时位置
|
||||
latitude: Number(droneLat).toFixed(6),
|
||||
longitude: Number(droneLng).toFixed(6),
|
||||
};
|
||||
}, [droneData, dockData, realtimeData]);
|
||||
|
||||
// 指令发送状态
|
||||
const [loading, setLoading] = useState<string | null>(null);
|
||||
const [isRecording, setIsRecording] = useState(false);
|
||||
const [cameraMode, setCameraMode] = useState<'photo' | 'video'>('photo'); // 相机模式
|
||||
|
||||
// WebSocket连接状态
|
||||
const [wsConnected, setWsConnected] = useState(false);
|
||||
|
||||
// DRC模式状态 - 只需进入一次即可持续控制
|
||||
const [drcMode, setDrcMode] = useState(false);
|
||||
const drcModeRef = useRef(false); // 用于在回调中访问最新状态
|
||||
|
||||
// 获取设备SN
|
||||
const deviceSn = device?.deviceSn;
|
||||
|
||||
// WebSocket连接管理 + 无人机遥测数据订阅
|
||||
useEffect(() => {
|
||||
if (visible && deviceSn) {
|
||||
// 1. 连接实时控制WebSocket
|
||||
deviceControlWs.connect(deviceSn);
|
||||
|
||||
// 2. 订阅无人机遥测数据(msg_alarm)
|
||||
// 只有进入操控台时才订阅,因为大部分时间无人机不在线
|
||||
console.log('[LeftControlPanel] 订阅无人机遥测数据:', deviceSn);
|
||||
deviceApi.subscribeDroneTelemetry(deviceSn).then((res) => {
|
||||
if (res.success) {
|
||||
console.log('[LeftControlPanel] 无人机遥测数据订阅成功');
|
||||
} else {
|
||||
console.warn('[LeftControlPanel] 无人机遥测数据订阅失败:', res.message);
|
||||
}
|
||||
});
|
||||
|
||||
const unsubscribe = deviceControlWs.onStatusChange((connected) => {
|
||||
setWsConnected(connected);
|
||||
if (connected) {
|
||||
console.log('[LeftControlPanel] 实时控制WebSocket已连接');
|
||||
} else {
|
||||
console.log('[LeftControlPanel] 实时控制WebSocket已断开');
|
||||
// 断开时重置DRC模式状态
|
||||
setDrcMode(false);
|
||||
drcModeRef.current = false;
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubscribe();
|
||||
deviceControlWs.disconnect();
|
||||
// 清理DRC模式状态
|
||||
setDrcMode(false);
|
||||
drcModeRef.current = false;
|
||||
|
||||
// 3. 取消订阅无人机遥测数据
|
||||
console.log('[LeftControlPanel] 取消订阅无人机遥测数据:', deviceSn);
|
||||
deviceApi.unsubscribeDroneTelemetry(deviceSn).then((res) => {
|
||||
if (res.success) {
|
||||
console.log('[LeftControlPanel] 无人机遥测数据已取消订阅');
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
}, [visible, deviceSn]);
|
||||
|
||||
// 进入DRC模式(只需调用一次)
|
||||
const enterDrcMode = useCallback(async () => {
|
||||
if (!deviceSn) {
|
||||
message.error('未选择设备');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (drcModeRef.current) {
|
||||
return true; // 已经在DRC模式中
|
||||
}
|
||||
|
||||
setLoading('drc');
|
||||
try {
|
||||
const res = await deviceApi.enterDrcMode(deviceSn);
|
||||
if (res.code === 0) {
|
||||
setDrcMode(true);
|
||||
drcModeRef.current = true;
|
||||
message.success('已进入指令飞行模式');
|
||||
return true;
|
||||
} else {
|
||||
message.error(res.msg || '进入指令飞行模式失败');
|
||||
return false;
|
||||
}
|
||||
} catch (error: any) {
|
||||
message.error(error.message || '进入指令飞行模式失败');
|
||||
return false;
|
||||
} finally {
|
||||
setLoading(null);
|
||||
}
|
||||
}, [deviceSn]);
|
||||
|
||||
// 一键返航
|
||||
const handleReturnHome = useCallback(async () => {
|
||||
if (!deviceSn) {
|
||||
message.error('未选择设备');
|
||||
return;
|
||||
}
|
||||
|
||||
Modal.confirm({
|
||||
title: '确认返航',
|
||||
content: '确定要让无人机执行一键返航吗?',
|
||||
onOk: async () => {
|
||||
setLoading('return');
|
||||
try {
|
||||
const res = await deviceApi.returnHome(deviceSn);
|
||||
if (res.code === 0) {
|
||||
message.success('返航命令已发送');
|
||||
} else {
|
||||
message.error(res.msg || '返航命令发送失败');
|
||||
}
|
||||
} catch (error: any) {
|
||||
message.error(error.message || '返航命令发送失败');
|
||||
} finally {
|
||||
setLoading(null);
|
||||
}
|
||||
},
|
||||
});
|
||||
}, [deviceSn]);
|
||||
|
||||
// 取消返航
|
||||
const handleCancelReturn = useCallback(async () => {
|
||||
if (!deviceSn) {
|
||||
message.error('未选择设备');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading('cancelReturn');
|
||||
try {
|
||||
const res = await deviceApi.cancelReturnHome(deviceSn);
|
||||
if (res.code === 0) {
|
||||
message.success('取消返航命令已发送');
|
||||
} else {
|
||||
message.error(res.msg || '取消返航命令发送失败');
|
||||
}
|
||||
} catch (error: any) {
|
||||
message.error(error.message || '取消返航命令发送失败');
|
||||
} finally {
|
||||
setLoading(null);
|
||||
}
|
||||
}, [deviceSn]);
|
||||
|
||||
// 航线暂停(紧急悬停)
|
||||
const handlePause = useCallback(async () => {
|
||||
if (!deviceSn) {
|
||||
message.error('未选择设备');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading('pause');
|
||||
try {
|
||||
const res = await deviceApi.pause(deviceSn);
|
||||
if (res.code === 0) {
|
||||
message.success('航线暂停/悬停命令已发送');
|
||||
} else {
|
||||
message.error(res.msg || '暂停命令发送失败');
|
||||
}
|
||||
} catch (error: any) {
|
||||
message.error(error.message || '暂停命令发送失败');
|
||||
} finally {
|
||||
setLoading(null);
|
||||
}
|
||||
}, [deviceSn]);
|
||||
|
||||
// 航线恢复
|
||||
const handleResume = useCallback(async () => {
|
||||
if (!deviceSn) {
|
||||
message.error('未选择设备');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading('resume');
|
||||
try {
|
||||
const res = await deviceApi.resume(deviceSn);
|
||||
if (res.code === 0) {
|
||||
message.success('航线恢复命令已发送');
|
||||
} else {
|
||||
message.error(res.msg || '恢复命令发送失败');
|
||||
}
|
||||
} catch (error: any) {
|
||||
message.error(error.message || '恢复命令发送失败');
|
||||
} finally {
|
||||
setLoading(null);
|
||||
}
|
||||
}, [deviceSn]);
|
||||
|
||||
// 切换相机模式
|
||||
const handleSwitchCameraMode = useCallback(async (mode: 'photo' | 'video') => {
|
||||
if (!deviceSn) {
|
||||
message.error('未选择设备');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading('switchMode');
|
||||
try {
|
||||
// camera_mode: 0=拍照模式, 1=录像模式
|
||||
const cameraModeValue = mode === 'photo' ? 0 : 1;
|
||||
const res = await deviceApi.switchCameraMode(deviceSn, cameraModeValue);
|
||||
if (res?.code === 0) {
|
||||
setCameraMode(mode);
|
||||
message.success(`已切换到${mode === 'photo' ? '拍照' : '录像'}模式`);
|
||||
} else {
|
||||
message.error(res?.msg || '切换相机模式失败');
|
||||
}
|
||||
} catch (error: any) {
|
||||
message.error(error.message || '切换相机模式失败');
|
||||
} finally {
|
||||
setLoading(null);
|
||||
}
|
||||
}, [deviceSn]);
|
||||
|
||||
// 拍照
|
||||
const handleTakePhoto = useCallback(async () => {
|
||||
if (!deviceSn) {
|
||||
message.error('未选择设备');
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果当前是录像模式,先切换到拍照模式
|
||||
if (cameraMode !== 'photo') {
|
||||
await handleSwitchCameraMode('photo');
|
||||
}
|
||||
|
||||
setLoading('photo');
|
||||
try {
|
||||
const res = await deviceApi.takePhoto(deviceSn);
|
||||
if (res.code === 0) {
|
||||
message.success('拍照命令已发送');
|
||||
} else {
|
||||
message.error(res.msg || '拍照命令发送失败');
|
||||
}
|
||||
} catch (error: any) {
|
||||
message.error(error.message || '拍照命令发送失败');
|
||||
} finally {
|
||||
setLoading(null);
|
||||
}
|
||||
}, [deviceSn, cameraMode, handleSwitchCameraMode]);
|
||||
|
||||
// 开始录像
|
||||
const handleStartRecording = useCallback(async () => {
|
||||
if (!deviceSn) {
|
||||
message.error('未选择设备');
|
||||
return;
|
||||
}
|
||||
|
||||
// 先切换到录像模式
|
||||
if (cameraMode !== 'video') {
|
||||
await handleSwitchCameraMode('video');
|
||||
}
|
||||
|
||||
setLoading('recording');
|
||||
try {
|
||||
const res = await deviceApi.startRecording(deviceSn);
|
||||
if (res.code === 0) {
|
||||
setIsRecording(true);
|
||||
message.success('开始录像命令已发送');
|
||||
} else {
|
||||
message.error(res.msg || '开始录像命令发送失败');
|
||||
}
|
||||
} catch (error: any) {
|
||||
message.error(error.message || '开始录像命令发送失败');
|
||||
} finally {
|
||||
setLoading(null);
|
||||
}
|
||||
}, [deviceSn, cameraMode, handleSwitchCameraMode]);
|
||||
|
||||
// 停止录像
|
||||
const handleStopRecording = useCallback(async () => {
|
||||
if (!deviceSn) {
|
||||
message.error('未选择设备');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading('recording');
|
||||
try {
|
||||
const res = await deviceApi.stopRecording(deviceSn);
|
||||
if (res.code === 0) {
|
||||
setIsRecording(false);
|
||||
message.success('停止录像命令已发送');
|
||||
} else {
|
||||
message.error(res.msg || '停止录像命令发送失败');
|
||||
}
|
||||
} catch (error: any) {
|
||||
message.error(error.message || '停止录像命令发送失败');
|
||||
} finally {
|
||||
setLoading(null);
|
||||
}
|
||||
}, [deviceSn]);
|
||||
|
||||
// DRC杆量控制 (使用WebSocket实时发送,需先进入DRC模式)
|
||||
const handleStickControl = useCallback(async (direction: string) => {
|
||||
if (!deviceSn) {
|
||||
message.error('未选择设备');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!wsConnected) {
|
||||
message.warning('实时控制通道未连接,正在重连...');
|
||||
deviceControlWs.connect(deviceSn);
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查是否已进入DRC模式,如果没有则先进入
|
||||
if (!drcModeRef.current) {
|
||||
const entered = await enterDrcMode();
|
||||
if (!entered) return;
|
||||
}
|
||||
|
||||
const offset = 300;
|
||||
let params = { roll: 1024, pitch: 1024, throttle: 1024, yaw: 1024 };
|
||||
|
||||
switch (direction) {
|
||||
case 'up': params.throttle = 1024 + offset; break;
|
||||
case 'down': params.throttle = 1024 - offset; break;
|
||||
case 'left': params.yaw = 1024 - offset; break;
|
||||
case 'right': params.yaw = 1024 + offset; break;
|
||||
case 'forward': params.pitch = 1024 + offset; break;
|
||||
case 'backward': params.pitch = 1024 - offset; break;
|
||||
case 'moveLeft': params.roll = 1024 - offset; break;
|
||||
case 'moveRight': params.roll = 1024 + offset; break;
|
||||
default: break;
|
||||
}
|
||||
|
||||
const success = deviceControlWs.sendStickControl(params);
|
||||
if (!success) {
|
||||
message.error('摇杆指令发送失败');
|
||||
}
|
||||
}, [deviceSn, wsConnected, enterDrcMode]);
|
||||
|
||||
// 云台控制 (使用WebSocket实时发送,需先进入DRC模式)
|
||||
const handleGimbalControl = useCallback(async (direction: string) => {
|
||||
if (!deviceSn) {
|
||||
message.error('未选择设备');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!wsConnected) {
|
||||
message.warning('实时控制通道未连接,正在重连...');
|
||||
deviceControlWs.connect(deviceSn);
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查是否已进入DRC模式,如果没有则先进入
|
||||
if (!drcModeRef.current) {
|
||||
const entered = await enterDrcMode();
|
||||
if (!entered) return;
|
||||
}
|
||||
|
||||
const speed = 20;
|
||||
let params = { pitchSpeed: 0, yawSpeed: 0, locked: false };
|
||||
|
||||
switch (direction) {
|
||||
case 'up': params.pitchSpeed = speed; break;
|
||||
case 'down': params.pitchSpeed = -speed; break;
|
||||
case 'left': params.yawSpeed = -speed; break;
|
||||
case 'right': params.yawSpeed = speed; break;
|
||||
default: break;
|
||||
}
|
||||
|
||||
const success = deviceControlWs.sendGimbalControl(params);
|
||||
if (!success) {
|
||||
message.error('云台指令发送失败');
|
||||
}
|
||||
}, [deviceSn, wsConnected, enterDrcMode]);
|
||||
|
||||
return (
|
||||
<div className={`${styles.leftPanel} ${visible ? styles.visible : ''}`}>
|
||||
@@ -76,12 +542,32 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
</div>
|
||||
<div className={styles.hudOverlay}>
|
||||
<div className={styles.crosshair} />
|
||||
{/* HUD左上角 - 飞行模式和状态 */}
|
||||
<div style={{position: 'absolute', top: 10, left: 10, color: '#0f0', fontSize: 12, fontFamily: 'monospace'}}>
|
||||
CAM: Main<br/>ISO: Auto<br/>EXP: 0.0
|
||||
MODE: {flightData.flightMode}<br/>
|
||||
<span style={{color: droneData ? '#0f0' : '#f00'}}>
|
||||
{droneData ? '● 遥测正常' : '○ 等待遥测'}
|
||||
</span><br/>
|
||||
GIMBAL: P{flightData.gimbalPitch}° Y{flightData.gimbalYaw}°
|
||||
</div>
|
||||
{/* HUD左下角 - 无人机GPS坐标和高度 */}
|
||||
<div style={{position: 'absolute', bottom: 30, left: 10, color: '#0ff', fontSize: 11, fontFamily: 'monospace'}}>
|
||||
<AimOutlined style={{marginRight: 4}} />
|
||||
LAT: {flightData.latitude}°<br/>
|
||||
<span style={{marginLeft: 16}}>LNG: {flightData.longitude}°</span><br/>
|
||||
<span style={{marginLeft: 16}}>ALT: {flightData.altitude}m</span>
|
||||
</div>
|
||||
{/* HUD右上角 - 电池信息 */}
|
||||
<div style={{position: 'absolute', top: 10, right: 10, color: '#fff', fontSize: 12, fontFamily: 'monospace', textAlign: 'right'}}>
|
||||
<span style={{color: Number(flightData.batteryPercent) > 30 ? '#0f0' : '#f00'}}>
|
||||
BAT: {flightData.batteryPercent}%
|
||||
</span><br/>
|
||||
{flightData.batteryVoltage}V / {flightData.batteryTemp}°C<br/>
|
||||
<span style={{color: '#0ff'}}>剩余: {flightData.remainFlightTime}min</span>
|
||||
</div>
|
||||
{/* HUD底部状态条 */}
|
||||
<div style={{
|
||||
position: 'absolute', bottom: 10, left: 10, right: 10,
|
||||
position: 'absolute', bottom: 10, left: 10, right: 10,
|
||||
display: 'flex', justifyContent: 'space-between',
|
||||
color: '#fff', fontSize: 12, textShadow: '0 0 2px #000'
|
||||
}}>
|
||||
@@ -89,73 +575,139 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
<span>D: {flightData.distance}m</span>
|
||||
<span>H.S: {flightData.hSpeed}m/s</span>
|
||||
<span>V.S: {flightData.vSpeed}m/s</span>
|
||||
<span>WIND: {flightData.windSpeed}m/s</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{/* 飞行仪表盘区域 */}
|
||||
<div className={styles.flightDashboard}>
|
||||
<div className={styles.dashItem}>
|
||||
<div className={styles.dashLabel}><CompassOutlined /> PITCH</div>
|
||||
<div className={styles.dashValue}>{flightData.pitch}°</div>
|
||||
</div>
|
||||
<div className={styles.dashItem}>
|
||||
<div className={styles.dashLabel}><CompassOutlined /> ROLL</div>
|
||||
<div className={styles.dashValue}>{flightData.roll}°</div>
|
||||
</div>
|
||||
<div className={styles.dashItem}>
|
||||
<div className={styles.dashLabel}><CompassOutlined /> YAW</div>
|
||||
<div className={styles.dashValue}>{flightData.yaw}°</div>
|
||||
</div>
|
||||
<div className={styles.dashItem}>
|
||||
<div className={styles.dashLabel}>RTK</div>
|
||||
<div className={styles.dashValue} style={{color: '#00ff88'}}>{flightData.rtkStatus}</div>
|
||||
</div>
|
||||
<div className={styles.dashItem}>
|
||||
<div className={styles.dashLabel}>SAT</div>
|
||||
<div className={styles.dashValue}>{flightData.satellites}</div>
|
||||
</div>
|
||||
<div className={styles.dashItem}>
|
||||
<div className={styles.dashLabel}>LINK</div>
|
||||
<div className={styles.dashValue}>{flightData.signal}%</div>
|
||||
</div>
|
||||
<Tooltip title="俯仰角 - 无人机前后倾斜角度">
|
||||
<div className={styles.dashItem}>
|
||||
<div className={styles.dashLabel}><CompassOutlined /> PITCH</div>
|
||||
<div className={styles.dashValue}>{flightData.pitch}°</div>
|
||||
</div>
|
||||
</Tooltip>
|
||||
<Tooltip title="横滚角 - 无人机左右倾斜角度">
|
||||
<div className={styles.dashItem}>
|
||||
<div className={styles.dashLabel}><CompassOutlined /> ROLL</div>
|
||||
<div className={styles.dashValue}>{flightData.roll}°</div>
|
||||
</div>
|
||||
</Tooltip>
|
||||
<Tooltip title="偏航角 - 无人机航向角度">
|
||||
<div className={styles.dashItem}>
|
||||
<div className={styles.dashLabel}><CompassOutlined /> YAW</div>
|
||||
<div className={styles.dashValue}>{flightData.yaw}°</div>
|
||||
</div>
|
||||
</Tooltip>
|
||||
<Tooltip title={`RTK定位状态 (RTK卫星数: ${flightData.rtkSatellites})`}>
|
||||
<div className={styles.dashItem}>
|
||||
<div className={styles.dashLabel}>RTK</div>
|
||||
<div className={styles.dashValue} style={{
|
||||
color: flightData.rtkStatus === 'FIX' ? '#00ff88' :
|
||||
flightData.rtkStatus === 'FLOAT' ? '#ffaa00' : '#ff4444'
|
||||
}}>
|
||||
{flightData.rtkStatus}
|
||||
</div>
|
||||
</div>
|
||||
</Tooltip>
|
||||
<Tooltip title="GPS卫星数量">
|
||||
<div className={styles.dashItem}>
|
||||
<div className={styles.dashLabel}>SAT</div>
|
||||
<div className={styles.dashValue} style={{
|
||||
color: flightData.satellites >= 10 ? '#00ff88' :
|
||||
flightData.satellites >= 6 ? '#ffaa00' : '#ff4444'
|
||||
}}>
|
||||
{flightData.satellites}
|
||||
</div>
|
||||
</div>
|
||||
</Tooltip>
|
||||
<Tooltip title="图传信号质量">
|
||||
<div className={styles.dashItem}>
|
||||
<div className={styles.dashLabel}><WifiOutlined /> LINK</div>
|
||||
<div className={styles.dashValue} style={{
|
||||
color: flightData.signal >= 70 ? '#00ff88' :
|
||||
flightData.signal >= 40 ? '#ffaa00' : '#ff4444'
|
||||
}}>
|
||||
{flightData.signal}%
|
||||
</div>
|
||||
</div>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<div className={styles.controlsContent}>
|
||||
{/* 主要动作 */}
|
||||
{/* 飞行控制指令 */}
|
||||
<div className={styles.controlGroup}>
|
||||
<div className={styles.groupTitle}>快捷指令 / ACTIONS</div>
|
||||
<div className={styles.groupTitle}>飞行控制 / FLIGHT CONTROL</div>
|
||||
<div className={styles.flightActions}>
|
||||
<button
|
||||
onClick={() => handleControl('一键起飞')}
|
||||
disabled={dockData?.mode_code === 1 || dockData?.drone_in_dock !== 1}
|
||||
>
|
||||
<RocketOutlined /> 一键起飞
|
||||
<button onClick={handleReturnHome} disabled={loading === 'return'}>
|
||||
{loading === 'return' ? <LoadingOutlined /> : <HomeOutlined />} 一键返航
|
||||
</button>
|
||||
<button onClick={() => handleControl('一键返航')}>
|
||||
<HomeOutlined /> 一键返航
|
||||
<button onClick={handleCancelReturn} disabled={loading === 'cancelReturn'}>
|
||||
{loading === 'cancelReturn' ? <LoadingOutlined /> : <StopOutlined />} 取消返航
|
||||
</button>
|
||||
<button className={styles.danger} onClick={() => handleControl('紧急悬停')}>
|
||||
<StopOutlined /> 紧急悬停
|
||||
<button className={styles.danger} onClick={handlePause} disabled={loading === 'pause'}>
|
||||
{loading === 'pause' ? <LoadingOutlined /> : <PauseCircleOutlined />} 航线暂停
|
||||
</button>
|
||||
<button onClick={() => handleControl('拍照')}>
|
||||
<CameraOutlined /> 拍照
|
||||
<button onClick={handleResume} disabled={loading === 'resume'}>
|
||||
{loading === 'resume' ? <LoadingOutlined /> : <CaretRightOutlined />} 航线恢复
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 相机控制 */}
|
||||
<div className={styles.controlGroup}>
|
||||
<div className={styles.groupTitle}>
|
||||
相机控制 / CAMERA
|
||||
<Tag color={cameraMode === 'photo' ? 'blue' : 'red'} style={{ marginLeft: 8 }}>
|
||||
{cameraMode === 'photo' ? '拍照模式' : '录像模式'}
|
||||
</Tag>
|
||||
</div>
|
||||
<div className={styles.flightActions}>
|
||||
<button onClick={handleTakePhoto} disabled={loading === 'photo'}>
|
||||
{loading === 'photo' ? <LoadingOutlined /> : <CameraOutlined />} 拍照
|
||||
</button>
|
||||
{!isRecording ? (
|
||||
<button onClick={handleStartRecording} disabled={loading === 'recording'}>
|
||||
{loading === 'recording' ? <LoadingOutlined /> : <PlayCircleOutlined />} 开始录像
|
||||
</button>
|
||||
) : (
|
||||
<button className={styles.danger} onClick={handleStopRecording} disabled={loading === 'recording'}>
|
||||
{loading === 'recording' ? <LoadingOutlined /> : <StopOutlined />} 停止录像
|
||||
</button>
|
||||
)}
|
||||
<button onClick={() => handleSwitchCameraMode(cameraMode === 'photo' ? 'video' : 'photo')} disabled={loading === 'switchMode'}>
|
||||
{loading === 'switchMode' ? <LoadingOutlined /> : <SwapOutlined />} 切换模式
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 飞行姿态控制 (模拟双摇杆) */}
|
||||
<div className={styles.controlGroup}>
|
||||
<div className={styles.groupTitle}>姿态控制 / ATTITUDE CONTROL</div>
|
||||
<div className={styles.groupTitle}>
|
||||
姿态控制 / ATTITUDE CONTROL
|
||||
<Tooltip title={wsConnected ? '实时控制通道已连接' : '实时控制通道未连接'}>
|
||||
<span style={{ marginLeft: 8, fontSize: 12 }}>
|
||||
{wsConnected ? (
|
||||
<LinkOutlined style={{ color: '#00ff88' }} />
|
||||
) : (
|
||||
<DisconnectOutlined style={{ color: '#ff4444' }} />
|
||||
)}
|
||||
</span>
|
||||
</Tooltip>
|
||||
{drcMode && (
|
||||
<Tag color="green" style={{ marginLeft: 8 }}>DRC模式</Tag>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.joystickArea}>
|
||||
{/* 左手:升降 + 转向 */}
|
||||
<div className={styles.joystickGroup}>
|
||||
<div className={styles.joystickLabel}>升降 & 偏航 (Left)</div>
|
||||
<div className={styles.dpad}>
|
||||
<button className={styles.up} onClick={() => handleControl('上升')} title="上升"><VerticalAlignTopOutlined /></button>
|
||||
<button className={styles.left} onClick={() => handleControl('左转')} title="左转"><RotateLeftOutlined /></button>
|
||||
<button className={styles.right} onClick={() => handleControl('右转')} title="右转"><RotateRightOutlined /></button>
|
||||
<button className={styles.down} onClick={() => handleControl('下降')} title="下降"><VerticalAlignBottomOutlined /></button>
|
||||
<button className={styles.up} onClick={() => handleStickControl('up')} title="上升"><VerticalAlignTopOutlined /></button>
|
||||
<button className={styles.left} onClick={() => handleStickControl('left')} title="左转"><RotateLeftOutlined /></button>
|
||||
<button className={styles.right} onClick={() => handleStickControl('right')} title="右转"><RotateRightOutlined /></button>
|
||||
<button className={styles.down} onClick={() => handleStickControl('down')} title="下降"><VerticalAlignBottomOutlined /></button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -163,10 +715,10 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
<div className={styles.joystickGroup}>
|
||||
<div className={styles.joystickLabel}>水平移动 (Right)</div>
|
||||
<div className={styles.dpad}>
|
||||
<button className={styles.up} onClick={() => handleControl('前进')} title="前进"><ArrowUpOutlined /></button>
|
||||
<button className={styles.left} onClick={() => handleControl('向左飞')} title="向左"><ArrowLeftOutlined /></button>
|
||||
<button className={styles.right} onClick={() => handleControl('向右飞')} title="向右"><ArrowRightOutlined /></button>
|
||||
<button className={styles.down} onClick={() => handleControl('后退')} title="后退"><ArrowDownOutlined /></button>
|
||||
<button className={styles.up} onClick={() => handleStickControl('forward')} title="前进"><ArrowUpOutlined /></button>
|
||||
<button className={styles.left} onClick={() => handleStickControl('moveLeft')} title="向左"><ArrowLeftOutlined /></button>
|
||||
<button className={styles.right} onClick={() => handleStickControl('moveRight')} title="向右"><ArrowRightOutlined /></button>
|
||||
<button className={styles.down} onClick={() => handleStickControl('backward')} title="后退"><ArrowDownOutlined /></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -174,15 +726,20 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
|
||||
{/* 云台控制 */}
|
||||
<div className={styles.controlGroup}>
|
||||
<div className={styles.groupTitle}>云台控制 / GIMBAL</div>
|
||||
<div className={styles.groupTitle}>
|
||||
云台控制 / GIMBAL
|
||||
{drcMode && (
|
||||
<Tag color="green" style={{ marginLeft: 8 }}>DRC模式</Tag>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.joystickArea}>
|
||||
<div className={styles.joystickGroup} style={{flex: 1}}>
|
||||
<div className={styles.joystickLabel}>云台方向</div>
|
||||
<div className={styles.dpad}>
|
||||
<button className={styles.up} onClick={() => handleControl('云台向上')}><ArrowUpOutlined /></button>
|
||||
<button className={styles.left} onClick={() => handleControl('云台向左')}><ArrowLeftOutlined /></button>
|
||||
<button className={styles.right} onClick={() => handleControl('云台向右')}><ArrowRightOutlined /></button>
|
||||
<button className={styles.down} onClick={() => handleControl('云台向下')}><ArrowDownOutlined /></button>
|
||||
<button className={styles.up} onClick={() => handleGimbalControl('up')} title="云台上仰"><ArrowUpOutlined /></button>
|
||||
<button className={styles.left} onClick={() => handleGimbalControl('left')} title="云台左转"><ArrowLeftOutlined /></button>
|
||||
<button className={styles.right} onClick={() => handleGimbalControl('right')} title="云台右转"><ArrowRightOutlined /></button>
|
||||
<button className={styles.down} onClick={() => handleGimbalControl('down')} title="云台下俯"><ArrowDownOutlined /></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+79
-7
@@ -1,5 +1,5 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Spin, Empty, message, Tooltip, Tabs, Progress } from 'antd';
|
||||
import { Spin, Empty, message, Tooltip, Tabs, Progress, Modal } from 'antd';
|
||||
import {
|
||||
CloseOutlined,
|
||||
EnvironmentOutlined,
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
ThunderboltOutlined,
|
||||
DashboardOutlined,
|
||||
SignalFilled,
|
||||
LoadingOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { deviceApi } from '@/services/device';
|
||||
import { ordersApi } from '@/services/orders';
|
||||
@@ -24,15 +25,16 @@ interface RightPanelProps {
|
||||
onControlClick: (device: any, realtimeData: any) => void;
|
||||
}
|
||||
|
||||
const RightPanel: React.FC<RightPanelProps> = ({
|
||||
visible,
|
||||
tourism,
|
||||
const RightPanel: React.FC<RightPanelProps> = ({
|
||||
visible,
|
||||
tourism,
|
||||
onClose,
|
||||
onControlClick
|
||||
onControlClick
|
||||
}) => {
|
||||
const [deviceList, setDeviceList] = useState<any[]>([]);
|
||||
const [selectedDeviceSn, setSelectedDeviceSn] = useState<string>('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [takeoffLoading, setTakeoffLoading] = useState(false);
|
||||
|
||||
const { realtimeData, sseConnected, connectSSE, disconnectSSE } = useDeviceSSE();
|
||||
|
||||
@@ -85,6 +87,73 @@ const RightPanel: React.FC<RightPanelProps> = ({
|
||||
|
||||
const formatValue = (val: any, unit: string = '') => (val !== undefined && val !== null ? `${val}${unit}` : '-');
|
||||
|
||||
// 一键起飞
|
||||
const handleTakeoff = () => {
|
||||
const dockData = realtimeData?.rawData?.dockData;
|
||||
|
||||
// 检查机库状态
|
||||
if (dockData?.mode_code === 1) {
|
||||
message.warning('机库正在执行任务,无法起飞');
|
||||
return;
|
||||
}
|
||||
|
||||
// 只有明确知道无人机不在库时才阻止(值为0时)
|
||||
if (dockData?.drone_in_dock === 0) {
|
||||
message.warning('无人机不在库,无法起飞');
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取机库位置信息
|
||||
const dockLatitude = dockData?.latitude || realtimeData?.gps?.latitude;
|
||||
const dockLongitude = dockData?.longitude || realtimeData?.gps?.longitude;
|
||||
const dockHeight = dockData?.height || realtimeData?.gps?.altitude || 0;
|
||||
|
||||
if (!dockLatitude || !dockLongitude) {
|
||||
message.error('无法获取机库位置信息');
|
||||
return;
|
||||
}
|
||||
|
||||
// 弹窗确认
|
||||
Modal.confirm({
|
||||
title: '确认一键起飞',
|
||||
content: (
|
||||
<div>
|
||||
<p>无人机将自动开机并起飞到指定位置</p>
|
||||
<p style={{ fontSize: 12, color: '#666' }}>
|
||||
目标坐标: {dockLatitude.toFixed(6)}, {dockLongitude.toFixed(6)}<br />
|
||||
目标高度: {(dockHeight + 30).toFixed(1)}m (机库高度+30m)
|
||||
</p>
|
||||
</div>
|
||||
),
|
||||
okText: '确认起飞',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
setTakeoffLoading(true);
|
||||
try {
|
||||
const res = await deviceApi.takeoff({
|
||||
deviceSn: selectedDeviceSn,
|
||||
targetLatitude: dockLatitude,
|
||||
targetLongitude: dockLongitude,
|
||||
targetHeight: dockHeight + 30,
|
||||
securityTakeoffHeight: 50,
|
||||
rthAltitude: 50,
|
||||
maxSpeed: 5,
|
||||
});
|
||||
|
||||
if (res.code === 0) {
|
||||
message.success('起飞命令已发送,无人机将自动开机并起飞');
|
||||
} else {
|
||||
message.error(res.msg || '起飞命令发送失败');
|
||||
}
|
||||
} catch (error: any) {
|
||||
message.error(error.message || '起飞命令发送失败');
|
||||
} finally {
|
||||
setTakeoffLoading(false);
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const renderItem = (label: string, value: any, unit: string = '', status: 'normal'|'warning'|'error'|'success' = 'normal') => (
|
||||
<div className={styles.hudItem}>
|
||||
<div className={styles.label}>{label}</div>
|
||||
@@ -190,8 +259,11 @@ const RightPanel: React.FC<RightPanelProps> = ({
|
||||
<button className={styles.primary} onClick={() => onControlClick(selectedDevice, realtimeData)}>
|
||||
<VideoCameraOutlined /> 进入操控台
|
||||
</button>
|
||||
<button disabled={dockData?.mode_code === 1 || dockData?.drone_in_dock !== 1} onClick={() => message.info('一键起飞指令发送')}>
|
||||
<RocketOutlined /> 一键起飞
|
||||
<button
|
||||
disabled={takeoffLoading || dockData?.mode_code === 1 || dockData?.drone_in_dock === 0}
|
||||
onClick={handleTakeoff}
|
||||
>
|
||||
{takeoffLoading ? <LoadingOutlined /> : <RocketOutlined />} 一键起飞
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+57
-1
@@ -14,6 +14,60 @@ export interface DockData {
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
// 无人机遥测数据接口定义
|
||||
export interface DroneData {
|
||||
// 飞行姿态
|
||||
attitude_pitch?: number; // 俯仰角 (度)
|
||||
attitude_roll?: number; // 横滚角 (度)
|
||||
attitude_head?: number; // 偏航角/航向 (度)
|
||||
|
||||
// 速度
|
||||
horizontal_speed?: number; // 水平速度 (m/s)
|
||||
vertical_speed?: number; // 垂直速度 (m/s)
|
||||
ground_speed?: number; // 地面速度 (m/s)
|
||||
|
||||
// 位置
|
||||
latitude?: number; // 纬度
|
||||
longitude?: number; // 经度
|
||||
height?: number; // 高度 (m)
|
||||
elevation?: number; // 海拔高度 (m)
|
||||
home_distance?: number; // 距Home点距离 (m)
|
||||
|
||||
// 电池
|
||||
battery?: {
|
||||
capacity_percent?: number; // 电量百分比
|
||||
voltage?: number; // 电压 (mV)
|
||||
temperature?: number; // 温度 (°C)
|
||||
remain_flight_time?: number; // 剩余飞行时间 (s)
|
||||
};
|
||||
|
||||
// 飞行模式
|
||||
mode_code?: number; // 飞行模式代码
|
||||
gear?: number; // 档位
|
||||
|
||||
// RTK/GPS
|
||||
position_state?: {
|
||||
rtk_number?: number; // RTK 卫星数
|
||||
gps_number?: number; // GPS 卫星数
|
||||
is_fixed?: number; // 是否固定 (1=FIX)
|
||||
};
|
||||
|
||||
// 云台
|
||||
gimbal_pitch?: number; // 云台俯仰角
|
||||
gimbal_roll?: number; // 云台横滚角
|
||||
gimbal_yaw?: number; // 云台偏航角
|
||||
|
||||
// 其他
|
||||
wind_speed?: number; // 风速 (m/s)
|
||||
wind_direction?: number; // 风向 (度)
|
||||
storage?: {
|
||||
total?: number; // 存储总容量
|
||||
used?: number; // 已使用容量
|
||||
};
|
||||
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
// 实时数据
|
||||
export interface RealtimeData {
|
||||
deviceSn: string;
|
||||
@@ -26,7 +80,9 @@ export interface RealtimeData {
|
||||
flightStatus?: string;
|
||||
timestamp?: number;
|
||||
rawData?: {
|
||||
dockData?: any;
|
||||
dockData?: any; // 机库状态数据 (fire_alarm)
|
||||
droneData?: DroneData; // 无人机遥测数据 (msg_alarm)
|
||||
msgAlarmData?: any; // msg_alarm 完整数据
|
||||
[key: string]: any;
|
||||
};
|
||||
}
|
||||
|
||||
+26
-5
@@ -13,7 +13,10 @@ export interface TilesetConfig {
|
||||
position?: { // 模型位置调整
|
||||
longitude?: number; // 经度偏移
|
||||
latitude?: number; // 纬度偏移
|
||||
height?: number; // 高度偏移
|
||||
height?: number; // 高度偏移(通用)
|
||||
cesiumHeight?: number; // Cesium Ion地形对应的高度偏移
|
||||
arcgisHeight?: number; // ArcGIS地形对应的高度偏移
|
||||
terrainType?: string; // 高度标定时使用的地形服务: cesium_ion/arcgis/ellipsoid
|
||||
};
|
||||
transform?: { // 模型变换
|
||||
scale?: number; // 缩放比例
|
||||
@@ -42,7 +45,7 @@ export interface TilesetState {
|
||||
// Hook返回类型
|
||||
export interface UseTilesetLoaderResult {
|
||||
tilesets: Map<string, TilesetState>;
|
||||
loadTileset: (config: TilesetConfig, viewer: any, Cesium: any) => Promise<any>;
|
||||
loadTileset: (config: TilesetConfig, viewer: any, Cesium: any, currentTerrainType?: string) => Promise<any>;
|
||||
unloadTileset: (id: string, viewer: any) => void;
|
||||
unloadAllTilesets: (viewer: any) => void;
|
||||
flyToTileset: (id: string, viewer: any, Cesium: any) => void;
|
||||
@@ -56,11 +59,16 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
|
||||
|
||||
/**
|
||||
* 加载3D Tiles模型
|
||||
* @param config 模型配置
|
||||
* @param viewer Cesium Viewer实例
|
||||
* @param Cesium Cesium模块
|
||||
* @param currentTerrainType 当前使用的地形类型,用于选择对应的高度偏移
|
||||
*/
|
||||
const loadTileset = useCallback(async (
|
||||
config: TilesetConfig,
|
||||
viewer: any,
|
||||
Cesium: any
|
||||
Cesium: any,
|
||||
currentTerrainType?: string
|
||||
): Promise<any> => {
|
||||
if (!viewer || !Cesium) {
|
||||
console.error('Viewer或Cesium未初始化');
|
||||
@@ -138,9 +146,22 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
|
||||
});
|
||||
});
|
||||
|
||||
// 模型位置调整 - 只有当位置偏移不为0时才调整
|
||||
// 模型位置调整 - 根据当前地形类型选择对应的高度偏移
|
||||
if (config.position) {
|
||||
const { longitude = 0, latitude = 0, height = 0 } = config.position;
|
||||
const { longitude = 0, latitude = 0, cesiumHeight, arcgisHeight } = config.position;
|
||||
|
||||
// 根据当前地形类型选择对应的高度偏移
|
||||
let height = config.position.height || 0; // 默认使用通用高度
|
||||
if (currentTerrainType === 'cesium_ion' && cesiumHeight !== undefined && cesiumHeight !== null) {
|
||||
height = cesiumHeight;
|
||||
console.log(`模型 [${config.name}] 使用 Cesium Ion 高度偏移: ${height}`);
|
||||
} else if (currentTerrainType === 'arcgis' && arcgisHeight !== undefined && arcgisHeight !== null) {
|
||||
height = arcgisHeight;
|
||||
console.log(`模型 [${config.name}] 使用 ArcGIS 高度偏移: ${height}`);
|
||||
} else {
|
||||
console.log(`模型 [${config.name}] 使用通用高度偏移: ${height}`);
|
||||
}
|
||||
|
||||
// 只有当有非零偏移时才应用位置调整
|
||||
if (longitude !== 0 || latitude !== 0 || height !== 0) {
|
||||
const boundingSphere = tileset.boundingSphere;
|
||||
|
||||
+165
-26
@@ -33,8 +33,10 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
|
||||
// 3D Tiles 模型管理
|
||||
const [tilesetPanelVisible, setTilesetPanelVisible] = useState(false);
|
||||
const [currentTourismModels, setCurrentTourismModels] = useState<TilesetConfig[]>([]); // 当前景区的模型
|
||||
const [currentTourismModels, setCurrentTourismModels] = useState<TilesetConfig[]>([]); // 当前景区的所有模型配置
|
||||
const [modelLoading, setModelLoading] = useState(false);
|
||||
const [terrainLoading, setTerrainLoading] = useState(false); // 是否正在加载高程地形
|
||||
const terrainLoadedRef = useRef(false); // 是否已加载高程地形
|
||||
const {
|
||||
tilesets,
|
||||
loadTileset,
|
||||
@@ -79,7 +81,100 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
});
|
||||
}, []);
|
||||
|
||||
// 加载景区绑定的模型,返回是否有模型
|
||||
/**
|
||||
* 动态切换到高程地形
|
||||
* 在进入景区详情、加载3D模型时调用
|
||||
* @param preferredTerrainType 优先使用的地形类型(从模型配置中获取)
|
||||
*/
|
||||
const switchToElevationTerrain = useCallback(async (preferredTerrainType?: string): Promise<string> => {
|
||||
if (!viewerRef.current || !Cesium) {
|
||||
return 'ellipsoid';
|
||||
}
|
||||
|
||||
// 如果已加载且地形类型匹配,跳过
|
||||
if (terrainLoadedRef.current && !preferredTerrainType) {
|
||||
return 'loaded';
|
||||
}
|
||||
|
||||
setTerrainLoading(true);
|
||||
console.log('开始加载高程地形...', preferredTerrainType ? `优先使用: ${preferredTerrainType}` : '');
|
||||
|
||||
let loadedTerrainType = 'ellipsoid';
|
||||
|
||||
// 根据优先地形类型决定加载顺序
|
||||
if (preferredTerrainType === 'arcgis') {
|
||||
// 优先尝试 ArcGIS
|
||||
try {
|
||||
const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
|
||||
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
|
||||
);
|
||||
console.log('高程地形加载成功: ArcGIS World Elevation (根据模型配置)');
|
||||
viewerRef.current.terrainProvider = terrainProvider;
|
||||
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
|
||||
terrainLoadedRef.current = true;
|
||||
loadedTerrainType = 'arcgis';
|
||||
} catch (arcgisError) {
|
||||
console.warn('ArcGIS 加载失败,尝试 Cesium Ion:', arcgisError);
|
||||
try {
|
||||
const terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
|
||||
requestVertexNormals: true,
|
||||
requestWaterMask: true,
|
||||
});
|
||||
console.log('高程地形加载成功: Cesium World Terrain (备用)');
|
||||
viewerRef.current.terrainProvider = terrainProvider;
|
||||
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
|
||||
terrainLoadedRef.current = true;
|
||||
loadedTerrainType = 'cesium_ion';
|
||||
message.warning('ArcGIS地形加载失败,已切换到Cesium Ion,模型高度可能有偏差');
|
||||
} catch (cesiumError) {
|
||||
console.warn('Cesium Ion 也加载失败,保持椭球地形:', cesiumError);
|
||||
loadedTerrainType = 'ellipsoid';
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 默认优先尝试 Cesium Ion
|
||||
try {
|
||||
const terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
|
||||
requestVertexNormals: true,
|
||||
requestWaterMask: true,
|
||||
});
|
||||
console.log('高程地形加载成功: Cesium World Terrain');
|
||||
viewerRef.current.terrainProvider = terrainProvider;
|
||||
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
|
||||
terrainLoadedRef.current = true;
|
||||
loadedTerrainType = 'cesium_ion';
|
||||
} catch (cesiumError) {
|
||||
console.warn('Cesium World Terrain 加载失败,尝试 ArcGIS:', cesiumError);
|
||||
try {
|
||||
const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
|
||||
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
|
||||
);
|
||||
console.log('高程地形加载成功: ArcGIS World Elevation');
|
||||
viewerRef.current.terrainProvider = terrainProvider;
|
||||
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
|
||||
terrainLoadedRef.current = true;
|
||||
loadedTerrainType = 'arcgis';
|
||||
if (preferredTerrainType === 'cesium_ion') {
|
||||
message.warning('Cesium Ion地形加载失败,已切换到ArcGIS,模型高度可能有偏差');
|
||||
}
|
||||
} catch (arcgisError) {
|
||||
console.warn('ArcGIS World Elevation 也加载失败,保持椭球地形:', arcgisError);
|
||||
loadedTerrainType = 'ellipsoid';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setTerrainLoading(false);
|
||||
return loadedTerrainType;
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 加载景区绑定的模型
|
||||
* 策略:
|
||||
* 1. 默认只加载第一个模型(通常是主模型)
|
||||
* 2. 其他模型存储在 currentTourismModels 中,可通过模型面板手动加载
|
||||
* 3. 如果模型数量较少(<=2个),自动加载所有模型
|
||||
*/
|
||||
const loadTourismModels = useCallback(async (tourismId: number): Promise<boolean> => {
|
||||
if (!viewerRef.current || !Cesium) {
|
||||
console.log('Viewer或Cesium未准备好');
|
||||
@@ -101,39 +196,63 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
if (res.resp_code === 0 && modelList && modelList.length > 0) {
|
||||
const configs = modelList.map((model: any) => convertToTilesetConfig(model));
|
||||
console.log('转换后的模型配置:', configs);
|
||||
|
||||
// 保存所有模型配置(供模型面板使用)
|
||||
setCurrentTourismModels(configs);
|
||||
|
||||
// 【重要】加载模型前,先切换到高程地形
|
||||
// 从第一个模型的配置中获取地形类型(用于保持与高度标定时一致的地形)
|
||||
const firstModelTerrainType = configs[0]?.position?.terrainType;
|
||||
console.log('第一个模型的地形类型配置:', firstModelTerrainType);
|
||||
const loadedTerrainType = await switchToElevationTerrain(firstModelTerrainType);
|
||||
console.log('实际加载的地形类型:', loadedTerrainType);
|
||||
|
||||
// 确定要自动加载的模型数量
|
||||
// 策略:模型数量 <= 2 时全部加载,否则只加载第一个
|
||||
const autoLoadCount = configs.length <= 2 ? configs.length : 1;
|
||||
const configsToLoad = configs.slice(0, autoLoadCount);
|
||||
|
||||
if (configs.length > autoLoadCount) {
|
||||
message.info(`景区共有 ${configs.length} 个模型,已自动加载第 1 个,其他可通过模型面板加载`);
|
||||
}
|
||||
|
||||
let loadedCount = 0;
|
||||
// 加载所有模型
|
||||
for (const config of configs) {
|
||||
let firstTileset: any = null;
|
||||
|
||||
// 加载指定数量的模型,传入实际加载的地形类型
|
||||
for (const config of configsToLoad) {
|
||||
console.log('准备加载模型:', config.name, 'URL:', config.url);
|
||||
if (config.url) {
|
||||
const tileset = await loadTileset(config, viewerRef.current, Cesium);
|
||||
const tileset = await loadTileset(config, viewerRef.current, Cesium, loadedTerrainType);
|
||||
if (tileset) {
|
||||
loadedCount++;
|
||||
message.success(`模型 [${config.name}] 加载成功`);
|
||||
// 加载成功后飞到第一个模型位置
|
||||
if (loadedCount === 1) {
|
||||
// 使用 viewer.flyTo 自动飞到模型
|
||||
try {
|
||||
await viewerRef.current.flyTo(tileset, {
|
||||
duration: 2.0,
|
||||
offset: new Cesium.HeadingPitchRange(
|
||||
Cesium.Math.toRadians(0),
|
||||
Cesium.Math.toRadians(-45),
|
||||
0
|
||||
),
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('flyTo 失败,尝试 zoomTo:', e);
|
||||
await viewerRef.current.zoomTo(tileset);
|
||||
}
|
||||
firstTileset = tileset;
|
||||
}
|
||||
message.success(`模型 [${config.name}] 加载成功`);
|
||||
}
|
||||
} else {
|
||||
console.warn('模型URL为空,跳过加载:', config.name);
|
||||
}
|
||||
}
|
||||
|
||||
// 飞到第一个加载成功的模型
|
||||
if (firstTileset) {
|
||||
try {
|
||||
await viewerRef.current.flyTo(firstTileset, {
|
||||
duration: 2.0,
|
||||
offset: new Cesium.HeadingPitchRange(
|
||||
Cesium.Math.toRadians(0),
|
||||
Cesium.Math.toRadians(-45),
|
||||
0
|
||||
),
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('flyTo 失败,尝试 zoomTo:', e);
|
||||
await viewerRef.current.zoomTo(firstTileset);
|
||||
}
|
||||
}
|
||||
|
||||
setModelLoading(false);
|
||||
return loadedCount > 0;
|
||||
} else {
|
||||
@@ -146,7 +265,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
setModelLoading(false);
|
||||
return false;
|
||||
}
|
||||
}, [loadTileset, unloadAllTilesets]);
|
||||
}, [loadTileset, unloadAllTilesets, switchToElevationTerrain]);
|
||||
|
||||
// 处理景区点击
|
||||
const handleTourismSelect = useCallback((tourism: any) => {
|
||||
@@ -234,6 +353,13 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
Cesium = cesiumModule;
|
||||
const cesiumBaseUrl = process.env.CESIUM_BASE_URL || '/';
|
||||
Cesium.buildModuleUrl.setBaseUrl(`${cesiumBaseUrl}cesium/`);
|
||||
|
||||
// 设置 Cesium Ion Access Token(用于加载 Cesium World Terrain)
|
||||
const cesiumToken = process.env.REACT_APP_CESIUM_TOKEN;
|
||||
if (cesiumToken) {
|
||||
Cesium.Ion.defaultAccessToken = cesiumToken;
|
||||
}
|
||||
|
||||
if (!document.querySelector('link[href*="cesium"]')) {
|
||||
const link = document.createElement('link');
|
||||
link.rel = 'stylesheet';
|
||||
@@ -244,8 +370,18 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
|
||||
if (!containerRef.current) return;
|
||||
|
||||
// 【重要】初始化时使用椭球地形(无高程),快速加载
|
||||
// 原因:
|
||||
// 1. 全球地形加载较慢,影响首屏体验
|
||||
// 2. Cesium World Terrain 精度约30m,与大疆建图的厘米级精度差异大
|
||||
// 会导致模型部分贴合、部分悬浮、部分嵌入地面的问题
|
||||
// 3. 大疆建图的模型本身包含了高精度的地形信息,不需要额外的地形数据
|
||||
// 解决方案:使用椭球地形 + 模型高度偏移微调
|
||||
const terrainProvider = new Cesium.EllipsoidTerrainProvider();
|
||||
console.log('地图仪表盘: 使用椭球地形(快速加载,模型自带高程)');
|
||||
|
||||
viewerRef.current = new Cesium.Viewer(containerRef.current, {
|
||||
terrainProvider: new Cesium.EllipsoidTerrainProvider(),
|
||||
terrainProvider: terrainProvider,
|
||||
scene3DOnly: false,
|
||||
shouldAnimate: true,
|
||||
animation: false,
|
||||
@@ -262,6 +398,9 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
maximumRenderTimeChange: Infinity,
|
||||
});
|
||||
|
||||
// 使用椭球地形时不需要深度测试
|
||||
// viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
|
||||
|
||||
viewerRef.current.imageryLayers.remove(viewerRef.current.imageryLayers.get(0));
|
||||
viewerRef.current.scene.globe.baseColor = Cesium.Color.fromCssColorString('#1e4d7b');
|
||||
|
||||
@@ -442,8 +581,8 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 模型加载中提示 */}
|
||||
{modelLoading && (
|
||||
{/* 地形/模型加载中提示 */}
|
||||
{(terrainLoading || modelLoading) && (
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
@@ -458,7 +597,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
zIndex: 800,
|
||||
}}
|
||||
>
|
||||
正在加载3D模型...
|
||||
{terrainLoading ? '正在加载高程地形...' : '正在加载3D模型...'}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -16,6 +16,83 @@ export interface DeviceItem {
|
||||
createTime?: string;
|
||||
}
|
||||
|
||||
// ========== 指令相关接口类型 ==========
|
||||
|
||||
/** 一键起飞参数 */
|
||||
export interface TakeoffParams {
|
||||
deviceSn: string;
|
||||
/** 目标点纬度 */
|
||||
targetLatitude: number;
|
||||
/** 目标点经度 */
|
||||
targetLongitude: number;
|
||||
/** 目标点高度(椭球高),使用 WGS84 模型,默认100 */
|
||||
targetHeight?: number;
|
||||
/** 安全起飞高度,相对起飞点的高度,默认50 */
|
||||
securityTakeoffHeight?: number;
|
||||
/** 返航模式:0=智能高度,1=设定高度,默认1 */
|
||||
rthMode?: number;
|
||||
/** 返航高度,相对起飞点的高度,默认50 */
|
||||
rthAltitude?: number;
|
||||
/** 遥控器失控动作:0=悬停,1=降落,2=返航,默认2 */
|
||||
rcLostAction?: number;
|
||||
/** 指点飞行失控动作:0=继续执行,1=退出任务,默认1 */
|
||||
commanderModeLostAction?: number;
|
||||
/** 指点飞行模式:0=智能高度飞行,1=设定高度飞行,默认1 */
|
||||
commanderFlightMode?: number;
|
||||
/** 指点飞行高度,相对起飞点的高度,默认50 */
|
||||
commanderFlightHeight?: number;
|
||||
/** 一键起飞任务UUID,不传则自动生成 */
|
||||
flightId?: string;
|
||||
/** 最大飞行速度(m/s),范围1-15,默认5 */
|
||||
maxSpeed?: number;
|
||||
/** 飞行安全预检查:0=关闭,1=开启,默认0 */
|
||||
flightSafetyAdvanceCheck?: number;
|
||||
}
|
||||
|
||||
/** DRC杆量控制参数 */
|
||||
export interface StickControlParams {
|
||||
deviceSn: string;
|
||||
/** 横滚通道(624-1424,1024为中值,控制左右平移) */
|
||||
roll?: number;
|
||||
/** 俯仰通道(624-1424,1024为中值,控制前后平移) */
|
||||
pitch?: number;
|
||||
/** 升降通道(624-1424,1024为悬停,控制升降) */
|
||||
throttle?: number;
|
||||
/** 偏航通道(624-1424,1024为中值,控制左右旋转) */
|
||||
yaw?: number;
|
||||
}
|
||||
|
||||
/** 云台控制参数 */
|
||||
export interface GimbalControlParams {
|
||||
deviceSn: string;
|
||||
/** 云台 pitch 速度(度/秒) */
|
||||
pitchSpeed?: number;
|
||||
/** 云台 yaw 速度(度/秒) */
|
||||
yawSpeed?: number;
|
||||
/** 是否锁定机头:false=仅云台转,true=机身一起转 */
|
||||
locked?: boolean;
|
||||
}
|
||||
|
||||
/** 命令响应结果 */
|
||||
export interface CommandResult {
|
||||
code: number;
|
||||
msg: string;
|
||||
data?: string; // commandId
|
||||
}
|
||||
|
||||
/** 命令状态 */
|
||||
export interface CommandStatus {
|
||||
commandId: string;
|
||||
deviceSn: string;
|
||||
commandType: string;
|
||||
status: string;
|
||||
statusDesc: string;
|
||||
createTime?: number;
|
||||
sendTime?: number;
|
||||
retryCount?: number;
|
||||
errorMsg?: string;
|
||||
}
|
||||
|
||||
export const deviceApi = {
|
||||
wayline: async (params: { current?: number; pageSize?: number; [k:string]: any }) => {
|
||||
const { current, pageSize, ...rest } = params || {};
|
||||
@@ -69,5 +146,210 @@ export const deviceApi = {
|
||||
const res = await request(`/api-device/device/${deviceSn}`, { method: 'DELETE' });
|
||||
return (res as any).data || res;
|
||||
},
|
||||
|
||||
// ========== 设备指令控制 ==========
|
||||
|
||||
/**
|
||||
* 一键起飞(飞向指定点)
|
||||
* @param params 起飞参数
|
||||
* @returns 命令ID
|
||||
*/
|
||||
takeoff: async (params: TakeoffParams): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/takeoff', {
|
||||
method: 'POST',
|
||||
data: params,
|
||||
});
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
/**
|
||||
* 一键返航
|
||||
* @param deviceSn 设备SN
|
||||
* @returns 命令ID
|
||||
*/
|
||||
returnHome: async (deviceSn: string): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/return', {
|
||||
method: 'POST',
|
||||
params: { deviceSn },
|
||||
});
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
/**
|
||||
* 取消返航
|
||||
* @param deviceSn 设备SN
|
||||
* @returns 命令ID
|
||||
*/
|
||||
cancelReturnHome: async (deviceSn: string): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/return/cancel', {
|
||||
method: 'POST',
|
||||
params: { deviceSn },
|
||||
});
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
/**
|
||||
* 航线暂停/紧急悬停
|
||||
* @param deviceSn 设备SN
|
||||
* @returns 命令ID
|
||||
*/
|
||||
pause: async (deviceSn: string): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/pause', {
|
||||
method: 'POST',
|
||||
params: { deviceSn },
|
||||
});
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
/**
|
||||
* 航线恢复
|
||||
* @param deviceSn 设备SN
|
||||
* @returns 命令ID
|
||||
*/
|
||||
resume: async (deviceSn: string): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/resume', {
|
||||
method: 'POST',
|
||||
params: { deviceSn },
|
||||
});
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
/**
|
||||
* 拍照
|
||||
* @param deviceSn 设备SN
|
||||
* @returns 命令ID
|
||||
*/
|
||||
takePhoto: async (deviceSn: string): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/photo', {
|
||||
method: 'POST',
|
||||
params: { deviceSn },
|
||||
});
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
/**
|
||||
* 开始录像
|
||||
* @param deviceSn 设备SN
|
||||
* @returns 命令ID
|
||||
*/
|
||||
startRecording: async (deviceSn: string): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/recording/start', {
|
||||
method: 'POST',
|
||||
params: { deviceSn },
|
||||
});
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
/**
|
||||
* 停止录像
|
||||
* @param deviceSn 设备SN
|
||||
* @returns 命令ID
|
||||
*/
|
||||
stopRecording: async (deviceSn: string): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/recording/stop', {
|
||||
method: 'POST',
|
||||
params: { deviceSn },
|
||||
});
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
/**
|
||||
* 切换相机模式
|
||||
* @param deviceSn 设备SN
|
||||
* @param cameraMode 相机模式:0=拍照模式,1=录像模式
|
||||
* @returns 命令ID
|
||||
*/
|
||||
switchCameraMode: async (deviceSn: string, cameraMode: number): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/camera/mode', {
|
||||
method: 'POST',
|
||||
params: { deviceSn, cameraMode },
|
||||
});
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
/**
|
||||
* 进入指令飞行模式(DRC模式)
|
||||
* @param deviceSn 设备SN
|
||||
* @returns 命令ID
|
||||
*/
|
||||
enterDrcMode: async (deviceSn: string): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/drc/enter', {
|
||||
method: 'POST',
|
||||
params: { deviceSn },
|
||||
});
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
/**
|
||||
* DRC杆量控制
|
||||
* @param params 杆量控制参数
|
||||
* @returns 命令ID
|
||||
*/
|
||||
stickControl: async (params: StickControlParams): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/drc/stick', {
|
||||
method: 'POST',
|
||||
data: params,
|
||||
});
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
/**
|
||||
* 云台控制
|
||||
* @param params 云台控制参数
|
||||
* @returns 命令ID
|
||||
*/
|
||||
gimbalControl: async (params: GimbalControlParams): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/gimbal', {
|
||||
method: 'POST',
|
||||
data: params,
|
||||
});
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
/**
|
||||
* 查询命令状态
|
||||
* @param commandId 命令ID
|
||||
* @returns 命令状态
|
||||
*/
|
||||
getCommandStatus: async (commandId: string): Promise<{ code: number; data: CommandStatus }> => {
|
||||
const res = await request(`/api-device/device/command/status/${commandId}`, {
|
||||
method: 'GET',
|
||||
});
|
||||
return res as { code: number; data: CommandStatus };
|
||||
},
|
||||
|
||||
// ========== 无人机遥测数据订阅 ==========
|
||||
|
||||
/**
|
||||
* 订阅无人机遥测数据(msg_alarm)
|
||||
* 进入操控台时调用,开始接收无人机实时遥测数据
|
||||
* @param deviceSn 设备SN
|
||||
*/
|
||||
subscribeDroneTelemetry: async (deviceSn: string): Promise<{ success: boolean; message?: string }> => {
|
||||
try {
|
||||
const res = await request(`/api-device/sse/drone-telemetry/${deviceSn}/subscribe`, {
|
||||
method: 'POST',
|
||||
});
|
||||
return { success: true, message: res as string };
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message };
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 取消订阅无人机遥测数据(msg_alarm)
|
||||
* 退出操控台时调用,停止接收无人机实时遥测数据
|
||||
* @param deviceSn 设备SN
|
||||
*/
|
||||
unsubscribeDroneTelemetry: async (deviceSn: string): Promise<{ success: boolean; message?: string }> => {
|
||||
try {
|
||||
const res = await request(`/api-device/sse/drone-telemetry/${deviceSn}/unsubscribe`, {
|
||||
method: 'POST',
|
||||
});
|
||||
return { success: true, message: res as string };
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message };
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
/**
|
||||
* 设备实时控制WebSocket服务
|
||||
* 用于高频率的云台控制和摇杆控制(5-10Hz)
|
||||
*/
|
||||
|
||||
export interface StickControlData {
|
||||
/** 横滚通道(624-1424,1024为中值,控制左右平移) */
|
||||
roll?: number;
|
||||
/** 俯仰通道(624-1424,1024为中值,控制前后平移) */
|
||||
pitch?: number;
|
||||
/** 升降通道(624-1424,1024为悬停,控制升降) */
|
||||
throttle?: number;
|
||||
/** 偏航通道(624-1424,1024为中值,控制左右旋转) */
|
||||
yaw?: number;
|
||||
}
|
||||
|
||||
export interface GimbalControlData {
|
||||
/** 云台 pitch 速度(度/秒) */
|
||||
pitchSpeed?: number;
|
||||
/** 云台 yaw 速度(度/秒) */
|
||||
yawSpeed?: number;
|
||||
/** 是否锁定机头:false=仅云台转,true=机身一起转 */
|
||||
locked?: boolean;
|
||||
}
|
||||
|
||||
export interface ControlMessage {
|
||||
type: 'stick_control' | 'gimbal_control' | 'heartbeat';
|
||||
deviceSn: string;
|
||||
data?: StickControlData | GimbalControlData;
|
||||
}
|
||||
|
||||
export interface ControlResponse {
|
||||
type: 'response' | 'error' | 'pong';
|
||||
success?: boolean;
|
||||
message?: string;
|
||||
commandId?: string;
|
||||
}
|
||||
|
||||
type MessageHandler = (message: ControlResponse) => void;
|
||||
type StatusHandler = (connected: boolean) => void;
|
||||
|
||||
class DeviceControlWebSocket {
|
||||
private ws: WebSocket | null = null;
|
||||
private reconnectTimer: NodeJS.Timeout | null = null;
|
||||
private heartbeatTimer: NodeJS.Timeout | null = null;
|
||||
private reconnectAttempts = 0;
|
||||
private maxReconnectAttempts = 5;
|
||||
private reconnectDelay = 2000;
|
||||
private heartbeatInterval = 15000;
|
||||
|
||||
private messageHandlers: MessageHandler[] = [];
|
||||
private statusHandlers: StatusHandler[] = [];
|
||||
|
||||
private currentDeviceSn: string | null = null;
|
||||
private manualClose = false;
|
||||
|
||||
/**
|
||||
* 连接WebSocket
|
||||
* @param deviceSn 设备SN
|
||||
*/
|
||||
connect(deviceSn: string): void {
|
||||
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
||||
if (this.currentDeviceSn === deviceSn) {
|
||||
console.log('[ControlWS] 已连接到该设备');
|
||||
return;
|
||||
}
|
||||
// 切换设备,先断开
|
||||
this.disconnect();
|
||||
}
|
||||
|
||||
this.currentDeviceSn = deviceSn;
|
||||
this.reconnectAttempts = 0;
|
||||
this.manualClose = false;
|
||||
this.doConnect();
|
||||
}
|
||||
|
||||
private doConnect(): void {
|
||||
if (!this.currentDeviceSn) return;
|
||||
|
||||
try {
|
||||
// WebSocket地址,通过网关代理到device-center
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const host = window.location.host;
|
||||
const url = `${protocol}//${host}/api-device/ws/control/${this.currentDeviceSn}`;
|
||||
|
||||
console.log('[ControlWS] 连接:', url);
|
||||
this.ws = new WebSocket(url);
|
||||
|
||||
this.ws.onopen = () => {
|
||||
console.log('[ControlWS] 连接成功');
|
||||
this.reconnectAttempts = 0;
|
||||
this.startHeartbeat();
|
||||
this.notifyStatusHandlers(true);
|
||||
};
|
||||
|
||||
this.ws.onmessage = (event) => {
|
||||
try {
|
||||
const message = JSON.parse(event.data) as ControlResponse;
|
||||
if (message.type !== 'pong') {
|
||||
console.log('[ControlWS] 收到消息:', message);
|
||||
}
|
||||
this.notifyMessageHandlers(message);
|
||||
} catch (e) {
|
||||
console.warn('[ControlWS] 解析消息失败:', e);
|
||||
}
|
||||
};
|
||||
|
||||
this.ws.onclose = (event) => {
|
||||
console.log('[ControlWS] 断开:', event.code, event.reason);
|
||||
this.stopHeartbeat();
|
||||
this.notifyStatusHandlers(false);
|
||||
|
||||
// 非手动关闭,尝试重连
|
||||
if (!this.manualClose && this.currentDeviceSn) {
|
||||
this.scheduleReconnect();
|
||||
}
|
||||
};
|
||||
|
||||
this.ws.onerror = (error) => {
|
||||
console.error('[ControlWS] 错误:', error);
|
||||
};
|
||||
} catch (e) {
|
||||
console.error('[ControlWS] 创建失败:', e);
|
||||
this.scheduleReconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleReconnect(): void {
|
||||
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
||||
console.error('[ControlWS] 重连次数超限,停止重连');
|
||||
return;
|
||||
}
|
||||
|
||||
this.reconnectAttempts++;
|
||||
const delay = this.reconnectDelay * Math.pow(1.5, this.reconnectAttempts - 1);
|
||||
console.log(`[ControlWS] ${delay}ms后重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
|
||||
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
this.doConnect();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
private startHeartbeat(): void {
|
||||
this.stopHeartbeat();
|
||||
this.heartbeatTimer = setInterval(() => {
|
||||
if (this.currentDeviceSn) {
|
||||
this.send({ type: 'heartbeat', deviceSn: this.currentDeviceSn });
|
||||
}
|
||||
}, this.heartbeatInterval);
|
||||
}
|
||||
|
||||
private stopHeartbeat(): void {
|
||||
if (this.heartbeatTimer) {
|
||||
clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 断开连接
|
||||
*/
|
||||
disconnect(): void {
|
||||
this.manualClose = true;
|
||||
this.currentDeviceSn = null;
|
||||
this.stopHeartbeat();
|
||||
|
||||
if (this.reconnectTimer) {
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
|
||||
if (this.ws) {
|
||||
this.ws.close(1000, 'Manual disconnect');
|
||||
this.ws = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息
|
||||
*/
|
||||
private send(message: ControlMessage): boolean {
|
||||
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
||||
console.warn('[ControlWS] 未连接,无法发送');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
this.ws.send(JSON.stringify(message));
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.error('[ControlWS] 发送失败:', e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送摇杆控制指令
|
||||
*/
|
||||
sendStickControl(data: StickControlData): boolean {
|
||||
if (!this.currentDeviceSn) {
|
||||
console.warn('[ControlWS] 未设置设备SN');
|
||||
return false;
|
||||
}
|
||||
return this.send({
|
||||
type: 'stick_control',
|
||||
deviceSn: this.currentDeviceSn,
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送云台控制指令
|
||||
*/
|
||||
sendGimbalControl(data: GimbalControlData): boolean {
|
||||
if (!this.currentDeviceSn) {
|
||||
console.warn('[ControlWS] 未设置设备SN');
|
||||
return false;
|
||||
}
|
||||
return this.send({
|
||||
type: 'gimbal_control',
|
||||
deviceSn: this.currentDeviceSn,
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否已连接
|
||||
*/
|
||||
isConnected(): boolean {
|
||||
return this.ws !== null && this.ws.readyState === WebSocket.OPEN;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前设备SN
|
||||
*/
|
||||
getCurrentDeviceSn(): string | null {
|
||||
return this.currentDeviceSn;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加消息处理器
|
||||
*/
|
||||
onMessage(handler: MessageHandler): () => void {
|
||||
this.messageHandlers.push(handler);
|
||||
return () => {
|
||||
this.messageHandlers = this.messageHandlers.filter(h => h !== handler);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加状态处理器
|
||||
*/
|
||||
onStatusChange(handler: StatusHandler): () => void {
|
||||
this.statusHandlers.push(handler);
|
||||
return () => {
|
||||
this.statusHandlers = this.statusHandlers.filter(h => h !== handler);
|
||||
};
|
||||
}
|
||||
|
||||
private notifyMessageHandlers(message: ControlResponse): void {
|
||||
this.messageHandlers.forEach(handler => {
|
||||
try {
|
||||
handler(message);
|
||||
} catch (e) {
|
||||
console.error('[ControlWS] 消息处理器错误:', e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private notifyStatusHandlers(connected: boolean): void {
|
||||
this.statusHandlers.forEach(handler => {
|
||||
try {
|
||||
handler(connected);
|
||||
} catch (e) {
|
||||
console.error('[ControlWS] 状态处理器错误:', e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 导出单例
|
||||
export const deviceControlWs = new DeviceControlWebSocket();
|
||||
@@ -47,6 +47,9 @@ export interface ThreeDModelVO {
|
||||
longitude: number;
|
||||
latitude: number;
|
||||
height: number;
|
||||
cesiumHeight?: number; // Cesium Ion地形对应的高度偏移
|
||||
arcgisHeight?: number; // ArcGIS地形对应的高度偏移
|
||||
terrainType?: string; // 高度标定时使用的地形服务: cesium_ion/arcgis/ellipsoid
|
||||
};
|
||||
transform: {
|
||||
scale: number;
|
||||
@@ -84,6 +87,9 @@ export interface ThreeDModelDTO {
|
||||
offsetLongitude?: number;
|
||||
offsetLatitude?: number;
|
||||
offsetHeight?: number;
|
||||
cesiumHeight?: number; // Cesium Ion地形对应的高度偏移
|
||||
arcgisHeight?: number; // ArcGIS地形对应的高度偏移
|
||||
terrainType?: string; // 高度标定时使用的地形服务: cesium_ion/arcgis/ellipsoid
|
||||
scale?: number;
|
||||
rotationX?: number;
|
||||
rotationY?: number;
|
||||
@@ -306,6 +312,9 @@ export function convertToTilesetConfig(model: ThreeDModelVO) {
|
||||
longitude: model.position.longitude || 0,
|
||||
latitude: model.position.latitude || 0,
|
||||
height: model.position.height || 0,
|
||||
cesiumHeight: model.position.cesiumHeight,
|
||||
arcgisHeight: model.position.arcgisHeight,
|
||||
terrainType: model.position.terrainType || 'cesium_ion', // 默认使用 Cesium Ion
|
||||
} : undefined,
|
||||
transform: model.transform ? {
|
||||
scale: model.transform.scale || 1,
|
||||
|
||||
Reference in New Issue
Block a user