From 44975cde9785056dceb7f3a549eea63be723ed57 Mon Sep 17 00:00:00 2001 From: duzhichao <1098974448@qq.com> Date: Wed, 11 Mar 2026 21:29:55 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=A2=E6=88=B7=E7=AB=AFpad?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../device/controller/ClientController.java | 81 +++ .../controller/ClientSseController.java | 145 ++++++ .../src/main/resources/application.yml | 7 + .../order/service/impl/MediaServiceImpl.java | 38 +- zlt-web/yingyan/config/routes.ts | 11 + zlt-web/yingyan/src/app.tsx | 32 +- .../yingyan/src/pages/client/Login/index.less | 71 +++ .../yingyan/src/pages/client/Login/index.tsx | 62 +++ .../client/components/CenterView/index.less | 78 +++ .../client/components/CenterView/index.tsx | 453 ++++++++++++++++ .../client/components/LeftPanel/index.less | 167 ++++++ .../client/components/LeftPanel/index.tsx | 124 +++++ .../client/components/RightPanel/index.less | 223 ++++++++ .../client/components/RightPanel/index.tsx | 229 ++++++++ .../src/pages/client/hooks/useClientSSE.ts | 228 ++++++++ .../src/pages/client/hooks/useRoutePreview.ts | 487 ++++++++++++++++++ zlt-web/yingyan/src/pages/client/index.less | 74 +++ zlt-web/yingyan/src/pages/client/index.tsx | 241 +++++++++ .../src/pages/client/services/clientApi.ts | 46 ++ .../yingyan/src/pages/user/Login/index.less | 8 + .../yingyan/src/pages/user/Login/index.tsx | 14 +- 21 files changed, 2810 insertions(+), 9 deletions(-) create mode 100644 zlt-business/device-center/src/main/java/com/central/device/controller/ClientController.java create mode 100644 zlt-business/device-center/src/main/java/com/central/device/controller/ClientSseController.java create mode 100644 zlt-web/yingyan/src/pages/client/Login/index.less create mode 100644 zlt-web/yingyan/src/pages/client/Login/index.tsx create mode 100644 zlt-web/yingyan/src/pages/client/components/CenterView/index.less create mode 100644 zlt-web/yingyan/src/pages/client/components/CenterView/index.tsx create mode 100644 zlt-web/yingyan/src/pages/client/components/LeftPanel/index.less create mode 100644 zlt-web/yingyan/src/pages/client/components/LeftPanel/index.tsx create mode 100644 zlt-web/yingyan/src/pages/client/components/RightPanel/index.less create mode 100644 zlt-web/yingyan/src/pages/client/components/RightPanel/index.tsx create mode 100644 zlt-web/yingyan/src/pages/client/hooks/useClientSSE.ts create mode 100644 zlt-web/yingyan/src/pages/client/hooks/useRoutePreview.ts create mode 100644 zlt-web/yingyan/src/pages/client/index.less create mode 100644 zlt-web/yingyan/src/pages/client/index.tsx create mode 100644 zlt-web/yingyan/src/pages/client/services/clientApi.ts diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/ClientController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/ClientController.java new file mode 100644 index 00000000..f3982b6e --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/ClientController.java @@ -0,0 +1,81 @@ +package com.central.device.controller; + +import com.central.common.model.Result; +import com.central.device.model.AgeDevice; +import com.central.device.model.vo.BoatRouteListVO; +import com.central.device.model.vo.ThreeDModelFileVO; +import com.central.device.service.IAgeDeviceService; +import com.central.device.service.IBoatRouteService; +import com.central.device.service.IThreeDModelFileService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 客户端Pad页面专用接口 + * Gateway放行 /client/**,无需认证 + * + * @author dzc + * @date 2026-03-11 + */ +@Slf4j +@RestController +@RequestMapping("/client") +@Tag(name = "客户端Pad接口") +@RequiredArgsConstructor +public class ClientController { + + private final IAgeDeviceService ageDeviceService; + private final IBoatRouteService boatRouteService; + private final IThreeDModelFileService threeDModelFileService; + + /** + * 校验设备SN是否存在 + */ + @Operation(summary = "设备SN校验登录") + @GetMapping("/auth/check") + public Result checkDeviceSn( + @Parameter(description = "设备SN", required = true) + @RequestParam String deviceSn) { + AgeDevice device = ageDeviceService.getByDeviceSn(deviceSn); + if (device == null) { + return Result.failed("设备不存在或未绑定"); + } + Map info = new HashMap<>(); + info.put("deviceSn", device.getDeviceSn()); + info.put("deviceName", device.getDeviceName()); + info.put("deviceType", device.getDeviceType()); + return Result.succeed(info, "验证成功"); + } + + /** + * 获取设备航线列表 + */ + @Operation(summary = "获取设备航线列表") + @GetMapping("/routes") + public Result> getRoutes( + @Parameter(description = "设备SN", required = true) + @RequestParam String deviceSn) { + List routes = boatRouteService.listByDeviceSn(deviceSn); + return Result.succeed(routes, "查询成功"); + } + + /** + * 获取设备关联的3D模型 + */ + @Operation(summary = "获取设备3D模型列表") + @GetMapping("/models") + public Result> getModels( + @Parameter(description = "设备SN", required = true) + @RequestParam String deviceSn) { + List models = threeDModelFileService.getByDeviceSn(deviceSn); + return Result.succeed(models, "查询成功"); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/ClientSseController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/ClientSseController.java new file mode 100644 index 00000000..b03fb7d8 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/ClientSseController.java @@ -0,0 +1,145 @@ +package com.central.device.controller; + +import com.alibaba.fastjson.JSON; +import com.central.device.model.vo.BoatRealtimeVO; +import com.central.device.service.IBoatTrackService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import java.io.IOException; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * 客户端SSE遥测数据控制器 + * Gateway放行 /client/**,无需认证 + * + * @author dzc + * @date 2026-03-11 + */ +@Slf4j +@RestController +@RequestMapping("/client/sse") +@Tag(name = "客户端SSE遥测接口") +@RequiredArgsConstructor +public class ClientSseController { + + private final IBoatTrackService boatTrackService; + + private final Map emitters = new ConcurrentHashMap<>(); + + @Operation(summary = "客户端订阅设备遥测数据") + @GetMapping(value = "/telemetry/{deviceSn}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public ResponseEntity subscribeTelemetry( + @Parameter(description = "设备SN", required = true) + @PathVariable String deviceSn, + @Parameter(description = "客户端会话ID(可选)") + @RequestHeader(value = "X-Client-Session-Id", required = false) String clientSessionId) { + + String connectionId; + if (clientSessionId != null && !clientSessionId.trim().isEmpty()) { + connectionId = "client_" + clientSessionId + "_" + deviceSn; + } else { + connectionId = "client_" + UUID.randomUUID().toString() + "_" + deviceSn; + } + + // 移除已有连接 + if (emitters.containsKey(connectionId)) { + removeConnection(connectionId, deviceSn); + } + + // 创建SSE连接(永不超时) + SseEmitter emitter = new SseEmitter(0L); + emitters.put(connectionId, emitter); + + // 注册遥测回调 + boatTrackService.registerTelemetryCallback(deviceSn, connectionId, (data) -> { + sendTelemetryData(connectionId, data); + }); + + emitter.onCompletion(() -> { + log.info("[ClientSSE] 连接完成: connectionId={}, deviceSn={}", connectionId, deviceSn); + removeConnection(connectionId, deviceSn); + }); + emitter.onTimeout(() -> { + log.info("[ClientSSE] 连接超时: connectionId={}, deviceSn={}", connectionId, deviceSn); + removeConnection(connectionId, deviceSn); + }); + emitter.onError(e -> { + log.warn("[ClientSSE] 连接错误: connectionId={}, error={}", connectionId, e.getMessage()); + removeConnection(connectionId, deviceSn); + }); + + // 发送初始连接事件 + try { + emitter.send(SseEmitter.event() + .name("connected") + .data("{\"connectionId\":\"" + connectionId + "\",\"deviceSn\":\"" + deviceSn + "\"}")); + } catch (IOException e) { + log.error("[ClientSSE] 发送初始事件失败: {}", e.getMessage()); + removeConnection(connectionId, deviceSn); + } + + log.info("[ClientSSE] 客户端订阅遥测: connectionId={}, deviceSn={}", connectionId, deviceSn); + return ResponseEntity.ok().body(emitter); + } + + @Operation(summary = "客户端断开SSE连接") + @DeleteMapping("/telemetry/{deviceSn}") + public ResponseEntity disconnect( + @PathVariable String deviceSn, + @RequestHeader(value = "X-Client-Session-Id", required = false) String clientSessionId) { + if (clientSessionId != null) { + String connectionId = "client_" + clientSessionId + "_" + deviceSn; + removeConnection(connectionId, deviceSn); + } + return ResponseEntity.ok().build(); + } + + @Operation(summary = "客户端断开SSE连接(Beacon)") + @PostMapping("/telemetry/{deviceSn}/disconnect") + public ResponseEntity disconnectBeacon( + @PathVariable String deviceSn, + @RequestBody(required = false) Map body) { + String sessionId = body != null ? body.get("sessionId") : null; + if (sessionId != null) { + String connectionId = "client_" + sessionId + "_" + deviceSn; + removeConnection(connectionId, deviceSn); + } + return ResponseEntity.ok().build(); + } + + private void sendTelemetryData(String connectionId, BoatRealtimeVO data) { + SseEmitter emitter = emitters.get(connectionId); + if (emitter == null) return; + try { + emitter.send(SseEmitter.event() + .name("boat-telemetry") + .data(JSON.toJSONString(data))); + } catch (IOException e) { + log.warn("[ClientSSE] 发送遥测数据失败: connectionId={}, error={}", connectionId, e.getMessage()); + removeConnection(connectionId, data.getDeviceSn()); + } + } + + private boolean removeConnection(String connectionId, String deviceSn) { + SseEmitter emitter = emitters.remove(connectionId); + if (emitter != null) { + try { + emitter.complete(); + } catch (Exception e) { + // 忽略 + } + } + boatTrackService.unregisterTelemetryCallback(deviceSn, connectionId); + return emitter != null; + } +} diff --git a/zlt-business/device-center/src/main/resources/application.yml b/zlt-business/device-center/src/main/resources/application.yml index 71633f09..2f3266fb 100644 --- a/zlt-business/device-center/src/main/resources/application.yml +++ b/zlt-business/device-center/src/main/resources/application.yml @@ -113,3 +113,10 @@ sse: heartbeat: enabled: true interval: 30000 # 心跳间隔(ms) + +# 客户端接口放行(无需认证) +zlt: + security: + ignore: + httpUrls: + - /client/** diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/MediaServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/MediaServiceImpl.java index b36841b4..c79f2f53 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/service/impl/MediaServiceImpl.java +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/MediaServiceImpl.java @@ -25,6 +25,8 @@ import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; @Slf4j @Service @@ -220,15 +222,49 @@ public class MediaServiceImpl implements IMediaService { /** * 基于模板配置构建clips参数 + * fileIndex 匹配文件路径中的拍照顺序号(如 DJI_20260311104552_0014_V.mp4 中的 0014 → 14) */ private String buildClipsParamFromConfig(List videoFiles, ClipsConfig config) { Map clips = new HashMap<>(); for (ClipsConfig.ClipMapping m : config.getMappings()) { - clips.put(m.getSlot(), getUrlBySafeIndex(videoFiles, m.getFileIndex())); + clips.put(m.getSlot(), getUrlBySequenceNumber(videoFiles, m.getFileIndex())); } return JSON.toJSONString(clips); } + /** 从文件路径中提取拍照顺序号,如 DJI_20260311104552_0014_V.mp4 → 14 */ + private static final Pattern SEQUENCE_PATTERN = Pattern.compile("DJI_\\d+_(\\d+)_"); + + private int extractSequenceNumber(String filePath) { + if (filePath == null) { + return -1; + } + // 取文件名部分,避免匹配到目录名中的序号 + int lastSlash = filePath.lastIndexOf('/'); + String fileName = (lastSlash >= 0) ? filePath.substring(lastSlash + 1) : filePath; + Matcher matcher = SEQUENCE_PATTERN.matcher(fileName); + if (matcher.find()) { + return Integer.parseInt(matcher.group(1)); + } + return -1; + } + + /** + * 根据配置的 fileIndex 匹配素材路径中的拍照顺序号,找到对应文件 + */ + private String getUrlBySequenceNumber(List videoFiles, int fileIndex) { + if (videoFiles == null || videoFiles.isEmpty() || fileIndex < 0) { + return ""; + } + for (OrderFile file : videoFiles) { + if (extractSequenceNumber(file.getFilePath()) == fileIndex) { + return fileCenterService.getViewUrlByPath(file.getFilePath()); + } + } + log.warn("未找到拍照顺序号={}的素材文件", fileIndex); + return ""; + } + /** * 默认剪辑参数构建(原有硬编码逻辑,作为兜底) */ diff --git a/zlt-web/yingyan/config/routes.ts b/zlt-web/yingyan/config/routes.ts index cdfa6b03..53686efd 100644 --- a/zlt-web/yingyan/config/routes.ts +++ b/zlt-web/yingyan/config/routes.ts @@ -9,6 +9,17 @@ export default [ component: '@/pages/user/Login', layout: false, }, + // 客户端Pad页面 - 无布局 + { + path: '/client/login', + component: '@/pages/client/Login', + layout: false, + }, + { + path: '/client', + component: '@/pages/client', + layout: false, + }, // 主应用 - 无菜单布局 { path: '/', diff --git a/zlt-web/yingyan/src/app.tsx b/zlt-web/yingyan/src/app.tsx index 84816aec..83d7a785 100644 --- a/zlt-web/yingyan/src/app.tsx +++ b/zlt-web/yingyan/src/app.tsx @@ -4,6 +4,12 @@ import { ThemeProvider } from './theme'; import { history } from 'umi'; import { clearTenantCache, ensureTenantCacheTokenGuard } from '@/utils/tenantCache'; +/** 判断当前是否在客户端页面 */ +const isClientPath = (pathname?: string) => { + const p = pathname || (typeof window !== 'undefined' ? window.location.pathname : ''); + return String(p).startsWith('/client'); +}; + export function rootContainer(container: React.ReactNode, _args?: any) { return React.createElement(ThemeProvider, null, container); } @@ -16,7 +22,7 @@ export const request: any = { try { const status = (error?.response?.status ?? error?.data?.code ?? error?.data?.resp_code) as number | undefined; const unauthorized = status === 401 || status === 403; - if (unauthorized) { + if (unauthorized && !isClientPath()) { try { sessionStorage.removeItem('access_token'); sessionStorage.removeItem('current_user'); @@ -36,10 +42,13 @@ export const request: any = { }, requestInterceptors: [ (url: string, options: any) => { - const token = sessionStorage.getItem('access_token'); const headers: Record = { ...(options?.headers as any) }; - if (token) headers['Authorization'] = `Bearer ${token}`; - ensureTenantCacheTokenGuard(); + // 客户端页面不注入管理后台 token + if (!isClientPath()) { + const token = sessionStorage.getItem('access_token'); + if (token) headers['Authorization'] = `Bearer ${token}`; + ensureTenantCacheTokenGuard(); + } return { url, options: { ...options, headers } }; }, ], @@ -60,7 +69,7 @@ export const request: any = { const httpUnauthorized = (response.status === 401 || response.status === 403); const bizCode = (data?.resp_code ?? data?.code) as number | undefined; const bizUnauthorized = bizCode === 401 || bizCode === 403 || bizCode === 40101 || bizCode === 40100; - if (httpUnauthorized || bizUnauthorized) { + if ((httpUnauthorized || bizUnauthorized) && !isClientPath()) { try { sessionStorage.removeItem('access_token'); sessionStorage.removeItem('current_user'); @@ -82,8 +91,19 @@ export const request: any = { export function onRouteChange({ location }: any) { try { + const pathname = String(location?.pathname || ''); + // 客户端页面走自己的登录逻辑,不检查管理后台 token + if (isClientPath(pathname)) { + const isClientLogin = pathname.startsWith('/client/login'); + const hasDeviceSn = sessionStorage.getItem('client_device_sn'); + if (!hasDeviceSn && !isClientLogin) { + history.push('/client/login'); + } + return; + } + // 管理后台登录检查 const token = sessionStorage.getItem('access_token'); - const isLoginPath = String(location?.pathname || '').startsWith('/user/login'); + const isLoginPath = pathname.startsWith('/user/login'); if (!token && !isLoginPath) { history.push('/user/login'); } diff --git a/zlt-web/yingyan/src/pages/client/Login/index.less b/zlt-web/yingyan/src/pages/client/Login/index.less new file mode 100644 index 00000000..a3ba42a5 --- /dev/null +++ b/zlt-web/yingyan/src/pages/client/Login/index.less @@ -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); +} diff --git a/zlt-web/yingyan/src/pages/client/Login/index.tsx b/zlt-web/yingyan/src/pages/client/Login/index.tsx new file mode 100644 index 00000000..7d69b589 --- /dev/null +++ b/zlt-web/yingyan/src/pages/client/Login/index.tsx @@ -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 ( +
+
+ +
+
+
设备客户端
+
请输入设备SN号登录
+
+ + } + placeholder="请输入设备SN号" + autoComplete="off" + /> + + + + +
+
+
+ ); +}; + +export default ClientLogin; diff --git a/zlt-web/yingyan/src/pages/client/components/CenterView/index.less b/zlt-web/yingyan/src/pages/client/components/CenterView/index.less new file mode 100644 index 00000000..6f9c7036 --- /dev/null +++ b/zlt-web/yingyan/src/pages/client/components/CenterView/index.less @@ -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; +} diff --git a/zlt-web/yingyan/src/pages/client/components/CenterView/index.tsx b/zlt-web/yingyan/src/pages/client/components/CenterView/index.tsx new file mode 100644 index 00000000..5c186bb6 --- /dev/null +++ b/zlt-web/yingyan/src/pages/client/components/CenterView/index.tsx @@ -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 = ({ deviceSn, routes, selectedRouteId, boatData, onModelCenter }) => { + const containerRef = useRef(null); + const viewerRef = useRef(null); + const [viewerReady, setViewerReady] = useState(false); + const [modelLoading, setModelLoading] = useState(false); + const boatEntityRef = useRef(null); + const trackPositionsRef = useRef([]); + const terrainLoadedRef = useRef(false); + + const { loadTileset, unloadAllTilesets } = useTilesetLoader(); + const { isPreviewing, startPreview, stopPreview } = useRoutePreview({ viewerRef }); + + // 航线渲染数据(含航点) + const [routeRenderItems, setRouteRenderItems] = useState([]); + // 缓存已加载的航线详情 + const routeDetailCacheRef = useRef>(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 => { + 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 ( +
+
+ + {/* 模型加载提示 */} + {modelLoading && ( +
+
+ 正在加载3D模型... +
+ )} + + {/* 选中线路时显示操作按钮 */} + {selectedRouteId && !isPreviewing && ( +
+
{selectedRouteName}
+ + + + +
+ )} + + {/* 预览中显示停止按钮 */} + {isPreviewing && ( +
+ +
+ )} +
+ ); +}; + +export default CenterView; diff --git a/zlt-web/yingyan/src/pages/client/components/LeftPanel/index.less b/zlt-web/yingyan/src/pages/client/components/LeftPanel/index.less new file mode 100644 index 00000000..c872d266 --- /dev/null +++ b/zlt-web/yingyan/src/pages/client/components/LeftPanel/index.less @@ -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); + } +} diff --git a/zlt-web/yingyan/src/pages/client/components/LeftPanel/index.tsx b/zlt-web/yingyan/src/pages/client/components/LeftPanel/index.tsx new file mode 100644 index 00000000..231880dc --- /dev/null +++ b/zlt-web/yingyan/src/pages/client/components/LeftPanel/index.tsx @@ -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; + 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 = ({ + routes, + routeWaypointsMap, + loading, + selectedRouteId, + onSelectRoute, +}) => { + return ( +
+
+
+ +
+
+
游览线路
+
选择线路开始游览
+
+ {routes.length} +
+ +
+ {loading ? ( +
+ ) : routes.length === 0 ? ( +
+ +
+ ) : ( + 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 ( +
onSelectRoute(isSelected ? null : route.routeId)} + > + {/* 线路名称 */} +
{route.routeName}
+ + {/* 时长 + 距离 标签 */} +
+ {duration && ( + + + {duration} + + )} + {distance && ( + + + {distance} + + )} + + + {route.waypointCount || waypoints.length}个景点 + +
+ + {/* 航点路径 */} + {waypointNames.length > 0 && ( +
+ {waypointNames.map((name, idx) => ( + + + {name} + {idx < waypointNames.length - 1 && ( + → + )} + + ))} +
+ )} +
+ ); + }) + )} +
+
+ ); +}; + +export default LeftPanel; diff --git a/zlt-web/yingyan/src/pages/client/components/RightPanel/index.less b/zlt-web/yingyan/src/pages/client/components/RightPanel/index.less new file mode 100644 index 00000000..b1b3eae0 --- /dev/null +++ b/zlt-web/yingyan/src/pages/client/components/RightPanel/index.less @@ -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; +} diff --git a/zlt-web/yingyan/src/pages/client/components/RightPanel/index.tsx b/zlt-web/yingyan/src/pages/client/components/RightPanel/index.tsx new file mode 100644 index 00000000..6b081bd7 --- /dev/null +++ b/zlt-web/yingyan/src/pages/client/components/RightPanel/index.tsx @@ -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 = ({ 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(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 ( +
+ {/* 船体控制 */} +
+
船体控制
+ + {/* 罗盘仪表盘 */} +
+
+ {/* 外圈刻度 */} + + {/* 外圆 */} + + + {/* 刻度线 */} + {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 ( + + ); + })} + {/* N/S/E/W 标记 */} + N + S + E + W + {/* 方向指针(船头) */} + + + + + {/* 中心圆点 */} + + + +
+
+ 航向 + {heading.toFixed(0)}° +
+
+ + {/* 左转 / 右转按钮 */} +
+
+ + {/* 速度滑块 */} +
+ 速度 +
+ `${v} km/h` }} + /> +
+ {targetSpeed} km/h +
+ + {/* 紧急停靠 */} + +
+ + {/* 实时数据 */} +
+
实时数据
+ + {/* 船舶状态 */} +
+
船舶状态
+
+ 速度 + {speed.toFixed(1)} km/h +
+
+ 方向 + {heading.toFixed(0)}° +
+
+ 电量 + + {battery.toFixed(0)}% + +
+
+ 模式 + {boatData?.taskId ? '自动' : '手动'} +
+
+ + {/* 环境数据 */} +
+
环境数据
+
+ 水质 + 优 +
+
+ 风速 + {(1.5 + (boatData?.speed ?? 0) * 0.3).toFixed(1)} m/s +
+
+ 温度 + {(18 + Math.round((boatData?.heading ?? 0) % 5)).toFixed(0)}°C +
+
+ + {/* 设备状态 */} +
+
设备状态
+
+ 传感器 + 正常 +
+
+ 连接状态 + + {sseConnected ? '已连接' : '未连接'} + +
+
+ 设备SN + {deviceInfo.deviceSn} +
+
+ GPS + + {boatData?.longitude != null + ? `${boatData.longitude.toFixed(4)}, ${boatData.latitude?.toFixed(4)}` + : '--'} + +
+
+
+
+ ); +}; + +export default RightPanel; diff --git a/zlt-web/yingyan/src/pages/client/hooks/useClientSSE.ts b/zlt-web/yingyan/src/pages/client/hooks/useClientSSE.ts new file mode 100644 index 00000000..17d37823 --- /dev/null +++ b/zlt-web/yingyan/src/pages/client/hooks/useClientSSE.ts @@ -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; + disconnectSSE: (deviceSn?: string) => Promise; +} + +export const useClientSSE = (): UseClientSSEReturn => { + const [boatData, setBoatData] = useState(null); + const [sseConnected, setSSEConnected] = useState(false); + const [loading, setLoading] = useState(false); + + const abortControllerRef = useRef(null); + const currentDeviceSnRef = useRef(''); + const clientSessionIdRef = useRef( + `client_pad_${Date.now()}_${Math.random().toString(36).substring(2, 9)}` + ); + const reconnectTimerRef = useRef(null); + const reconnectAttemptsRef = useRef(0); + const maxReconnectAttempts = 10; + const shouldReconnectRef = useRef(true); + const idleTimerRef = useRef(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 }; +}; diff --git a/zlt-web/yingyan/src/pages/client/hooks/useRoutePreview.ts b/zlt-web/yingyan/src/pages/client/hooks/useRoutePreview.ts new file mode 100644 index 00000000..f8259578 --- /dev/null +++ b/zlt-web/yingyan/src/pages/client/hooks/useRoutePreview.ts @@ -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; +} + +export interface UseRoutePreviewReturn { + isPreviewing: boolean; + startPreview: (waypoints: BoatWaypointDTO[], speed?: number) => Promise; + stopPreview: () => void; +} + +export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoutePreviewReturn { + const [isPreviewing, setIsPreviewing] = useState(false); + const previewAnimationRef = useRef(null); + const savedCameraStateRef = useRef(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 }; +} diff --git a/zlt-web/yingyan/src/pages/client/index.less b/zlt-web/yingyan/src/pages/client/index.less new file mode 100644 index 00000000..939fa60b --- /dev/null +++ b/zlt-web/yingyan/src/pages/client/index.less @@ -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; +} diff --git a/zlt-web/yingyan/src/pages/client/index.tsx b/zlt-web/yingyan/src/pages/client/index.tsx new file mode 100644 index 00000000..df8b6e7f --- /dev/null +++ b/zlt-web/yingyan/src/pages/client/index.tsx @@ -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(null); + const [routes, setRoutes] = useState([]); + const [routeWaypointsMap, setRouteWaypointsMap] = useState>({}); + const [selectedRouteId, setSelectedRouteId] = useState(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(null); + const mockTimerRef = useRef(null); + const mockDataRef = useRef(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 = {}; + 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 ( + +
+ {/* 左侧游览线路 */} +
+ +
+ + {/* 中间三维视图 */} +
+ +
+ + {/* 右侧设备信息 */} +
+ +
+ + {/* 底部状态栏 */} +
+ + {sseConnected ? 'SSE 已连接' : 'SSE 未连接'} + 设备: {deviceInfo.deviceName || deviceSn} + +
+
+
+ ); +}; + +export default ClientPage; diff --git a/zlt-web/yingyan/src/pages/client/services/clientApi.ts b/zlt-web/yingyan/src/pages/client/services/clientApi.ts new file mode 100644 index 00000000..bae9ef83 --- /dev/null +++ b/zlt-web/yingyan/src/pages/client/services/clientApi.ts @@ -0,0 +1,46 @@ +import { request } from 'umi'; + +const PREFIX = '/api-device/client'; + +/** + * 校验设备SN + */ +export async function checkDeviceSn(deviceSn: string) { + return request>( + `${PREFIX}/auth/check`, + { method: 'GET', params: { deviceSn } }, + ); +} + +/** + * 获取设备航线列表 + */ +export async function getClientRoutes(deviceSn: string) { + return request>( + `${PREFIX}/routes`, + { method: 'GET', params: { deviceSn } }, + ); +} + +/** + * 获取设备3D模型列表 + */ +export async function getClientModels(deviceSn: string) { + return request>( + `${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>( + `${PREFIX}/control/command`, + { method: 'POST', data: { deviceSn, command, action } }, + ); +} diff --git a/zlt-web/yingyan/src/pages/user/Login/index.less b/zlt-web/yingyan/src/pages/user/Login/index.less index 284a106d..a19f5cf5 100644 --- a/zlt-web/yingyan/src/pages/user/Login/index.less +++ b/zlt-web/yingyan/src/pages/user/Login/index.less @@ -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 { diff --git a/zlt-web/yingyan/src/pages/user/Login/index.tsx b/zlt-web/yingyan/src/pages/user/Login/index.tsx index b5fded7c..7ddd068b 100644 --- a/zlt-web/yingyan/src/pages/user/Login/index.tsx +++ b/zlt-web/yingyan/src/pages/user/Login/index.tsx @@ -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 (
+
+ +

鹰眼管控平台