feat: 客户端pad

This commit is contained in:
2026-03-11 21:29:55 +08:00
parent 5e66537a87
commit 44975cde97
21 changed files with 2810 additions and 9 deletions
@@ -0,0 +1,71 @@
.container {
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #0a1628 0%, #0d2137 50%, #0a1628 100%);
position: relative;
}
.backEntry {
position: absolute;
top: 16px;
right: 24px;
z-index: 10;
}
.card {
width: 400px;
padding: 48px 40px;
background: rgba(15, 25, 40, 0.9);
border: 1px solid rgba(0, 212, 255, 0.2);
border-radius: 12px;
backdrop-filter: blur(20px);
}
.title {
font-size: 28px;
font-weight: 600;
color: #fff;
text-align: center;
margin-bottom: 8px;
}
.subtitle {
font-size: 14px;
color: rgba(255, 255, 255, 0.5);
text-align: center;
margin-bottom: 32px;
}
.card :global(.ant-input-affix-wrapper) {
background: rgba(255, 255, 255, 0.05);
border-color: rgba(255, 255, 255, 0.15);
color: #fff;
}
.card :global(.ant-input-affix-wrapper:hover),
.card :global(.ant-input-affix-wrapper-focused) {
border-color: #00d4ff;
}
.card :global(.ant-input) {
background: transparent;
color: #fff;
}
.card :global(.ant-input::placeholder) {
color: rgba(255, 255, 255, 0.3);
}
.card :global(.ant-btn-primary) {
height: 48px;
font-size: 16px;
background: linear-gradient(135deg, #00d4ff, #0099cc);
border: none;
}
.card :global(.ant-btn-primary:hover) {
background: linear-gradient(135deg, #33ddff, #00aadd);
}
@@ -0,0 +1,62 @@
import React, { useState } from 'react';
import { Form, Input, Button, message } from 'antd';
import { ApiOutlined, DesktopOutlined } from '@ant-design/icons';
import { history } from 'umi';
import { checkDeviceSn } from '../services/clientApi';
import styles from './index.less';
const ClientLogin: React.FC = () => {
const [loading, setLoading] = useState(false);
const onFinish = async (values: { deviceSn: string }) => {
setLoading(true);
try {
const res = await checkDeviceSn(values.deviceSn.trim());
if (res.resp_code === 0 && res.data) {
sessionStorage.setItem('client_device_sn', res.data.deviceSn);
sessionStorage.setItem('client_device_info', JSON.stringify(res.data));
history.push('/client');
} else {
message.error(res.resp_msg || '设备不存在或未绑定');
}
} catch {
message.error('网络异常,请重试');
}
setLoading(false);
};
return (
<div className={styles.container}>
<div className={styles.backEntry}>
<Button
type="link"
icon={<DesktopOutlined />}
onClick={() => history.push('/user/login')}
style={{ color: 'rgba(255,255,255,0.7)', fontSize: 14 }}
>
管理后台登录
</Button>
</div>
<div className={styles.card}>
<div className={styles.title}>设备客户端</div>
<div className={styles.subtitle}>请输入设备SN号登录</div>
<Form onFinish={onFinish} size="large">
<Form.Item name="deviceSn" rules={[{ required: true, message: '请输入设备SN' }]}>
<Input
prefix={<ApiOutlined style={{ color: 'rgba(255,255,255,0.4)' }} />}
placeholder="请输入设备SN号"
autoComplete="off"
/>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" loading={loading} block>
登录
</Button>
</Form.Item>
</Form>
</div>
</div>
);
};
export default ClientLogin;
@@ -0,0 +1,78 @@
.wrapper {
width: 100%;
height: 100%;
position: relative;
}
.cesiumContainer {
width: 100%;
height: 100%;
}
/* 隐藏 Cesium 水印 */
.cesiumContainer :global(.cesium-viewer-bottom) {
display: none !important;
}
.cesiumContainer :global(.cesium-widget-credits) {
display: none !important;
}
.loadingTip {
position: absolute;
top: 60px;
left: 50%;
transform: translateX(-50%);
color: #fff;
font-size: 14px;
background: linear-gradient(135deg, rgba(0, 100, 150, 0.85) 0%, rgba(0, 60, 100, 0.85) 100%);
padding: 10px 20px;
border-radius: 20px;
z-index: 800;
display: flex;
align-items: center;
gap: 10px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
border: 1px solid rgba(0, 240, 255, 0.3);
}
.loadingSpinner {
width: 16px;
height: 16px;
border: 2px solid rgba(255, 255, 255, 0.3);
border-top-color: #00f0ff;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
.routeActions {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
background: rgba(10, 18, 32, 0.92);
padding: 10px 20px;
border-radius: 8px;
z-index: 800;
display: flex;
align-items: center;
gap: 12px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.4);
border: 1px solid rgba(0, 212, 255, 0.3);
}
.routeActionsTitle {
color: #00d4ff;
font-size: 13px;
font-weight: 500;
max-width: 150px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
@@ -0,0 +1,453 @@
import React, { useEffect, useRef, useState, useCallback, useMemo } from 'react';
import { message, Button, Space } from 'antd';
import { PlayCircleOutlined, EyeOutlined, StopOutlined } from '@ant-design/icons';
import { useTilesetLoader } from '@/pages/map3d/components/MapContainer/3d/hooks/useTilesetLoader';
import { useCesiumRouteLibraryRenderer } from '@/pages/map3d/components/RouteEditor/hooks/useCesiumRouteLibraryRenderer';
import { useRoutePreview } from '../../hooks/useRoutePreview';
import { getClientModels } from '../../services/clientApi';
import { convertToTilesetConfig } from '@/services/threeDModel';
import { getBoatRouteDetail } from '@/services/boatRoute';
import type { BoatRouteListVO, BoatTelemetryData, BoatWaypointDTO } from '@/types/boatRoute';
import styles from './index.less';
let Cesium: any = null;
interface CenterViewProps {
deviceSn: string;
routes: BoatRouteListVO[];
selectedRouteId: string | null;
boatData: BoatTelemetryData | null;
onModelCenter?: (lon: number, lat: number) => void;
}
const CenterView: React.FC<CenterViewProps> = ({ deviceSn, routes, selectedRouteId, boatData, onModelCenter }) => {
const containerRef = useRef<HTMLDivElement>(null);
const viewerRef = useRef<any>(null);
const [viewerReady, setViewerReady] = useState(false);
const [modelLoading, setModelLoading] = useState(false);
const boatEntityRef = useRef<any>(null);
const trackPositionsRef = useRef<any[]>([]);
const terrainLoadedRef = useRef(false);
const { loadTileset, unloadAllTilesets } = useTilesetLoader();
const { isPreviewing, startPreview, stopPreview } = useRoutePreview({ viewerRef });
// 航线渲染数据(含航点)
const [routeRenderItems, setRouteRenderItems] = useState<any[]>([]);
// 缓存已加载的航线详情
const routeDetailCacheRef = useRef<Map<string, BoatWaypointDTO[]>>(new Map());
const { flyToRoute: flyToRouteLibrary } = useCesiumRouteLibraryRenderer({
viewerRef,
routes: routeRenderItems,
});
// 初始化 Cesium(参考鹰眼 CesiumContainer 初始化模式)
useEffect(() => {
let destroyed = false;
const initCesium = async () => {
if (!containerRef.current) return;
if (!Cesium) {
const cesiumModule = (window as any).Cesium || await import('cesium');
Cesium = cesiumModule;
(window as any).Cesium = cesiumModule;
// 设置 Worker 基础路径,避免从 file:/// 加载
const cesiumBaseUrl = process.env.CESIUM_BASE_URL || '/';
Cesium.buildModuleUrl.setBaseUrl(`${cesiumBaseUrl}cesium/`);
// 设置 Ion Token,避免使用内置过期 token 导致 401
const cesiumToken = process.env.REACT_APP_CESIUM_TOKEN;
if (cesiumToken) {
Cesium.Ion.defaultAccessToken = cesiumToken;
}
// 加载 Cesium CSS
if (!document.querySelector('link[href*="cesium"]')) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = `${cesiumBaseUrl}cesium/Widgets/widgets.css`;
document.head.appendChild(link);
}
}
if (destroyed) return;
const viewer = new Cesium.Viewer(containerRef.current, {
terrainProvider: new Cesium.EllipsoidTerrainProvider(),
scene3DOnly: false,
shouldAnimate: true,
animation: false,
timeline: false,
fullscreenButton: false,
geocoder: false,
homeButton: false,
sceneModePicker: false,
baseLayerPicker: false,
navigationHelpButton: false,
infoBox: false,
selectionIndicator: false,
requestRenderMode: true,
maximumRenderTimeChange: Infinity,
});
// 移除默认图层,添加 ArcGIS 影像
viewer.imageryLayers.remove(viewer.imageryLayers.get(0));
viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString('#1e4d7b');
viewer.imageryLayers.addImageryProvider(
new Cesium.UrlTemplateImageryProvider({
url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
minimumLevel: 0,
maximumLevel: 18,
})
);
viewer.scene.globe.enableLighting = false;
viewer.scene.skyAtmosphere.show = true;
viewerRef.current = viewer;
setViewerReady(true);
// 隐藏 Cesium 水印
const creditContainer = viewer.cesiumWidget?.creditContainer;
if (creditContainer) {
creditContainer.style.display = 'none';
}
};
initCesium();
return () => {
destroyed = true;
if (viewerRef.current && !viewerRef.current.isDestroyed()) {
unloadAllTilesets(viewerRef.current);
viewerRef.current.destroy();
viewerRef.current = null;
}
};
}, []);
/**
* 动态切换高程地形(参考鹰眼 switchToElevationTerrain)
* 根据模型配置的地形类型,优先尝试对应地形,失败后降级
*/
const switchToElevationTerrain = useCallback(async (preferredTerrainType?: string): Promise<string> => {
if (!viewerRef.current || !Cesium) return 'ellipsoid';
if (terrainLoadedRef.current && !preferredTerrainType) return 'loaded';
let loadedTerrainType = 'ellipsoid';
if (preferredTerrainType === 'arcgis') {
try {
const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
);
viewerRef.current.terrainProvider = terrainProvider;
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
terrainLoadedRef.current = true;
loadedTerrainType = 'arcgis';
} catch {
try {
const terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
requestVertexNormals: true,
requestWaterMask: true,
});
viewerRef.current.terrainProvider = terrainProvider;
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
terrainLoadedRef.current = true;
loadedTerrainType = 'cesium_ion';
} catch {
loadedTerrainType = 'ellipsoid';
}
}
} else {
try {
const terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
requestVertexNormals: true,
requestWaterMask: true,
});
viewerRef.current.terrainProvider = terrainProvider;
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
terrainLoadedRef.current = true;
loadedTerrainType = 'cesium_ion';
} catch {
try {
const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
);
viewerRef.current.terrainProvider = terrainProvider;
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
terrainLoadedRef.current = true;
loadedTerrainType = 'arcgis';
} catch {
loadedTerrainType = 'ellipsoid';
}
}
}
return loadedTerrainType;
}, []);
// 加载3D模型(参考鹰眼 loadDeviceModels)
useEffect(() => {
if (!viewerReady || !deviceSn) return;
let cancelled = false;
const loadModels = async () => {
setModelLoading(true);
unloadAllTilesets(viewerRef.current);
try {
const res = await getClientModels(deviceSn);
const modelList = res.datas || res.data;
if (cancelled || res.resp_code !== 0 || !modelList?.length) {
setModelLoading(false);
return;
}
const configs = modelList.map((model: any) => convertToTilesetConfig(model));
// 并行:高程地形加载 + 模型准备
const firstTerrainType = configs[0]?.position?.terrainType;
const terrainPromise = switchToElevationTerrain(firstTerrainType);
const autoLoadCount = configs.length <= 2 ? configs.length : 1;
const configsToLoad = configs.slice(0, autoLoadCount);
// 等待高程加载完成
const loadedTerrainType = await terrainPromise;
if (cancelled) { setModelLoading(false); return; }
let firstTileset: any = null;
for (const config of configsToLoad) {
if (!config.url) continue;
const tileset = await loadTileset(config, viewerRef.current, Cesium, loadedTerrainType);
if (tileset && !firstTileset) {
firstTileset = tileset;
}
}
// 模型加载完成后飞到模型位置
if (firstTileset && viewerRef.current && !viewerRef.current.isDestroyed?.()) {
try {
const radius = Number(firstTileset?.boundingSphere?.radius);
const range = Number.isFinite(radius) && radius > 0 ? Math.max(50, radius * 0.8) : 100;
viewerRef.current.flyTo(firstTileset, {
duration: 1.5,
offset: new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(0),
Cesium.Math.toRadians(-50),
range
),
});
// 通知父组件模型中心位置(用于模拟数据定位)
if (onModelCenter && firstTileset.boundingSphere?.center) {
const cartographic = Cesium.Cartographic.fromCartesian(firstTileset.boundingSphere.center);
onModelCenter(
Cesium.Math.toDegrees(cartographic.longitude),
Cesium.Math.toDegrees(cartographic.latitude),
);
}
} catch (e) {
console.warn('飞到模型位置失败:', e);
}
}
} catch (error) {
console.error('加载设备模型失败:', error);
}
setModelLoading(false);
};
loadModels();
return () => { cancelled = true; };
}, [viewerReady, deviceSn]);
// 选中航线时加载航点详情并渲染
useEffect(() => {
if (!viewerReady || !selectedRouteId) {
setRouteRenderItems([]);
return;
}
const loadAndRender = async () => {
let waypoints = routeDetailCacheRef.current.get(selectedRouteId);
if (!waypoints) {
try {
const res = await getBoatRouteDetail(selectedRouteId);
if (res.resp_code === 0 && res.data?.waypoints) {
waypoints = res.data.waypoints.map((wp) => ({
longitude: wp.longitude,
latitude: wp.latitude,
speed: wp.speed,
stayDuration: wp.stayDuration,
}));
routeDetailCacheRef.current.set(selectedRouteId, waypoints);
}
} catch {
message.error('线路详情加载失败');
return;
}
}
if (waypoints && waypoints.length > 0) {
setRouteRenderItems([{
routeId: selectedRouteId,
routeName: routes.find((r) => r.routeId === selectedRouteId)?.routeName || '',
waypoints,
visible: true,
highlighted: true,
}]);
// 使用 useCesiumRouteLibraryRenderer 的 flyToRoute(基于 Rectangle,视角更可靠)
// 延迟一帧让 routeRenderItems 生效,entity 创建后再飞
setTimeout(() => flyToRouteLibrary(selectedRouteId), 100);
}
};
loadAndRender();
}, [viewerReady, selectedRouteId]);
// 实时船位渲染
useEffect(() => {
if (!viewerReady || !Cesium || !boatData?.longitude || !boatData?.latitude) return;
const viewer = viewerRef.current;
if (!viewer || viewer.isDestroyed()) return;
const position = Cesium.Cartesian3.fromDegrees(boatData.longitude, boatData.latitude, 2);
trackPositionsRef.current.push(position);
// 限制轨迹点数
if (trackPositionsRef.current.length > 500) {
trackPositionsRef.current = trackPositionsRef.current.slice(-400);
}
// 更新/创建船位 Entity
if (!boatEntityRef.current) {
boatEntityRef.current = viewer.entities.add({
position,
point: {
pixelSize: 12,
color: Cesium.Color.fromCssColorString('#00d4ff'),
outlineColor: Cesium.Color.WHITE,
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
label: {
text: '当前位置',
font: '12px sans-serif',
fillColor: Cesium.Color.WHITE,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth: 2,
outlineColor: Cesium.Color.BLACK,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -16),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
});
} else {
boatEntityRef.current.position = position;
}
// 轨迹线
if (trackPositionsRef.current.length >= 2) {
const trackId = 'client-boat-track';
let trackEntity = viewer.entities.getById(trackId);
if (!trackEntity) {
viewer.entities.add({
id: trackId,
polyline: {
positions: new Cesium.CallbackProperty(() => trackPositionsRef.current, false),
width: 3,
material: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.3,
color: Cesium.Color.LIME,
}),
clampToGround: true,
},
});
}
}
viewer.scene.requestRender();
}, [viewerReady, boatData]);
// 预览选中航线
const handlePreviewRoute = useCallback(async () => {
if (!selectedRouteId) return;
const waypoints = routeDetailCacheRef.current.get(selectedRouteId);
if (!waypoints || waypoints.length < 2) {
message.warning('航点数据不足,无法预览');
return;
}
await startPreview(waypoints, 2);
}, [selectedRouteId, startPreview]);
// 执行航线(暂未实现)
const handleExecuteRoute = useCallback(() => {
message.info('航行功能开发中...');
}, []);
// 获取选中航线名称
const selectedRouteName = useMemo(() => {
if (!selectedRouteId) return '';
return routes.find((r) => r.routeId === selectedRouteId)?.routeName || '';
}, [selectedRouteId, routes]);
return (
<div className={styles.wrapper}>
<div ref={containerRef} className={styles.cesiumContainer} />
{/* 模型加载提示 */}
{modelLoading && (
<div className={styles.loadingTip}>
<div className={styles.loadingSpinner} />
<span>正在加载3D模型...</span>
</div>
)}
{/* 选中线路时显示操作按钮 */}
{selectedRouteId && !isPreviewing && (
<div className={styles.routeActions}>
<div className={styles.routeActionsTitle}>{selectedRouteName}</div>
<Space>
<Button
type="primary"
icon={<EyeOutlined />}
onClick={handlePreviewRoute}
size="small"
>
预览线路
</Button>
<Button
icon={<PlayCircleOutlined />}
onClick={handleExecuteRoute}
size="small"
style={{ borderColor: '#00ff88', color: '#00ff88' }}
>
开始航行
</Button>
</Space>
</div>
)}
{/* 预览中显示停止按钮 */}
{isPreviewing && (
<div className={styles.routeActions}>
<Button
danger
type="primary"
icon={<StopOutlined />}
onClick={stopPreview}
size="small"
>
停止预览 (ESC)
</Button>
</div>
)}
</div>
);
};
export default CenterView;
@@ -0,0 +1,167 @@
.panel {
height: 100%;
display: flex;
flex-direction: column;
}
/* ========== 头部 ========== */
.header {
padding: 18px 16px;
border-bottom: 1px solid rgba(0, 212, 255, 0.12);
display: flex;
align-items: center;
gap: 10px;
}
.headerIcon {
width: 36px;
height: 36px;
border-radius: 10px;
background: linear-gradient(135deg, rgba(0, 112, 212, 0.3), rgba(0, 180, 255, 0.15));
display: flex;
align-items: center;
justify-content: center;
color: #00d4ff;
font-size: 16px;
flex-shrink: 0;
}
.headerTitle {
font-size: 15px;
font-weight: 600;
color: #fff;
line-height: 1.3;
}
.headerSub {
font-size: 11px;
color: rgba(255, 255, 255, 0.35);
}
.count {
margin-left: auto;
background: rgba(0, 112, 212, 0.2);
color: #00b4ff;
font-size: 12px;
font-weight: 600;
padding: 2px 10px;
border-radius: 10px;
flex-shrink: 0;
}
/* ========== 列表 ========== */
.list {
flex: 1;
overflow-y: auto;
padding: 10px;
}
.center {
display: flex;
align-items: center;
justify-content: center;
height: 200px;
}
/* ========== 线路卡片 ========== */
.routeCard {
padding: 14px;
margin-bottom: 8px;
border-radius: 10px;
cursor: pointer;
transition: all 0.25s;
border: 1px solid rgba(255, 255, 255, 0.06);
background: rgba(255, 255, 255, 0.03);
&:hover {
background: rgba(0, 150, 220, 0.08);
border-color: rgba(0, 180, 255, 0.2);
}
}
.routeCardActive {
background: rgba(0, 112, 212, 0.12);
border-color: rgba(0, 150, 255, 0.4);
box-shadow: 0 0 16px rgba(0, 112, 212, 0.12);
.routeName {
color: #00d4ff;
}
}
.routeName {
font-size: 15px;
font-weight: 600;
color: rgba(255, 255, 255, 0.92);
margin-bottom: 8px;
transition: color 0.2s;
}
/* ========== 标签行 ========== */
.tagRow {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 10px;
}
.tag {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 11px;
color: rgba(255, 255, 255, 0.5);
background: rgba(255, 255, 255, 0.06);
padding: 2px 8px;
border-radius: 4px;
}
.tagIcon {
font-size: 10px;
color: rgba(0, 180, 255, 0.6);
}
/* ========== 航点路径 ========== */
.waypointPath {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
padding: 10px 0 4px;
border-top: 1px dashed rgba(255, 255, 255, 0.08);
}
.waypointDot {
width: 6px;
height: 6px;
border-radius: 50%;
background: rgba(0, 180, 255, 0.6);
flex-shrink: 0;
}
.waypointName {
font-size: 12px;
color: rgba(255, 255, 255, 0.7);
}
.waypointArrow {
font-size: 11px;
color: rgba(0, 180, 255, 0.5);
margin: 0 1px;
}
/* ========== 开始航行按钮 ========== */
.startBtn {
margin-top: 12px;
height: 36px;
border-radius: 8px;
font-weight: 600;
font-size: 14px;
letter-spacing: 1px;
background: linear-gradient(135deg, #0070d4, #0096ff);
border: none;
&:hover {
background: linear-gradient(135deg, #0080e8, #00a8ff);
}
}
@@ -0,0 +1,124 @@
import React, { useMemo } from 'react';
import { Spin, Empty } from 'antd';
import {
ClockCircleOutlined,
EnvironmentOutlined,
SendOutlined,
NodeIndexOutlined,
} from '@ant-design/icons';
import type { BoatRouteListVO, BoatWaypointVO } from '@/types/boatRoute';
import styles from './index.less';
interface LeftPanelProps {
routes: BoatRouteListVO[];
routeWaypointsMap: Record<string, BoatWaypointVO[]>;
loading: boolean;
selectedRouteId: string | null;
onSelectRoute: (routeId: string | null) => void;
}
/** 格式化时间(秒 → "XX分钟") */
const formatDuration = (seconds?: number) => {
if (!seconds || seconds <= 0) return null;
const min = Math.round(seconds / 60);
return min > 0 ? `${min}分钟` : '<1分钟';
};
/** 格式化距离 */
const formatDistance = (meters?: number) => {
if (!meters || meters <= 0) return null;
return meters >= 1000 ? `${(meters / 1000).toFixed(1)}km` : `${Math.round(meters)}m`;
};
const LeftPanel: React.FC<LeftPanelProps> = ({
routes,
routeWaypointsMap,
loading,
selectedRouteId,
onSelectRoute,
}) => {
return (
<div className={styles.panel}>
<div className={styles.header}>
<div className={styles.headerIcon}>
<SendOutlined />
</div>
<div>
<div className={styles.headerTitle}>游览线路</div>
<div className={styles.headerSub}>选择线路开始游览</div>
</div>
<span className={styles.count}>{routes.length}</span>
</div>
<div className={styles.list}>
{loading ? (
<div className={styles.center}><Spin /></div>
) : routes.length === 0 ? (
<div className={styles.center}>
<Empty description="暂无游览线路" image={Empty.PRESENTED_IMAGE_SIMPLE} />
</div>
) : (
routes.map((route) => {
const isSelected = selectedRouteId === route.routeId;
const waypoints = routeWaypointsMap[route.routeId] || [];
const duration = formatDuration(route.totalDuration);
const distance = formatDistance(route.totalDistance);
// 构建航点路径名称列表
const waypointNames = waypoints
.filter((wp) => wp.pointName)
.map((wp) => wp.pointName);
return (
<div
key={route.routeId}
className={`${styles.routeCard} ${isSelected ? styles.routeCardActive : ''}`}
onClick={() => onSelectRoute(isSelected ? null : route.routeId)}
>
{/* 线路名称 */}
<div className={styles.routeName}>{route.routeName}</div>
{/* 时长 + 距离 标签 */}
<div className={styles.tagRow}>
{duration && (
<span className={styles.tag}>
<ClockCircleOutlined className={styles.tagIcon} />
{duration}
</span>
)}
{distance && (
<span className={styles.tag}>
<EnvironmentOutlined className={styles.tagIcon} />
{distance}
</span>
)}
<span className={styles.tag}>
<NodeIndexOutlined className={styles.tagIcon} />
{route.waypointCount || waypoints.length}个景点
</span>
</div>
{/* 航点路径 */}
{waypointNames.length > 0 && (
<div className={styles.waypointPath}>
{waypointNames.map((name, idx) => (
<React.Fragment key={idx}>
<span className={styles.waypointDot} />
<span className={styles.waypointName}>{name}</span>
{idx < waypointNames.length - 1 && (
<span className={styles.waypointArrow}>→</span>
)}
</React.Fragment>
))}
</div>
)}
</div>
);
})
)}
</div>
</div>
);
};
export default LeftPanel;
@@ -0,0 +1,223 @@
.panel {
height: 100%;
padding: 0;
display: flex;
flex-direction: column;
overflow-y: auto;
}
.section {
padding: 16px;
border-bottom: 1px solid rgba(0, 212, 255, 0.1);
}
.sectionTitle {
font-size: 14px;
font-weight: 600;
color: rgba(255, 255, 255, 0.9);
margin-bottom: 16px;
}
/* ========== 罗盘 ========== */
.compassWrapper {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 12px;
}
.compass {
width: 180px;
height: 180px;
position: relative;
}
.compassSvg {
width: 100%;
height: 100%;
}
.headingText {
display: flex;
align-items: baseline;
gap: 6px;
margin-top: 4px;
}
.headingLabel {
font-size: 12px;
color: rgba(255, 255, 255, 0.5);
}
.headingValue {
font-size: 22px;
font-weight: bold;
color: #0070d4;
}
/* ========== 左转/右转 ========== */
.turnRow {
display: flex;
justify-content: center;
gap: 16px;
margin-bottom: 16px;
}
.turnBtn {
width: 48px;
height: 36px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 6px;
border: 1px solid rgba(0, 150, 220, 0.4);
background: rgba(0, 60, 100, 0.35);
color: rgba(255, 255, 255, 0.8);
font-size: 16px;
cursor: pointer;
transition: all 0.15s;
padding: 0;
&:hover {
background: rgba(0, 100, 160, 0.5);
border-color: rgba(0, 180, 255, 0.6);
color: #fff;
}
&:active {
background: rgba(0, 130, 200, 0.7);
border-color: #00b4ff;
transform: scale(0.95);
}
}
/* ========== 速度滑块 ========== */
.speedRow {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 16px;
padding: 0 4px;
}
.speedLabel {
font-size: 12px;
color: rgba(255, 255, 255, 0.5);
flex-shrink: 0;
}
.speedSlider {
flex: 1;
:global(.ant-slider-rail) {
background: rgba(255, 255, 255, 0.1);
}
:global(.ant-slider-track) {
background: #0070d4;
}
:global(.ant-slider-handle)::after {
box-shadow: 0 0 6px rgba(0, 112, 212, 0.6);
}
}
.speedValue {
font-size: 13px;
font-weight: 600;
color: #0070d4;
flex-shrink: 0;
min-width: 60px;
text-align: right;
}
/* ========== 紧急停靠 ========== */
.emergencyBtn {
height: 42px;
border-radius: 6px;
border: none;
background: #d4380d;
color: #fff;
font-size: 15px;
font-weight: 600;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
cursor: pointer;
transition: all 0.2s;
letter-spacing: 2px;
&:hover {
background: #e84820;
}
&:active {
background: #cf1322;
transform: scale(0.98);
}
}
/* ========== 实时数据卡片 ========== */
.dataCard {
border-radius: 8px;
padding: 12px;
margin-bottom: 10px;
&:last-child {
margin-bottom: 0;
}
}
/* 三级透明层次 */
.dataCardLevel1 {
background: rgba(0, 112, 212, 0.12);
border: 1px solid rgba(0, 112, 212, 0.25);
}
.dataCardLevel2 {
background: rgba(0, 180, 150, 0.08);
border: 1px solid rgba(0, 180, 150, 0.2);
}
.dataCardLevel3 {
background: rgba(0, 212, 255, 0.05);
border: 1px solid rgba(0, 212, 255, 0.15);
}
.dataCardHeader {
font-size: 12px;
font-weight: 600;
color: #0070d4;
margin-bottom: 8px;
padding-bottom: 6px;
border-bottom: 1px solid rgba(0, 112, 212, 0.15);
}
.dataCardHeaderGreen {
color: #00b496;
border-bottom-color: rgba(0, 180, 150, 0.15);
}
.dataCardHeaderCyan {
color: #00a0cc;
border-bottom-color: rgba(0, 212, 255, 0.12);
}
.dataRow {
display: flex;
justify-content: space-between;
align-items: center;
padding: 4px 0;
}
.dataLabel {
font-size: 12px;
color: rgba(255, 255, 255, 0.45);
}
.dataValue {
font-size: 13px;
color: rgba(255, 255, 255, 0.9);
font-weight: 500;
}
@@ -0,0 +1,229 @@
import React, { useMemo, useCallback, useRef, useState } from 'react';
import { Button, Slider, message } from 'antd';
import {
WarningOutlined,
ArrowLeftOutlined,
ArrowRightOutlined,
} from '@ant-design/icons';
import type { BoatTelemetryData } from '@/types/boatRoute';
import { sendBoatCommand } from '../../services/clientApi';
import styles from './index.less';
interface RightPanelProps {
deviceInfo: { deviceSn: string; deviceName: string; deviceType: number };
boatData: BoatTelemetryData | null;
sseConnected: boolean;
}
const RightPanel: React.FC<RightPanelProps> = ({ deviceInfo, boatData, sseConnected }) => {
const heading = useMemo(() => boatData?.heading ?? 0, [boatData?.heading]);
const speed = useMemo(() => boatData?.speed ?? 0, [boatData?.speed]);
const battery = useMemo(() => boatData?.battery ?? 0, [boatData?.battery]);
const [targetSpeed, setTargetSpeed] = useState(5);
const activeCommandRef = useRef<string | null>(null);
const handleCommandPress = useCallback((command: string) => {
activeCommandRef.current = command;
sendBoatCommand(deviceInfo.deviceSn, command, 'press').catch(() => {
message.error('指令发送失败');
});
}, [deviceInfo.deviceSn]);
const handleCommandRelease = useCallback((command: string) => {
if (activeCommandRef.current === command) {
activeCommandRef.current = null;
}
sendBoatCommand(deviceInfo.deviceSn, command, 'release').catch(() => {});
}, [deviceInfo.deviceSn]);
const handleEmergencyStop = useCallback(() => {
activeCommandRef.current = null;
sendBoatCommand(deviceInfo.deviceSn, 'stop', 'press').catch(() => {
message.error('紧急停靠指令发送失败');
});
}, [deviceInfo.deviceSn]);
return (
<div className={styles.panel}>
{/* 船体控制 */}
<div className={styles.section}>
<div className={styles.sectionTitle}>船体控制</div>
{/* 罗盘仪表盘 */}
<div className={styles.compassWrapper}>
<div className={styles.compass}>
{/* 外圈刻度 */}
<svg className={styles.compassSvg} viewBox="0 0 200 200">
{/* 外圆 */}
<circle cx="100" cy="100" r="90" fill="none" stroke="rgba(0,150,220,0.3)" strokeWidth="2" />
<circle cx="100" cy="100" r="88" fill="none" stroke="rgba(0,150,220,0.08)" strokeWidth="4" />
{/* 刻度线 */}
{Array.from({ length: 72 }).map((_, i) => {
const angle = i * 5;
const isMajor = angle % 30 === 0;
const r1 = isMajor ? 78 : 83;
const r2 = 88;
const rad = (angle - 90) * Math.PI / 180;
return (
<line
key={i}
x1={100 + r1 * Math.cos(rad)}
y1={100 + r1 * Math.sin(rad)}
x2={100 + r2 * Math.cos(rad)}
y2={100 + r2 * Math.sin(rad)}
stroke={isMajor ? 'rgba(0,180,255,0.6)' : 'rgba(0,180,255,0.2)'}
strokeWidth={isMajor ? 2 : 1}
/>
);
})}
{/* N/S/E/W 标记 */}
<text x="100" y="26" textAnchor="middle" fill="#00d4ff" fontSize="14" fontWeight="bold">N</text>
<text x="100" y="182" textAnchor="middle" fill="rgba(255,255,255,0.5)" fontSize="12">S</text>
<text x="178" y="104" textAnchor="middle" fill="rgba(255,255,255,0.5)" fontSize="12">E</text>
<text x="22" y="104" textAnchor="middle" fill="rgba(255,255,255,0.5)" fontSize="12">W</text>
{/* 方向指针(船头) */}
<g transform={`rotate(${heading}, 100, 100)`}>
<polygon
points="100,32 93,70 100,62 107,70"
fill="#0070d4"
stroke="#00a0ff"
strokeWidth="1"
/>
<line x1="100" y1="62" x2="100" y2="100" stroke="rgba(0,112,212,0.5)" strokeWidth="2" />
</g>
{/* 中心圆点 */}
<circle cx="100" cy="100" r="5" fill="#0a1628" stroke="#00a0ff" strokeWidth="2" />
<circle cx="100" cy="100" r="2" fill="#00d4ff" />
</svg>
</div>
<div className={styles.headingText}>
<span className={styles.headingLabel}>航向</span>
<span className={styles.headingValue}>{heading.toFixed(0)}°</span>
</div>
</div>
{/* 左转 / 右转按钮 */}
<div className={styles.turnRow}>
<Button
className={styles.turnBtn}
onMouseDown={() => handleCommandPress('left')}
onMouseUp={() => handleCommandRelease('left')}
onMouseLeave={() => handleCommandRelease('left')}
onTouchStart={() => handleCommandPress('left')}
onTouchEnd={() => handleCommandRelease('left')}
icon={<ArrowLeftOutlined />}
/>
<Button
className={styles.turnBtn}
onMouseDown={() => handleCommandPress('right')}
onMouseUp={() => handleCommandRelease('right')}
onMouseLeave={() => handleCommandRelease('right')}
onTouchStart={() => handleCommandPress('right')}
onTouchEnd={() => handleCommandRelease('right')}
icon={<ArrowRightOutlined />}
/>
</div>
{/* 速度滑块 */}
<div className={styles.speedRow}>
<span className={styles.speedLabel}>速度</span>
<div className={styles.speedSlider}>
<Slider
min={0}
max={15}
step={0.5}
value={targetSpeed}
onChange={setTargetSpeed}
tooltip={{ formatter: (v) => `${v} km/h` }}
/>
</div>
<span className={styles.speedValue}>{targetSpeed} km/h</span>
</div>
{/* 紧急停靠 */}
<Button
className={styles.emergencyBtn}
onClick={handleEmergencyStop}
block
>
<WarningOutlined />
<span>紧急停靠</span>
</Button>
</div>
{/* 实时数据 */}
<div className={styles.section}>
<div className={styles.sectionTitle}>实时数据</div>
{/* 船舶状态 */}
<div className={`${styles.dataCard} ${styles.dataCardLevel1}`}>
<div className={styles.dataCardHeader}>船舶状态</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>速度</span>
<span className={styles.dataValue}>{speed.toFixed(1)} km/h</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>方向</span>
<span className={styles.dataValue}>{heading.toFixed(0)}°</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>电量</span>
<span className={styles.dataValue} style={{ color: battery < 20 ? '#ff4d4f' : '#00ff88' }}>
{battery.toFixed(0)}%
</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>模式</span>
<span className={styles.dataValue}>{boatData?.taskId ? '自动' : '手动'}</span>
</div>
</div>
{/* 环境数据 */}
<div className={`${styles.dataCard} ${styles.dataCardLevel2}`}>
<div className={`${styles.dataCardHeader} ${styles.dataCardHeaderGreen}`}>环境数据</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>水质</span>
<span className={styles.dataValue} style={{ color: '#00d4aa' }}>优</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>风速</span>
<span className={styles.dataValue}>{(1.5 + (boatData?.speed ?? 0) * 0.3).toFixed(1)} m/s</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>温度</span>
<span className={styles.dataValue}>{(18 + Math.round((boatData?.heading ?? 0) % 5)).toFixed(0)}°C</span>
</div>
</div>
{/* 设备状态 */}
<div className={`${styles.dataCard} ${styles.dataCardLevel3}`}>
<div className={`${styles.dataCardHeader} ${styles.dataCardHeaderCyan}`}>设备状态</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>传感器</span>
<span className={styles.dataValue} style={{ color: '#00ff88' }}>正常</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>连接状态</span>
<span className={styles.dataValue} style={{ color: sseConnected ? '#00ff88' : '#ff4d4f' }}>
{sseConnected ? '已连接' : '未连接'}
</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>设备SN</span>
<span className={styles.dataValue}>{deviceInfo.deviceSn}</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>GPS</span>
<span className={styles.dataValue}>
{boatData?.longitude != null
? `${boatData.longitude.toFixed(4)}, ${boatData.latitude?.toFixed(4)}`
: '--'}
</span>
</div>
</div>
</div>
</div>
);
};
export default RightPanel;
@@ -0,0 +1,228 @@
/**
* 客户端SSE Hook - 无人船遥测数据
* 基于现有 useBoatSSE 模式,连接客户端专用SSE端点(无需认证)
*/
import { useState, useRef, useEffect, useCallback } from 'react';
import type { BoatTelemetryData } from '@/types/boatRoute';
const IDLE_TIMEOUT_MS = 30 * 60 * 1000;
export interface UseClientSSEReturn {
boatData: BoatTelemetryData | null;
sseConnected: boolean;
loading: boolean;
connectSSE: (deviceSn: string) => Promise<void>;
disconnectSSE: (deviceSn?: string) => Promise<void>;
}
export const useClientSSE = (): UseClientSSEReturn => {
const [boatData, setBoatData] = useState<BoatTelemetryData | null>(null);
const [sseConnected, setSSEConnected] = useState(false);
const [loading, setLoading] = useState(false);
const abortControllerRef = useRef<AbortController | null>(null);
const currentDeviceSnRef = useRef<string>('');
const clientSessionIdRef = useRef<string>(
`client_pad_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
);
const reconnectTimerRef = useRef<NodeJS.Timeout | null>(null);
const reconnectAttemptsRef = useRef<number>(0);
const maxReconnectAttempts = 10;
const shouldReconnectRef = useRef<boolean>(true);
const idleTimerRef = useRef<NodeJS.Timeout | null>(null);
const performDisconnect = (deviceSn: string, sessionId: string) => {
if (!deviceSn) return;
fetch(`/api-device/client/sse/telemetry/${deviceSn}`, {
method: 'DELETE',
headers: { 'X-Client-Session-Id': sessionId },
keepalive: true,
}).catch(() => {});
};
const performBeaconDisconnect = (deviceSn: string, sessionId: string) => {
if (!deviceSn) return;
const url = `/api-device/client/sse/telemetry/${deviceSn}/disconnect`;
if (navigator.sendBeacon) {
const blob = new Blob([JSON.stringify({ sessionId })], { type: 'application/json' });
navigator.sendBeacon(url, blob);
}
};
const disconnectSSE = useCallback(async (deviceSn?: string) => {
const snToDisconnect = deviceSn || currentDeviceSnRef.current;
shouldReconnectRef.current = false;
if (reconnectTimerRef.current) {
clearTimeout(reconnectTimerRef.current);
reconnectTimerRef.current = null;
}
if (idleTimerRef.current) {
clearTimeout(idleTimerRef.current);
idleTimerRef.current = null;
}
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
if (snToDisconnect) {
performDisconnect(snToDisconnect, clientSessionIdRef.current);
}
setSSEConnected(false);
setBoatData(null);
currentDeviceSnRef.current = '';
}, []);
const scheduleReconnect = useCallback((deviceSn: string) => {
if (reconnectAttemptsRef.current >= maxReconnectAttempts) {
console.log('[ClientSSE] 达到最大重连次数');
setSSEConnected(false);
return;
}
const delay = Math.min(2000 * Math.pow(2, reconnectAttemptsRef.current), 60000);
reconnectAttemptsRef.current += 1;
reconnectTimerRef.current = setTimeout(() => {
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
connectSSE(deviceSn);
}
}, delay);
}, []);
const connectSSE = useCallback(async (deviceSn: string) => {
if (!deviceSn) return;
// 断开旧连接
if (currentDeviceSnRef.current && currentDeviceSnRef.current !== deviceSn) {
await disconnectSSE(currentDeviceSnRef.current);
}
currentDeviceSnRef.current = deviceSn;
shouldReconnectRef.current = true;
setLoading(true);
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
const abortController = new AbortController();
abortControllerRef.current = abortController;
try {
const url = `/api-device/client/sse/telemetry/${deviceSn}`;
const response = await fetch(url, {
method: 'GET',
headers: {
'Accept': 'text/event-stream',
'X-Client-Session-Id': clientSessionIdRef.current,
},
signal: abortController.signal,
});
if (!response.ok) {
throw new Error(`SSE连接失败: ${response.status}`);
}
setSSEConnected(true);
setLoading(false);
reconnectAttemptsRef.current = 0;
const reader = response.body?.getReader();
if (!reader) throw new Error('无法获取响应流');
const decoder = new TextDecoder();
let buffer = '';
const handleSSEEvent = (eventName: string, data: string) => {
if (eventName === 'boat-telemetry') {
try {
const parsed = JSON.parse(data) as BoatTelemetryData;
setBoatData(parsed);
} catch (e) {
console.warn('[ClientSSE] 解析遥测数据失败:', e);
}
}
};
const readStream = async () => {
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
setSSEConnected(false);
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
scheduleReconnect(deviceSn);
}
break;
}
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
let currentEvent = 'message';
let currentData = '';
for (const line of lines) {
if (line.startsWith('event:')) {
currentEvent = line.substring(6).trim();
} else if (line.startsWith('data:')) {
currentData = line.substring(5).trim();
} else if (line === '') {
if (currentData) {
handleSSEEvent(currentEvent, currentData);
}
currentEvent = 'message';
currentData = '';
}
}
}
} catch (error: any) {
if (error?.name === 'AbortError') return;
console.error('[ClientSSE] 读取流错误:', error);
setSSEConnected(false);
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
scheduleReconnect(deviceSn);
}
}
};
readStream();
} catch (error: any) {
if (error?.name === 'AbortError') return;
console.error('[ClientSSE] 连接失败:', error);
setSSEConnected(false);
setLoading(false);
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
scheduleReconnect(deviceSn);
}
}
}, [disconnectSSE, scheduleReconnect]);
// 页面关闭时断开
useEffect(() => {
const handleBeforeUnload = () => {
if (currentDeviceSnRef.current) {
performBeaconDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current);
}
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => window.removeEventListener('beforeunload', handleBeforeUnload);
}, []);
// 组件卸载清理
useEffect(() => {
return () => {
if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
shouldReconnectRef.current = false;
if (currentDeviceSnRef.current) {
performDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current);
}
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
};
}, []);
return { boatData, sseConnected, loading, connectSSE, disconnectSSE };
};
@@ -0,0 +1,487 @@
/**
* 航线第一视角预览 Hook
* 从鹰眼 RouteEditor 中提取的预览动画逻辑,用于客户端页面航线预览
*/
import { useState, useRef, useCallback, useEffect } from 'react';
import { message } from 'antd';
import type { BoatWaypointDTO } from '@/types/boatRoute';
export interface UseRoutePreviewOptions {
viewerRef: React.RefObject<any>;
}
export interface UseRoutePreviewReturn {
isPreviewing: boolean;
startPreview: (waypoints: BoatWaypointDTO[], speed?: number) => Promise<void>;
stopPreview: () => void;
}
export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoutePreviewReturn {
const [isPreviewing, setIsPreviewing] = useState(false);
const previewAnimationRef = useRef<number | null>(null);
const savedCameraStateRef = useRef<any>(null);
const previewBoatPartsRef = useRef<{ hull?: any; cabin?: any; mast?: any; marker?: any } | null>(null);
const getCesium = useCallback(() => (window as any).Cesium, []);
// 计算两点间航向角
const calculateHeading = useCallback((from: { longitude: number; latitude: number }, to: { longitude: number; latitude: number }) => {
const dLon = (to.longitude - from.longitude) * Math.PI / 180;
const lat1 = from.latitude * Math.PI / 180;
const lat2 = to.latitude * Math.PI / 180;
const y = Math.sin(dLon) * Math.cos(lat2);
const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
const bearing = Math.atan2(y, x) * 180 / Math.PI;
return (bearing + 360) % 360;
}, []);
// 停止预览
const stopPreview = useCallback(() => {
setIsPreviewing(false);
if (previewAnimationRef.current) {
cancelAnimationFrame(previewAnimationRef.current);
previewAnimationRef.current = null;
}
if ((previewAnimationRef as any).escHandler) {
window.removeEventListener('keydown', (previewAnimationRef as any).escHandler);
(previewAnimationRef as any).escHandler = null;
}
// 清理船只实体
if (previewBoatPartsRef.current) {
try {
const viewer = viewerRef?.current;
if (viewer && !viewer.isDestroyed?.()) {
const { hull, cabin, mast, marker } = previewBoatPartsRef.current;
if (hull) viewer.entities.remove(hull);
if (cabin) viewer.entities.remove(cabin);
if (mast) viewer.entities.remove(mast);
if (marker) viewer.entities.remove(marker);
}
} catch { /* ignore */ } finally {
previewBoatPartsRef.current = null;
}
}
// 恢复相机
if (savedCameraStateRef.current && viewerRef?.current) {
const viewer = viewerRef.current;
const Cesium = getCesium();
try { if (Cesium?.Matrix4) viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY); } catch { /* ignore */ }
viewer.camera.setView({
destination: savedCameraStateRef.current.position,
orientation: {
heading: savedCameraStateRef.current.heading,
pitch: savedCameraStateRef.current.pitch,
roll: savedCameraStateRef.current.roll,
},
});
savedCameraStateRef.current = null;
}
}, [viewerRef, getCesium]);
// 构建预览折线(密集化 + 贴模型表面)
const buildPreviewPolyline = useCallback(async (points: BoatWaypointDTO[]) => {
const viewer = viewerRef?.current;
const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.()) return [];
if (!Array.isArray(points) || points.length < 2) return [];
const applyOffset = (cartesian: any) => {
try {
const carto = Cesium.Cartographic.fromCartesian(cartesian);
carto.height = (Number(carto.height) || 0) + 0.05;
return Cesium.Cartesian3.fromRadians(carto.longitude, carto.latitude, carto.height);
} catch { return cartesian; }
};
// 密集化航点
const cartos: any[] = [];
let total = 0;
const maxTotal = 500;
for (let i = 0; i < points.length - 1; i++) {
const a = points[i], b = points[i + 1];
const ca = Cesium.Cartographic.fromDegrees(a.longitude, a.latitude, 300);
const cb = Cesium.Cartographic.fromDegrees(b.longitude, b.latitude, 300);
const geodesic = new Cesium.EllipsoidGeodesic(ca, cb);
const dist = Number(geodesic.surfaceDistance) || 0;
const segments = Math.max(2, Math.min(60, Math.ceil(dist / 10)));
for (let s = 0; s <= segments; s++) {
if (i > 0 && s === 0) continue;
if (total >= maxTotal) break;
const c = geodesic.interpolateUsingFraction(segments === 0 ? 0 : s / segments);
c.height = 300;
cartos.push(c);
total++;
}
if (total >= maxTotal) break;
}
if (cartos.length < 2) {
return points.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)).map(applyOffset);
}
const above = cartos.map((c: any) => Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, c.height || 300));
const clampFn = viewer.scene?.clampToHeightMostDetailed;
if (typeof clampFn !== 'function') return above.map(applyOffset);
try {
const clamped = await clampFn.call(viewer.scene, above);
const merged = (clamped || []).map((p: any, idx: number) => p || above[idx]);
const okCount = (clamped || []).filter(Boolean).length;
if (okCount < 2) return above.map(applyOffset);
return merged.map(applyOffset);
} catch {
return above.map(applyOffset);
}
}, [viewerRef, getCesium]);
// 开始预览
const startPreview = useCallback(async (waypoints: BoatWaypointDTO[], speed: number = 2) => {
const viewer = viewerRef?.current;
const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
if (!waypoints || waypoints.length < 2) {
message.warning('至少需要2个航点才能预览');
return;
}
if (isPreviewing) stopPreview();
const polylinePositions = await buildPreviewPolyline(waypoints);
if (!Array.isArray(polylinePositions) || polylinePositions.length < 2) {
message.warning('模型瓦片加载中,请稍后再试预览');
return;
}
// 清理旧船只
if (previewBoatPartsRef.current) {
try {
const { hull, cabin, mast, marker } = previewBoatPartsRef.current;
if (hull) viewer.entities.remove(hull);
if (cabin) viewer.entities.remove(cabin);
if (mast) viewer.entities.remove(mast);
if (marker) viewer.entities.remove(marker);
} catch { /* ignore */ } finally {
previewBoatPartsRef.current = null;
}
}
// 保存相机
savedCameraStateRef.current = {
position: viewer.camera.position.clone(),
heading: viewer.camera.heading,
pitch: viewer.camera.pitch,
roll: viewer.camera.roll,
};
setIsPreviewing(true);
message.info('开始航线预览,按ESC退出');
const chaseRange = 22;
const chasePitch = -20;
const ellipsoid = Cesium.Ellipsoid?.WGS84;
// 计算累积距离
const distances: number[] = [0];
for (let i = 1; i < polylinePositions.length; i++) {
distances[i] = distances[i - 1] + Cesium.Cartesian3.distance(polylinePositions[i - 1], polylinePositions[i]);
}
const totalDist = distances[distances.length - 1] || 0;
if (totalDist <= 1) {
message.warning('航线过短,无法预览');
setIsPreviewing(false);
return;
}
// Up方向偏移工具
const scratchEnu = new Cesium.Matrix4();
const scratchLocalOffset = new Cesium.Cartesian3();
const offsetUp = (origin: any, upMeters: number) => {
try {
if (!Cesium.Transforms?.eastNorthUpToFixedFrame || !Cesium.Matrix4?.multiplyByPoint) return origin;
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(origin, ellipsoid, scratchEnu);
scratchLocalOffset.x = 0; scratchLocalOffset.y = 0; scratchLocalOffset.z = upMeters;
return Cesium.Matrix4.multiplyByPoint(enu, scratchLocalOffset, new Cesium.Cartesian3());
} catch { return origin; }
};
// 创建船只实体
try {
const firstPos0 = polylinePositions[0];
const boatAboveRoute = 0.05;
const firstPos = offsetUp(firstPos0, boatAboveRoute);
const initialOrientation = Cesium.Transforms?.headingPitchRollQuaternion
? Cesium.Transforms.headingPitchRollQuaternion(firstPos, new Cesium.HeadingPitchRoll(0, 0, 0))
: undefined;
const hull = viewer.entities.add({
position: firstPos,
orientation: initialOrientation,
box: {
dimensions: new Cesium.Cartesian3(1.35, 0.5, 0.2),
material: Cesium.Color.fromCssColorString('#0B3D91').withAlpha(0.92),
outline: true, outlineColor: Cesium.Color.fromCssColorString('#E6F7FF').withAlpha(0.8),
shadows: Cesium.ShadowMode.DISABLED,
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0),
},
});
const cabinOffsetFn = (basePos: any, headingRad: number) => {
if (!Cesium.Transforms?.eastNorthUpToFixedFrame || !Cesium.Matrix4?.multiplyByPoint) return basePos;
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(basePos);
const localOffset = new Cesium.Cartesian3(
Math.sin(headingRad) * 0.25, Math.cos(headingRad) * 0.25, 0.16
);
return Cesium.Matrix4.multiplyByPoint(enu, localOffset, new Cesium.Cartesian3());
};
const cabinPos = cabinOffsetFn(firstPos, 0);
const cabin = viewer.entities.add({
position: cabinPos, orientation: initialOrientation,
box: {
dimensions: new Cesium.Cartesian3(0.55, 0.38, 0.24),
material: Cesium.Color.fromCssColorString('#F5F5F5').withAlpha(0.95),
outline: true, outlineColor: Cesium.Color.fromCssColorString('#FA8C16').withAlpha(0.85),
shadows: Cesium.ShadowMode.DISABLED,
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0),
},
});
const mast = viewer.entities.add({
position: cabinPos, orientation: initialOrientation,
cylinder: {
length: 0.38, topRadius: 0.015, bottomRadius: 0.015,
material: Cesium.Color.fromCssColorString('#FFFFFF').withAlpha(0.9),
shadows: Cesium.ShadowMode.DISABLED,
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0),
},
});
const markerImageUrl = typeof Cesium.buildModuleUrl === 'function'
? Cesium.buildModuleUrl('Assets/Textures/maki/ferry.png')
: '/cesium/Assets/Textures/maki/ferry.png';
const marker = viewer.entities.add({
position: offsetUp(firstPos0, boatAboveRoute + 0.12),
billboard: {
image: markerImageUrl, scale: 0.55,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scaleByDistance: new Cesium.NearFarScalar(20.0, 1.0, 200.0, 0.6),
},
});
previewBoatPartsRef.current = { hull, cabin, mast, marker };
(previewBoatPartsRef.current as any).boatAboveRoute = boatAboveRoute;
(previewBoatPartsRef.current as any).cabinOffset = cabinOffsetFn;
} catch (e) {
console.warn('创建预览船只实体失败:', e);
}
// 二分查找距离索引
const findIndexByDistance = (d: number) => {
let lo = 0, hi = distances.length - 1;
while (lo < hi) { const mid = Math.floor((lo + hi) / 2); if (distances[mid] < d) lo = mid + 1; else hi = mid; }
return Math.max(1, lo);
};
const scratchPosCur = new Cesium.Cartesian3();
const scratchPosA = new Cesium.Cartesian3();
const scratchPosB = new Cesium.Cartesian3();
const scratchCartoCur = new Cesium.Cartographic();
const scratchCartoA = new Cesium.Cartographic();
const scratchCartoB = new Cesium.Cartographic();
const fillSampleAtDistance = (d: number, outPos: any, outCarto: any) => {
const dd = Math.min(totalDist, Math.max(0, d));
const idx = findIndexByDistance(dd);
const prevD = distances[idx - 1] || 0;
const nextD = distances[idx] || prevD + 1;
const frac = Math.min(1, Math.max(0, (dd - prevD) / Math.max(1e-6, nextD - prevD)));
Cesium.Cartesian3.lerp(polylinePositions[idx - 1], polylinePositions[idx], frac, outPos);
try {
Cesium.Cartographic.fromCartesian(outPos, ellipsoid || undefined, outCarto);
} catch {
const c = Cesium.Cartographic.fromCartesian(outPos);
outCarto.longitude = c.longitude; outCarto.latitude = c.latitude; outCarto.height = c.height;
}
};
// 拐点检测
const turnAngleThresholdDeg = 12;
const turnHoldMs = 200;
const turnRotateMs = 650;
const normalizeAngleDeg = (deg: number) => ((deg % 360) + 360) % 360;
const shortestDeltaDeg = (fromDeg: number, toDeg: number) => {
let delta = normalizeAngleDeg(toDeg) - normalizeAngleDeg(fromDeg);
if (delta > 180) delta -= 360; if (delta < -180) delta += 360;
return delta;
};
const lerpHeadingDeg = (fromDeg: number, toDeg: number, f: number) => {
return normalizeAngleDeg(fromDeg + shortestDeltaDeg(fromDeg, toDeg) * Math.min(1, Math.max(0, f)));
};
const cornerInfos: Array<{ distance: number; fromHeading: number; toHeading: number }> = [];
try {
for (let i = 1; i < polylinePositions.length - 1; i++) {
const cPrev = new Cesium.Cartographic(), c = new Cesium.Cartographic(), cNext = new Cesium.Cartographic();
try {
Cesium.Cartographic.fromCartesian(polylinePositions[i - 1], ellipsoid, cPrev);
Cesium.Cartographic.fromCartesian(polylinePositions[i], ellipsoid, c);
Cesium.Cartographic.fromCartesian(polylinePositions[i + 1], ellipsoid, cNext);
} catch { continue; }
const h1 = calculateHeading(
{ longitude: Cesium.Math.toDegrees(cPrev.longitude), latitude: Cesium.Math.toDegrees(cPrev.latitude) },
{ longitude: Cesium.Math.toDegrees(c.longitude), latitude: Cesium.Math.toDegrees(c.latitude) }
);
const h2 = calculateHeading(
{ longitude: Cesium.Math.toDegrees(c.longitude), latitude: Cesium.Math.toDegrees(c.latitude) },
{ longitude: Cesium.Math.toDegrees(cNext.longitude), latitude: Cesium.Math.toDegrees(cNext.latitude) }
);
if (Math.abs(shortestDeltaDeg(h1, h2)) >= turnAngleThresholdDeg) {
cornerInfos.push({ distance: distances[i], fromHeading: h1, toHeading: h2 });
}
}
} catch { /* ignore */ }
let lastT = 0, traveled = 0;
let mode: 'move' | 'turn' = 'move';
let cornerPtr = 0, turnStartT = 0, turnFromHeading = 0, turnToHeading = 0, turnDistance = 0;
const animatePreview = (t: number) => {
if (!lastT) lastT = t;
const dt = Math.max(0, (t - lastT) / 1000);
lastT = t;
if (mode === 'move') {
traveled += dt * speed;
if (cornerPtr < cornerInfos.length && traveled >= cornerInfos[cornerPtr].distance) {
traveled = cornerInfos[cornerPtr].distance;
mode = 'turn'; turnStartT = t;
turnFromHeading = cornerInfos[cornerPtr].fromHeading;
turnToHeading = cornerInfos[cornerPtr].toHeading;
turnDistance = cornerInfos[cornerPtr].distance;
}
} else {
traveled = turnDistance;
if (t - turnStartT >= turnHoldMs + turnRotateMs) {
mode = 'move'; cornerPtr++;
}
}
if (traveled >= totalDist) {
stopPreview();
message.success('航线预览完成');
return;
}
fillSampleAtDistance(traveled, scratchPosCur, scratchCartoCur);
let headingDeg = 0;
if (mode === 'turn') {
const elapsed = t - turnStartT;
headingDeg = elapsed <= turnHoldMs
? turnFromHeading
: lerpHeadingDeg(turnFromHeading, turnToHeading, (elapsed - turnHoldMs) / Math.max(1, turnRotateMs));
} else {
const delta = Math.max(0.6, Math.min(2.5, speed * 0.35));
fillSampleAtDistance(traveled - delta, scratchPosA, scratchCartoA);
fillSampleAtDistance(traveled + delta, scratchPosB, scratchCartoB);
headingDeg = calculateHeading(
{ longitude: Cesium.Math.toDegrees(scratchCartoA.longitude), latitude: Cesium.Math.toDegrees(scratchCartoA.latitude) },
{ longitude: Cesium.Math.toDegrees(scratchCartoB.longitude), latitude: Cesium.Math.toDegrees(scratchCartoB.latitude) }
);
}
const headingRad = Cesium.Math.toRadians(headingDeg);
// 更新船只位置
try {
if (previewBoatPartsRef.current) {
const boatAboveRoute = Number((previewBoatPartsRef.current as any).boatAboveRoute) || 0.05;
const basePos = offsetUp(scratchPosCur, boatAboveRoute);
const orientation = Cesium.Transforms?.headingPitchRollQuaternion
? Cesium.Transforms.headingPitchRollQuaternion(basePos, new Cesium.HeadingPitchRoll(headingRad, 0, 0))
: undefined;
const { hull, cabin, mast } = previewBoatPartsRef.current;
if (hull) { hull.position = basePos; if (orientation) hull.orientation = orientation; }
const cabinOffsetFn = (previewBoatPartsRef.current as any).cabinOffset;
const cabinPos = typeof cabinOffsetFn === 'function' ? cabinOffsetFn(basePos, headingRad) : basePos;
if (cabin) { cabin.position = cabinPos; if (orientation) cabin.orientation = orientation; }
if (mast) { mast.position = cabinPos; if (orientation) mast.orientation = orientation; }
if (previewBoatPartsRef.current.marker) {
previewBoatPartsRef.current.marker.position = offsetUp(scratchPosCur, boatAboveRoute + 0.12);
}
}
} catch { /* ignore */ }
// 追踪相机
try {
const target = offsetUp(scratchPosCur, 0.8);
viewer.camera.lookAt(target, new Cesium.HeadingPitchRange(headingRad, Cesium.Math.toRadians(chasePitch), chaseRange));
} catch {
viewer.camera.setView({
destination: Cesium.Cartesian3.fromRadians(scratchCartoCur.longitude, scratchCartoCur.latitude, (Number(scratchCartoCur.height) || 0) + 10),
orientation: { heading: headingRad, pitch: Cesium.Math.toRadians(-10), roll: 0 },
});
}
try { viewer.scene?.requestRender?.(); } catch { /* ignore */ }
previewAnimationRef.current = requestAnimationFrame(animatePreview);
};
// 先请求一次渲染再启动动画
try { viewer.scene?.requestRender?.(); } catch { /* ignore */ }
setTimeout(() => {
previewAnimationRef.current = requestAnimationFrame(animatePreview);
}, 120);
// ESC退出
const handleEsc = (e: KeyboardEvent) => { if (e.key === 'Escape') stopPreview(); };
window.addEventListener('keydown', handleEsc);
(previewAnimationRef as any).escHandler = handleEsc;
}, [viewerRef, getCesium, isPreviewing, stopPreview, calculateHeading, buildPreviewPolyline]);
// 组件卸载清理
useEffect(() => {
return () => {
if (previewAnimationRef.current) cancelAnimationFrame(previewAnimationRef.current);
if ((previewAnimationRef as any).escHandler) {
window.removeEventListener('keydown', (previewAnimationRef as any).escHandler);
}
if (previewBoatPartsRef.current) {
try {
const viewer = viewerRef?.current;
if (viewer && !viewer.isDestroyed?.()) {
const { hull, cabin, mast, marker } = previewBoatPartsRef.current;
if (hull) viewer.entities.remove(hull);
if (cabin) viewer.entities.remove(cabin);
if (mast) viewer.entities.remove(mast);
if (marker) viewer.entities.remove(marker);
}
} catch { /* ignore */ } finally {
previewBoatPartsRef.current = null;
}
}
if (savedCameraStateRef.current && viewerRef?.current) {
const viewer = viewerRef.current;
const Cesium = (window as any).Cesium;
try { if (Cesium?.Matrix4) viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY); } catch { /* ignore */ }
try {
viewer.camera.setView({
destination: savedCameraStateRef.current.position,
orientation: {
heading: savedCameraStateRef.current.heading,
pitch: savedCameraStateRef.current.pitch,
roll: savedCameraStateRef.current.roll,
},
});
} catch { /* ignore */ } finally {
savedCameraStateRef.current = null;
}
}
};
}, [viewerRef]);
return { isPreviewing, startPreview, stopPreview };
}
@@ -0,0 +1,74 @@
.container {
width: 100vw;
height: 100vh;
display: flex;
background: #0a1628;
color: #fff;
overflow: hidden;
position: relative;
}
.leftPanel {
width: 280px;
height: calc(100vh - 36px);
background: rgba(15, 25, 40, 0.95);
border-right: 1px solid rgba(0, 212, 255, 0.15);
overflow-y: auto;
flex-shrink: 0;
}
.centerView {
flex: 1;
height: calc(100vh - 36px);
position: relative;
}
.rightPanel {
width: 320px;
height: calc(100vh - 36px);
background: rgba(15, 25, 40, 0.95);
border-left: 1px solid rgba(0, 212, 255, 0.15);
overflow-y: auto;
flex-shrink: 0;
}
.statusBar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 36px;
background: rgba(10, 18, 32, 0.95);
border-top: 1px solid rgba(0, 212, 255, 0.15);
display: flex;
align-items: center;
padding: 0 16px;
font-size: 12px;
color: rgba(255, 255, 255, 0.6);
z-index: 100;
}
.statusDot {
width: 8px;
height: 8px;
border-radius: 50%;
margin-right: 8px;
display: inline-block;
}
/* 滚动条样式 */
.leftPanel::-webkit-scrollbar,
.rightPanel::-webkit-scrollbar {
width: 4px;
}
.leftPanel::-webkit-scrollbar-thumb,
.rightPanel::-webkit-scrollbar-thumb {
background: rgba(0, 212, 255, 0.3);
border-radius: 2px;
}
.leftPanel::-webkit-scrollbar-track,
.rightPanel::-webkit-scrollbar-track {
background: transparent;
}
+241
View File
@@ -0,0 +1,241 @@
import React, { useEffect, useState, useMemo, useCallback, useRef } from 'react';
import { history } from 'umi';
import { ConfigProvider, message, Button, Modal } from 'antd';
import { LogoutOutlined } from '@ant-design/icons';
import { darkTheme } from '@/theme';
import LeftPanel from './components/LeftPanel';
import CenterView from './components/CenterView';
import RightPanel from './components/RightPanel';
import { useClientSSE } from './hooks/useClientSSE';
import { getClientRoutes } from './services/clientApi';
import { getBoatRouteDetail } from '@/services/boatRoute';
import type { BoatRouteListVO, BoatTelemetryData, BoatWaypointVO } from '@/types/boatRoute';
import styles from './index.less';
// 模拟遥测数据生成器
const createMockTelemetry = (deviceSn: string, prevData?: BoatTelemetryData | null, initLon?: number, initLat?: number): BoatTelemetryData => {
// 使用传入的初始位置,或者前次位置,或默认位置
const baseLon = prevData?.longitude ?? initLon ?? 108.366;
const baseLat = prevData?.latitude ?? initLat ?? 22.817;
const baseHeading = prevData?.heading ?? 45;
// 模拟船只缓慢移动
const headingRad = (baseHeading + (Math.random() - 0.5) * 10) * Math.PI / 180;
const moveDistance = 0.00002 + Math.random() * 0.00003; // ~2-5m
const newLon = baseLon + Math.cos(headingRad) * moveDistance;
const newLat = baseLat + Math.sin(headingRad) * moveDistance;
const newHeading = ((baseHeading + (Math.random() - 0.5) * 10) + 360) % 360;
return {
deviceSn,
longitude: newLon,
latitude: newLat,
heading: Number(newHeading.toFixed(1)),
speed: Number((1.5 + Math.random() * 2).toFixed(1)),
battery: Math.max(20, (prevData?.battery ?? 85) - Math.random() * 0.1),
signalStrength: 60 + Math.floor(Math.random() * 30),
status: '巡航中',
recordTime: new Date().toISOString(),
taskId: undefined,
currentWaypointIndex: undefined,
};
};
const ClientPage: React.FC = () => {
const [deviceInfo, setDeviceInfo] = useState<any>(null);
const [routes, setRoutes] = useState<BoatRouteListVO[]>([]);
const [routeWaypointsMap, setRouteWaypointsMap] = useState<Record<string, BoatWaypointVO[]>>({});
const [selectedRouteId, setSelectedRouteId] = useState<string | null>(null);
const [routeLoading, setRouteLoading] = useState(false);
const { boatData: sseBoatData, sseConnected, connectSSE, disconnectSSE } = useClientSSE();
const deviceSn = useMemo(() => sessionStorage.getItem('client_device_sn') || '', []);
// 模拟数据:SSE未连接时自动生成模拟遥测数据
const [mockBoatData, setMockBoatData] = useState<BoatTelemetryData | null>(null);
const mockTimerRef = useRef<NodeJS.Timeout | null>(null);
const mockDataRef = useRef<BoatTelemetryData | null>(null);
const modelCenterRef = useRef<{ lon: number; lat: number } | null>(null);
// 模型中心位置回调:当模型加载完成后,重置模拟数据起始位置到模型附近
const handleModelCenter = useCallback((lon: number, lat: number) => {
modelCenterRef.current = { lon, lat };
// 立即重置当前模拟数据位置到模型中心附近
if (mockDataRef.current) {
const newData = {
...mockDataRef.current,
longitude: lon + (Math.random() - 0.5) * 0.001,
latitude: lat + (Math.random() - 0.5) * 0.001,
};
mockDataRef.current = newData;
setMockBoatData(newData);
}
}, []);
// 启动/停止模拟数据:当真实SSE数据到达时停止模拟,否则持续模拟
useEffect(() => {
// 有真实SSE数据,停止模拟
if (sseBoatData) {
if (mockTimerRef.current) {
clearInterval(mockTimerRef.current);
mockTimerRef.current = null;
}
setMockBoatData(null);
mockDataRef.current = null;
return;
}
// 无真实数据且无模拟定时器,启动模拟
if (!mockTimerRef.current && deviceSn) {
console.log('[Mock] 启动模拟数据');
// 立即生成第一帧
const center = modelCenterRef.current;
const firstData = createMockTelemetry(deviceSn, null, center?.lon, center?.lat);
mockDataRef.current = firstData;
setMockBoatData(firstData);
mockTimerRef.current = setInterval(() => {
const center2 = modelCenterRef.current;
const newData = createMockTelemetry(
deviceSn,
mockDataRef.current,
center2?.lon,
center2?.lat,
);
mockDataRef.current = newData;
setMockBoatData(newData);
}, 2000);
}
return () => {
if (mockTimerRef.current) {
clearInterval(mockTimerRef.current);
mockTimerRef.current = null;
}
};
}, [sseBoatData, deviceSn]);
// 优先使用真实SSE数据,回退到模拟数据
const boatData = sseBoatData || mockBoatData;
// 退出登录
const handleLogout = useCallback(() => {
Modal.confirm({
title: '确认退出',
content: '退出后需要重新输入设备SN登录',
okText: '退出',
cancelText: '取消',
onOk: () => {
disconnectSSE();
sessionStorage.removeItem('client_device_sn');
sessionStorage.removeItem('client_device_info');
history.push('/client/login');
},
});
}, [disconnectSSE]);
// 校验登录状态
useEffect(() => {
const sn = sessionStorage.getItem('client_device_sn');
const info = sessionStorage.getItem('client_device_info');
if (!sn || !info) {
history.push('/client/login');
return;
}
try {
setDeviceInfo(JSON.parse(info));
} catch {
history.push('/client/login');
}
}, []);
// 加载游览线路列表 + 预加载航点详情
useEffect(() => {
if (!deviceSn) return;
setRouteLoading(true);
getClientRoutes(deviceSn)
.then(async (res) => {
if (res.resp_code === 0 && res.data) {
setRoutes(res.data);
// 并行预加载所有线路的航点详情
const detailResults = await Promise.allSettled(
res.data.map((r) => getBoatRouteDetail(r.routeId)),
);
const wpMap: Record<string, BoatWaypointVO[]> = {};
detailResults.forEach((result, idx) => {
if (result.status === 'fulfilled' && result.value.resp_code === 0 && result.value.data?.waypoints) {
wpMap[res.data[idx].routeId] = result.value.data.waypoints;
}
});
setRouteWaypointsMap(wpMap);
}
})
.catch(() => message.error('线路加载失败'))
.finally(() => setRouteLoading(false));
}, [deviceSn]);
// 连接SSE
useEffect(() => {
if (!deviceSn) return;
connectSSE(deviceSn);
return () => { disconnectSSE(); };
}, [deviceSn]);
if (!deviceInfo) return null;
return (
<ConfigProvider theme={darkTheme}>
<div className={styles.container}>
{/* 左侧游览线路 */}
<div className={styles.leftPanel}>
<LeftPanel
routes={routes}
routeWaypointsMap={routeWaypointsMap}
loading={routeLoading}
selectedRouteId={selectedRouteId}
onSelectRoute={setSelectedRouteId}
/>
</div>
{/* 中间三维视图 */}
<div className={styles.centerView}>
<CenterView
deviceSn={deviceSn}
routes={routes}
selectedRouteId={selectedRouteId}
boatData={boatData}
onModelCenter={handleModelCenter}
/>
</div>
{/* 右侧设备信息 */}
<div className={styles.rightPanel}>
<RightPanel
deviceInfo={deviceInfo}
boatData={boatData}
sseConnected={sseConnected}
/>
</div>
{/* 底部状态栏 */}
<div className={styles.statusBar}>
<span className={styles.statusDot} style={{ background: sseConnected ? '#00ff88' : '#ff4d4f' }} />
<span>{sseConnected ? 'SSE 已连接' : 'SSE 未连接'}</span>
<span style={{ marginLeft: 16 }}>设备: {deviceInfo.deviceName || deviceSn}</span>
<Button
type="text"
icon={<LogoutOutlined />}
onClick={handleLogout}
style={{ marginLeft: 'auto', color: 'rgba(255,255,255,0.6)', fontSize: 12 }}
size="small"
>
退出
</Button>
</div>
</div>
</ConfigProvider>
);
};
export default ClientPage;
@@ -0,0 +1,46 @@
import { request } from 'umi';
const PREFIX = '/api-device/client';
/**
* 校验设备SN
*/
export async function checkDeviceSn(deviceSn: string) {
return request<API.Result<{ deviceSn: string; deviceName: string; deviceType: number }>>(
`${PREFIX}/auth/check`,
{ method: 'GET', params: { deviceSn } },
);
}
/**
* 获取设备航线列表
*/
export async function getClientRoutes(deviceSn: string) {
return request<API.Result<any[]>>(
`${PREFIX}/routes`,
{ method: 'GET', params: { deviceSn } },
);
}
/**
* 获取设备3D模型列表
*/
export async function getClientModels(deviceSn: string) {
return request<API.Result<any[]>>(
`${PREFIX}/models`,
{ method: 'GET', params: { deviceSn } },
);
}
/**
* 发送船控制指令
* @param deviceSn 设备SN
* @param command 指令类型: forward | backward | left | right | stop
* @param action 动作: press(按下)| release(松开)
*/
export async function sendBoatCommand(deviceSn: string, command: string, action: 'press' | 'release') {
return request<API.Result<any>>(
`${PREFIX}/control/command`,
{ method: 'POST', data: { deviceSn, command, action } },
);
}
@@ -7,6 +7,14 @@
padding: 24px;
background:
linear-gradient(135deg, rgba(0, 20, 50, 0.95) 0%, rgba(0, 40, 80, 0.9) 50%, rgba(0, 60, 100, 0.85) 100%);
position: relative;
}
.login-client-entry {
position: absolute;
top: 16px;
right: 24px;
z-index: 10;
}
.login-wrap {
+12 -2
View File
@@ -1,8 +1,8 @@
import logo from '@/assets/logo.png';
import React, { useEffect, useRef, useState } from 'react';
import { LoginForm, ProFormText, ProFormCaptcha, ProFormCheckbox } from '@ant-design/pro-components';
import { AppstoreOutlined, LockOutlined, UserOutlined } from '@ant-design/icons';
import { Form, message, Spin } from 'antd';
import { AppstoreOutlined, LockOutlined, UserOutlined, LaptopOutlined } from '@ant-design/icons';
import { Form, message, Spin, Button } from 'antd';
import { v4 as uuidv4 } from 'uuid';
import { history } from 'umi';
import { login, LoginParams } from '@/services/login';
@@ -71,6 +71,16 @@ const LoginPage: React.FC = () => {
return (
<div className="login-page">
<div className="login-client-entry">
<Button
type="link"
icon={<LaptopOutlined />}
onClick={() => history.push('/client/login')}
style={{ color: 'rgba(255,255,255,0.7)', fontSize: 14 }}
>
客户端登录
</Button>
</div>
<div className="login-wrap">
<div className="login-hero">
<h1>鹰眼管控平台</h1>