diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/BoatRouteController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/BoatRouteController.java index 0faa381d..3a77ff31 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/controller/BoatRouteController.java +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/BoatRouteController.java @@ -13,13 +13,23 @@ 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 org.springframework.format.annotation.DateTimeFormat; import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import java.time.LocalDateTime; import java.util.List; /** - * 无人船航线管理Controller + * 无人船航线管理 Controller * * @author dzc * @date 2026-01-05 @@ -56,6 +66,21 @@ public class BoatRouteController { return Result.succeed(detail); } + @Operation(summary = "分页查询无人船航线列表") + @GetMapping("/page") + public Result> pageRoutes( + @Parameter(description = "航线名称") @RequestParam(required = false) String routeName, + @Parameter(description = "设备SN") @RequestParam(required = false) String deviceSn, + @Parameter(description = "创建开始时间") @RequestParam(required = false) + @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime, + @Parameter(description = "创建结束时间") @RequestParam(required = false) + @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime, + @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page, + @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer size) { + Page pageResult = boatRouteService.pageRoutes(routeName, deviceSn, startTime, endTime, page, size); + return Result.succeed(pageResult); + } + @Operation(summary = "获取设备绑定的航线列表") @GetMapping("/list/device/{deviceSn}") public Result> listByDeviceSn( diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/IBoatRouteService.java b/zlt-business/device-center/src/main/java/com/central/device/service/IBoatRouteService.java index 873788cd..be370ae4 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/service/IBoatRouteService.java +++ b/zlt-business/device-center/src/main/java/com/central/device/service/IBoatRouteService.java @@ -9,6 +9,7 @@ import com.central.device.model.vo.BoatRouteDetailVO; import com.central.device.model.vo.BoatRouteListVO; import com.central.device.model.vo.RouteValidateResultVO; +import java.time.LocalDateTime; import java.util.List; /** @@ -69,6 +70,20 @@ public interface IBoatRouteService extends IService { */ Page listByScenicId(Long scenicId, Integer page, Integer size); + /** + * 分页查询无人船航线列表 + * + * @param routeName 航线名称 + * @param deviceSn 设备SN + * @param startTime 创建开始时间 + * @param endTime 创建结束时间 + * @param page 页码 + * @param size 每页数量 + * @return 航线分页列表 + */ + Page pageRoutes(String routeName, String deviceSn, LocalDateTime startTime, LocalDateTime endTime, + Integer page, Integer size); + /** * 绑定航线到设备 * diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/BoatRouteServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/BoatRouteServiceImpl.java index 8cd9fcfd..91332a76 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/service/impl/BoatRouteServiceImpl.java +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/BoatRouteServiceImpl.java @@ -35,6 +35,7 @@ import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.math.RoundingMode; +import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -314,6 +315,34 @@ public class BoatRouteServiceImpl extends ServiceImpl pageRoutes(String routeName, String deviceSn, LocalDateTime startTime, + LocalDateTime endTime, Integer page, Integer size) { + String anchor = LoginUserContextHolder.getCurrentTenantId(); + try { + if (anchor == null || anchor.isEmpty()) { + anchor = com.central.common.context.TenantQueryOverrideContext.getTenantId(); + } + } catch (Exception ignored) { + log.error("获取当前登录用户租户失败"); + } + + Page pageParam = new Page<>(page, size); + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(anchor != null && !anchor.isEmpty(), BoatRoute::getTenantId, anchor) + .eq(BoatRoute::getDeleted, 0) + .like(StrUtil.isNotBlank(routeName), BoatRoute::getRouteName, StrUtil.trim(routeName)) + .like(StrUtil.isNotBlank(deviceSn), BoatRoute::getDeviceSn, StrUtil.trim(deviceSn)) + .ge(startTime != null, BoatRoute::getCreateTime, startTime) + .le(endTime != null, BoatRoute::getCreateTime, endTime) + .orderByDesc(BoatRoute::getCreateTime); + + Page routePage = this.page(pageParam, wrapper); + Page resultPage = new Page<>(page, size, routePage.getTotal()); + resultPage.setRecords(convertToListVO(routePage.getRecords())); + return resultPage; + } + @Override @Transactional(rollbackFor = Exception.class) public void bindToDevice(String routeId, String deviceSn) { diff --git a/zlt-business/device-center/src/main/resources/doc/waypoints.json b/zlt-business/device-center/src/main/resources/doc/waypoints.json index 98949bf8..040ebce9 100644 --- a/zlt-business/device-center/src/main/resources/doc/waypoints.json +++ b/zlt-business/device-center/src/main/resources/doc/waypoints.json @@ -1,8 +1,8 @@ { "routeId": "c928a113c4c2489883c41a038f0c7959", "routeName": "Manual Route 2026/4/12 1:1:58", - "deviceSn": "SHIP-V1-00001", - "deviceName": "Koi Fish Agent", + "deviceSn": "12345678", + "deviceName": "锦鲤一号", "scenicId": 1, "waypointCount": 75, "totalDistance": 1157, diff --git a/zlt-business/device-center/src/main/resources/doc/waypoints5.json b/zlt-business/device-center/src/main/resources/doc/waypoints5.json new file mode 100644 index 00000000..8bbf7142 --- /dev/null +++ b/zlt-business/device-center/src/main/resources/doc/waypoints5.json @@ -0,0 +1,93 @@ +{ + "routeId": "33415e9578a74c59a16a5d2d3fee492c", + "routeName": "Manual Test Route 2026/4/6 16:16:59", + "deviceSn": "12345678", + "deviceName": "锦鲤一号", + "scenicId": 1, + "waypointCount": 5, + "totalDistance": 320.65, + "totalDuration": 1603, + "cruiseSpeed": 0.2, + "loopEnabled": false, + "loopCount": 1, + "returnMode": "origin", + "safeDistance": 5, + "startPoint": "121.89807344122099,30.87373280450406", + "endPoint": "121.8984168707936,30.873953677640834", + "status": 1, + "statusDesc": "Local Draft", + "waypoints": [ + { + "waypointId": "289feeecdd554c3989759a584c777c09", + "waypointIndex": 0, + "longitude": 121.89807344122099, + "latitude": 30.87373280450406, + "speed": 2, + "stayDuration": 0, + "headingAngle": 49, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "起点", + "actions": null, + "remark": null + }, + { + "waypointId": "e1b7444d7d4942e2886b05f6b76f8392", + "waypointIndex": 1, + "longitude": 121.89865297403038, + "latitude": 30.874119329720497, + "speed": 2, + "stayDuration": 0, + "headingAngle": 49, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点1", + "actions": null, + "remark": null + }, + { + "waypointId": "ab214e90d4f6495d85abfeae791a6b53", + "waypointIndex": 2, + "longitude": 121.89949003611937, + "latitude": 30.874809529580364, + "speed": 2, + "stayDuration": 0, + "headingAngle": 49, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点2", + "actions": null, + "remark": null + }, + { + "waypointId": "e54c7b84314643538e9648d738a88ef7", + "waypointIndex": 3, + "longitude": 121.89906077613658, + "latitude": 30.874478239874847, + "speed": 2, + "stayDuration": 0, + "headingAngle": 233, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点3", + "actions": null, + "remark": null + }, + { + "waypointId": "2454526441a54e989fa4739c01510c18", + "waypointIndex": 4, + "longitude": 121.8984168707936, + "latitude": 30.873953677640834, + "speed": 2, + "stayDuration": 0, + "headingAngle": null, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "终点", + "actions": null, + "remark": null + } + ], + "createTime": "2026-04-06 08:16:59", + "updateTime": "2026-04-06 08:16:59" +} \ No newline at end of file diff --git a/zlt-web/react-web-next/config/routes.ts b/zlt-web/react-web-next/config/routes.ts index d8d6a9f0..b9aa9cb5 100644 --- a/zlt-web/react-web-next/config/routes.ts +++ b/zlt-web/react-web-next/config/routes.ts @@ -51,6 +51,7 @@ export default [ { path: '/device', routes: [ + { path: '/device/boatRoute.html', name: '无人船航线管理', component: '@/pages/device/BoatRoute' }, { path: '/device/wayline.html', component: '@/pages/device/Wayline' }, { path: '/device/device.html', component: '@/pages/device/Device' }, // 3D模型管理 diff --git a/zlt-web/react-web-next/src/pages/device/BoatRoute/components/BoatRouteCreateModal.tsx b/zlt-web/react-web-next/src/pages/device/BoatRoute/components/BoatRouteCreateModal.tsx new file mode 100644 index 00000000..cd803a8b --- /dev/null +++ b/zlt-web/react-web-next/src/pages/device/BoatRoute/components/BoatRouteCreateModal.tsx @@ -0,0 +1,115 @@ +import React, { useState } from 'react'; +import { ModalForm, ProFormText } from '@ant-design/pro-components'; +import { Alert, Button, Descriptions, Space, Upload, message } from 'antd'; +import { UploadOutlined } from '@ant-design/icons'; +import type { UploadFile } from 'antd/lib/upload/interface'; +import type { BoatRoutePayload } from '@/services/boatRoute'; +import { parseBoatRouteJson } from './routeJson'; + +interface BoatRouteCreateModalProps { + visible: boolean; + onVisibleChange: (visible: boolean) => void; + onFinish: (values: BoatRoutePayload) => Promise; +} + +const readFileText = (file: File) => + new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(String(reader.result || '')); + reader.onerror = () => reject(new Error('读取文件失败')); + reader.readAsText(file, 'utf-8'); + }); + +const BoatRouteCreateModal: React.FC = ({ visible, onVisibleChange, onFinish }) => { + const [fileList, setFileList] = useState([]); + const [parsedPayload, setParsedPayload] = useState(null); + const [routeName, setRouteName] = useState(''); + + const reset = () => { + setFileList([]); + setParsedPayload(null); + setRouteName(''); + }; + + const handleFile = async (file: File) => { + if (!routeName.trim()) { + message.warning('请先输入航线名称'); + return Upload.LIST_IGNORE; + } + + try { + const text = await readFileText(file); + const payload = parseBoatRouteJson(text, routeName.trim()); + setParsedPayload(payload); + setFileList([{ uid: file.name, name: file.name, status: 'done' }]); + message.success(`解析成功,共 ${payload.waypoints.length} 个航点`); + } catch (error: any) { + setParsedPayload(null); + setFileList([]); + message.error(error?.message || 'JSON 文件解析失败'); + } + + return false; + }; + + return ( + + title="新增无人船航线" + visible={visible} + width={720} + modalProps={{ destroyOnClose: true }} + onVisibleChange={(nextVisible) => { + onVisibleChange(nextVisible); + if (!nextVisible) reset(); + }} + onFinish={async () => { + if (!parsedPayload) { + message.warning('请上传并解析航线 JSON 文件'); + return false; + } + const success = await onFinish({ ...parsedPayload, routeName: routeName.trim() }); + if (success) reset(); + return success; + }} + > + { + setRouteName(event.target.value); + setParsedPayload(null); + setFileList([]); + }, + }} + /> + + { + setParsedPayload(null); + setFileList([]); + }}> + + + + + + {parsedPayload && ( + + {parsedPayload.deviceSn || '--'} + {parsedPayload.waypoints.length} + {parsedPayload.cruiseSpeed ?? '--'} m/s + {parsedPayload.safeDistance ?? '--'} m + {parsedPayload.loopEnabled ? '是' : '否'} + {parsedPayload.returnMode || '--'} + + )} + + + + ); +}; + +export default BoatRouteCreateModal; diff --git a/zlt-web/react-web-next/src/pages/device/BoatRoute/components/BoatRouteEditModal.tsx b/zlt-web/react-web-next/src/pages/device/BoatRoute/components/BoatRouteEditModal.tsx new file mode 100644 index 00000000..f6a41acc --- /dev/null +++ b/zlt-web/react-web-next/src/pages/device/BoatRoute/components/BoatRouteEditModal.tsx @@ -0,0 +1,286 @@ +import React, { useEffect, useState } from 'react'; +import { ModalForm, ProFormDigit, ProFormSelect, ProFormSwitch, ProFormText, ProFormTextArea } from '@ant-design/pro-components'; +import { Button, Card, Collapse, Empty, Form, Input, InputNumber, Modal, Space, Table, Tabs, Tag, message } from 'antd'; +import type { ColumnsType } from 'antd/lib/table'; +import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons'; +import type { BoatRouteDetail, BoatRoutePayload, BoatWaypoint } from '@/services/boatRoute'; +import { boatRouteApi } from '@/services/boatRoute'; +import { buildUpdatePayload, normalizeWaypoint } from './routeJson'; + +interface BoatRouteEditModalProps { + visible: boolean; + routeId?: string; + onVisibleChange: (visible: boolean) => void; + onFinish: (routeId: string, values: Partial) => Promise; +} + +const ACTION_TYPE_OPTIONS = [ + { label: '拍照', value: 'photo' }, + { label: '开始录像', value: 'video_start' }, + { label: '停止录像', value: 'video_stop' }, + { label: '鸣笛', value: 'horn' }, + { label: '灯光控制', value: 'light' }, +]; + +const TURN_MODE_OPTIONS = [ + { label: '平滑转弯', value: 'smooth' }, + { label: '急转弯', value: 'sharp' }, +]; + +const RETURN_MODE_OPTIONS = [ + { label: '返回起点', value: 'return_start' }, + { label: '原地停留', value: 'stay' }, + { label: '保持原文件值', value: 'origin' }, +]; + +const BoatRouteEditModal: React.FC = ({ visible, routeId, onVisibleChange, onFinish }) => { + const [form] = Form.useForm(); + const [waypointForm] = Form.useForm(); + const [actionForm] = Form.useForm(); + const [loading, setLoading] = useState(false); + const [detail, setDetail] = useState(null); + const [waypoints, setWaypoints] = useState([]); + const [waypointOpen, setWaypointOpen] = useState(false); + const [editingWaypointIndex, setEditingWaypointIndex] = useState(null); + const [actionOpen, setActionOpen] = useState(false); + const [editingActionIndex, setEditingActionIndex] = useState(null); + + const loadDetail = async () => { + if (!visible || !routeId) return; + setLoading(true); + try { + const data = await boatRouteApi.detail(routeId); + setDetail(data); + setWaypoints((data.waypoints || []).map((item, index) => normalizeWaypoint(item, index))); + form.setFieldsValue({ + routeName: data.routeName, + cruiseSpeed: data.cruiseSpeed, + loopEnabled: data.loopEnabled, + loopCount: data.loopCount, + returnMode: data.returnMode || 'return_start', + safeDistance: data.safeDistance, + boundaryId: data.boundaryId, + remark: data.remark, + showInModel: data.showInModel || 0, + }); + } catch { + message.error('加载航线详情失败'); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + loadDetail(); + }, [visible, routeId]); + + const closeWaypoint = () => { + setWaypointOpen(false); + setEditingWaypointIndex(null); + waypointForm.resetFields(); + }; + + const openWaypoint = (record?: BoatWaypoint, index?: number) => { + setEditingWaypointIndex(index ?? null); + waypointForm.setFieldsValue(record || { + waypointIndex: waypoints.length, + turnMode: 'smooth', + stayDuration: 0, + isKeyPoint: false, + actions: [], + }); + setWaypointOpen(true); + }; + + const saveWaypoint = async () => { + const values = await waypointForm.validateFields(); + const normalized = normalizeWaypoint(values, editingWaypointIndex ?? waypoints.length); + setWaypoints((list) => { + if (editingWaypointIndex === null) return [...list, normalized]; + return list.map((item, index) => (index === editingWaypointIndex ? { ...item, ...normalized } : item)); + }); + closeWaypoint(); + }; + + const removeWaypoint = (index: number) => { + Modal.confirm({ + title: `确认删除第 ${index + 1} 个航点?`, + onOk: () => setWaypoints((list) => list.filter((_, itemIndex) => itemIndex !== index)), + }); + }; + + const currentActions = Form.useWatch('actions', waypointForm) || []; + + const openAction = (record?: any, index?: number) => { + setEditingActionIndex(index ?? null); + actionForm.setFieldsValue({ + actionType: record?.actionType || 'photo', + duration: record?.duration ?? 0, + paramsText: record?.params ? JSON.stringify(record.params, null, 2) : '', + }); + setActionOpen(true); + }; + + const saveAction = async () => { + const values = await actionForm.validateFields(); + let params: any = undefined; + if (values.paramsText) { + try { + params = JSON.parse(values.paramsText); + } catch { + message.error('动作参数必须是合法 JSON'); + return; + } + } + const nextAction = { actionType: values.actionType, duration: values.duration, params }; + const actions = [...currentActions]; + if (editingActionIndex === null) actions.push(nextAction); + else actions[editingActionIndex] = nextAction; + waypointForm.setFieldsValue({ actions }); + setActionOpen(false); + setEditingActionIndex(null); + actionForm.resetFields(); + }; + + const removeAction = (index: number) => { + waypointForm.setFieldsValue({ actions: currentActions.filter((_: any, itemIndex: number) => itemIndex !== index) }); + }; + + const waypointColumns: ColumnsType = [ + { title: '序号', dataIndex: 'waypointIndex', width: 80, render: (_, __, index) => index + 1 }, + { title: '航点名称', dataIndex: 'pointName', width: 140 }, + { title: '经度', dataIndex: 'longitude', width: 140 }, + { title: '纬度', dataIndex: 'latitude', width: 140 }, + { title: '速度(m/s)', dataIndex: 'speed', width: 100 }, + { title: '停留(秒)', dataIndex: 'stayDuration', width: 100 }, + { title: '动作数', dataIndex: 'actions', width: 90, render: (actions) => (actions?.length || 0) }, + { + title: '操作', + width: 140, + fixed: 'right', + render: (_, record, index) => ( + + openWaypoint(record, index)}> 编辑 + removeWaypoint(index)}> 删除 + + ), + }, + ]; + + const actionColumns: ColumnsType = [ + { title: '动作类型', dataIndex: 'actionType', render: (value) => ACTION_TYPE_OPTIONS.find((item) => item.value === value)?.label || value }, + { title: '持续时间(秒)', dataIndex: 'duration', width: 120 }, + { title: '参数', dataIndex: 'params', ellipsis: true, render: (value) => value ? JSON.stringify(value) : '--' }, + { + title: '操作', + width: 120, + render: (_, record, index) => ( + + openAction(record, index)}>编辑 + removeAction(index)}>删除 + + ), + }, + ]; + + return ( + <> + { + onVisibleChange(nextVisible); + if (!nextVisible) { + setDetail(null); + setWaypoints([]); + form.resetFields(); + } + }} + onFinish={async (values) => { + if (!routeId || !detail) return false; + if (!waypoints.length) { + message.warning('航点不能为空'); + return false; + } + const payload = buildUpdatePayload({ ...detail, ...values }, waypoints); + return onFinish(routeId, payload); + }} + > + + + {loading ? : null} + + + + + + + + + + + + + 航点列表{waypoints.length} 个航点} + extra={} + > + record.waypointId || String(index)} + columns={waypointColumns} + dataSource={waypoints} + size="small" + scroll={{ x: 1000, y: 460 }} + pagination={{ pageSize: 10, showSizeChanger: true }} + expandable={{ + expandedRowRender: (record) => ( + record.actions?.length ? ( +
String(index)} columns={actionColumns.slice(0, 3)} dataSource={record.actions} pagination={false} size="small" /> + ) : + ), + }} + /> + + + + + + +
+ + + + + + + + + + + + + } onClick={(event) => { event.stopPropagation(); openAction(); }}>新增动作}> +
String(index)} columns={actionColumns} dataSource={currentActions} pagination={false} size="small" /> + + + + + + setActionOpen(false)} destroyOnClose> +
+ + + + + + +
+ + ); +}; + +export default BoatRouteEditModal; diff --git a/zlt-web/react-web-next/src/pages/device/BoatRoute/components/routeJson.ts b/zlt-web/react-web-next/src/pages/device/BoatRoute/components/routeJson.ts new file mode 100644 index 00000000..a1b9fde1 --- /dev/null +++ b/zlt-web/react-web-next/src/pages/device/BoatRoute/components/routeJson.ts @@ -0,0 +1,72 @@ +import type { BoatRoutePayload, BoatWaypoint, BoatWaypointAction } from '@/services/boatRoute'; + +const toNumber = (value: any, fallback?: number) => { + if (value === undefined || value === null || value === '') return fallback; + const num = Number(value); + return Number.isFinite(num) ? num : fallback; +}; + +const normalizeAction = (action: any): BoatWaypointAction => ({ + actionType: action?.actionType, + duration: toNumber(action?.duration, 0), + params: action?.params ?? undefined, +}); + +export const normalizeWaypoint = (waypoint: any, index: number): BoatWaypoint => ({ + waypointId: waypoint?.waypointId, + waypointIndex: toNumber(waypoint?.waypointIndex, index), + longitude: toNumber(waypoint?.longitude), + latitude: toNumber(waypoint?.latitude), + speed: toNumber(waypoint?.speed), + stayDuration: toNumber(waypoint?.stayDuration, 0), + headingAngle: toNumber(waypoint?.headingAngle), + turnMode: waypoint?.turnMode || 'smooth', + isKeyPoint: Boolean(waypoint?.isKeyPoint), + pointName: waypoint?.pointName || `航点${index + 1}`, + actions: Array.isArray(waypoint?.actions) ? waypoint.actions.map(normalizeAction) : [], + remark: waypoint?.remark || undefined, +}); + +export const parseBoatRouteJson = (jsonText: string, routeName: string): BoatRoutePayload => { + const source = JSON.parse(jsonText); + const waypoints = Array.isArray(source?.waypoints) + ? source.waypoints.map((item: any, index: number) => normalizeWaypoint(item, index)) + : []; + + if (!waypoints.length) { + throw new Error('JSON 文件中未找到 waypoints 数组'); + } + + const invalidIndex = waypoints.findIndex((item: BoatWaypoint) => item.longitude === undefined || item.latitude === undefined); + if (invalidIndex >= 0) { + throw new Error(`第 ${invalidIndex + 1} 个航点缺少经纬度`); + } + + return { + routeName, + deviceSn: source?.deviceSn, + scenicId: toNumber(source?.scenicId), + cruiseSpeed: toNumber(source?.cruiseSpeed, 2), + loopEnabled: Boolean(source?.loopEnabled), + loopCount: toNumber(source?.loopCount, 1), + returnMode: source?.returnMode || 'return_start', + safeDistance: toNumber(source?.safeDistance, 5), + boundaryId: source?.boundaryId, + remark: source?.remark, + showInModel: toNumber(source?.showInModel, 0), + waypoints, + }; +}; + +export const buildUpdatePayload = (detail: any, waypoints: BoatWaypoint[]): Partial => ({ + routeName: detail.routeName, + cruiseSpeed: toNumber(detail.cruiseSpeed, 2), + loopEnabled: Boolean(detail.loopEnabled), + loopCount: toNumber(detail.loopCount, 1), + returnMode: detail.returnMode || 'return_start', + safeDistance: toNumber(detail.safeDistance, 5), + boundaryId: detail.boundaryId, + remark: detail.remark, + showInModel: toNumber(detail.showInModel, 0), + waypoints: waypoints.map((item, index) => normalizeWaypoint(item, index)), +}); diff --git a/zlt-web/react-web-next/src/pages/device/BoatRoute/index.tsx b/zlt-web/react-web-next/src/pages/device/BoatRoute/index.tsx new file mode 100644 index 00000000..42c38469 --- /dev/null +++ b/zlt-web/react-web-next/src/pages/device/BoatRoute/index.tsx @@ -0,0 +1,186 @@ +import React, { useRef, useState } from 'react'; +import { + PageContainer, + ProFormDateTimeRangePicker, + ProFormText, + ProTable, + type ActionType, + type ProColumns, +} from '@ant-design/pro-components'; +import { Modal, Space, Tag, message } from 'antd'; +import { PlusOutlined } from '@ant-design/icons'; +import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui'; +import { boatRouteApi, type BoatRouteItem, type BoatRoutePayload } from '@/services/boatRoute'; +import BoatRouteCreateModal from './components/BoatRouteCreateModal'; +import BoatRouteEditModal from './components/BoatRouteEditModal'; + +const BoatRoutePage: React.FC = () => { + const actionRef = useRef(); + const [query, setQuery] = useState>({}); + const [createOpen, setCreateOpen] = useState(false); + const [editOpen, setEditOpen] = useState(false); + const [currentRouteId, setCurrentRouteId] = useState(); + + const add = async (values: BoatRoutePayload) => { + const hide = message.loading('保存中...'); + try { + await boatRouteApi.create(values); + message.success('新增成功'); + actionRef.current?.reload(); + return true; + } catch { + message.error('新增失败'); + return false; + } finally { + hide(); + } + }; + + const edit = async (routeId: string, values: Partial) => { + const hide = message.loading('保存中...'); + try { + await boatRouteApi.update(routeId, values); + message.success('修改成功'); + actionRef.current?.reload(); + return true; + } catch { + message.error('修改失败'); + return false; + } finally { + hide(); + } + }; + + const del = (record: BoatRouteItem) => { + Modal.confirm({ + title: `确认删除航线 [${record.routeName || '--'}]?`, + content: '删除后该航线及其航点数据将不可继续使用。', + onOk: async () => { + const hide = message.loading('正在删除...'); + try { + await boatRouteApi.remove(record.routeId); + message.success('删除成功'); + actionRef.current?.reload(); + } catch { + message.error('删除失败'); + } finally { + hide(); + } + }, + }); + }; + + const columns: ProColumns[] = [ + { dataIndex: 'index', valueType: 'indexBorder', width: 48 }, + { + title: '航线名称', + dataIndex: 'routeName', + ellipsis: true, + render: (_, record) => record.routeName || '--', + }, + { title: '设备 SN', dataIndex: 'deviceSn', copyable: true, ellipsis: true }, + { title: '设备名称', dataIndex: 'deviceName', ellipsis: true }, + { title: '航点数', dataIndex: 'waypointCount', width: 90 }, + { title: '总航程(m)', dataIndex: 'totalDistance', width: 110 }, + { title: '预计时长', dataIndex: 'totalDurationStr', width: 120 }, + { + title: '巡航速度', + dataIndex: 'cruiseSpeed', + width: 100, + render: (_, record) => (record.cruiseSpeed ? `${record.cruiseSpeed} m/s` : '--'), + }, + { + title: '状态', + dataIndex: 'statusDesc', + width: 110, + render: (_, record) => ( + + {record.statusDesc || record.status || '未知'} + + ), + }, + { title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', width: 180 }, + { + title: '操作', + key: 'action', + valueType: 'option', + width: 130, + fixed: 'right', + render: (_, record) => ( + + { + setCurrentRouteId(record.routeId); + setEditOpen(true); + }} + > + 编辑 + + del(record)}> + 删除 + + + ), + }, + ]; + + return ( + + actionRef.current?.reload()} + onFinish={async (values) => setQuery(values)} + > + + + + + + } + onClick={() => setCreateOpen(true)} + > + 新增航线 + + } + /> + + + + rowKey="routeId" + headerTitle="航线列表" + actionRef={actionRef} + request={(params) => boatRouteApi.page({ ...params, ...query })} + columns={columns} + search={false} + scroll={{ x: 1300 }} + pagination={{ showSizeChanger: true, showQuickJumper: true }} + /> + + + + { + setEditOpen(visible); + if (!visible) setCurrentRouteId(undefined); + }} + onFinish={edit} + /> + + ); +}; + +export default BoatRoutePage; diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useTilesetLoader.ts b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useTilesetLoader.ts index f9f87898..c0c405f7 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useTilesetLoader.ts +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useTilesetLoader.ts @@ -1,6 +1,6 @@ /** * 3D Tiles 倾斜摄影模型加载器 Hook - * 用于加载大疆建图等工具生成的3D Tiles模型 + * 用于加载大疆建图等工具生成的 3D Tiles 模型 */ import { useState, useCallback, useRef } from 'react'; @@ -8,26 +8,26 @@ import { useState, useCallback, useRef } from 'react'; export interface TilesetConfig { id: string; // 模型唯一标识 name: string; // 模型名称 - url: string; // tileset.json 的URL地址 - tourismId?: number; // 关联的景区ID + url: string; // tileset.json 的 URL 地址 + tourismId?: number; // 关联的景区 ID position?: { // 模型位置调整 longitude?: number; // 经度偏移 latitude?: number; // 纬度偏移 height?: number; // 高度偏移(通用) - cesiumHeight?: number; // Cesium Ion地形对应的高度偏移 - arcgisHeight?: number; // ArcGIS地形对应的高度偏移 + cesiumHeight?: number; // Cesium Ion 地形对应的高度偏移 + arcgisHeight?: number; // ArcGIS 地形对应的高度偏移 terrainType?: string; // 高度标定时使用的地形服务: cesium_ion/arcgis/ellipsoid }; transform?: { // 模型变换 scale?: number; // 缩放比例 - rotationX?: number; // X轴旋转(弧度) - rotationY?: number; // Y轴旋转 - rotationZ?: number; // Z轴旋转 + rotationX?: number; // X 轴旋转(弧度) + rotationY?: number; // Y 轴旋转 + rotationZ?: number; // Z 轴旋转 }; style?: { // 渲染样式 - maximumScreenSpaceError?: number; // LOD精度控制(默认16) + maximumScreenSpaceError?: number; // LOD 精度控制(默认16) maximumMemoryUsage?: number; // 最大内存使用(MB) - skipLevelOfDetail?: boolean; // 是否跳过LOD + skipLevelOfDetail?: boolean; // 是否跳过 LOD preferLeaves?: boolean; // 优先加载叶子节点 }; visible?: boolean; // 是否可见 @@ -42,7 +42,7 @@ export interface TilesetState { tileset?: any; // Cesium3DTileset 实例 } -// Hook返回类型 +// Hook 返回类型 export interface UseTilesetLoaderResult { tilesets: Map; loadTileset: (config: TilesetConfig, viewer: any, Cesium: any, currentTerrainType?: string) => Promise; @@ -58,10 +58,10 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { const tilesetsRef = useRef>(new Map()); /** - * 加载3D Tiles模型 + * 加载 3D Tiles 模型 * @param config 模型配置 - * @param viewer Cesium Viewer实例 - * @param Cesium Cesium模块 + * @param viewer Cesium Viewer 实例 + * @param Cesium Cesium 模块 * @param currentTerrainType 当前使用的地形类型,用于选择对应的高度偏移 */ const loadTileset = useCallback(async ( @@ -71,7 +71,7 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { currentTerrainType?: string ): Promise => { if (!viewer || !Cesium) { - console.error('Viewer或Cesium未初始化'); + console.error('Viewer 或 Cesium 未初始化'); return null; } @@ -81,7 +81,7 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { return tilesetsRef.current.get(config.id); } - // 更新状态为loading + // 更新状态为 loading setTilesets(prev => { const newMap = new Map(prev); newMap.set(config.id, { @@ -101,13 +101,13 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { console.log('[Tileset] 使用代理路径:', tilesetUrl); } - // 创建3DTileset - 高清晰度渲染配置 + // 创建 3D Tileset - 高清晰度渲染配置 const tileset = await Cesium.Cesium3DTileset.fromUrl(tilesetUrl, { // 核心清晰度控制 - 值越小越清晰(大疆司空使用约1-2) maximumScreenSpaceError: config.style?.maximumScreenSpaceError ?? 1, maximumMemoryUsage: config.style?.maximumMemoryUsage ?? 2048, // 增加内存以加载更多高精度瓦片 - // 禁用LOD跳跃以获得更好的清晰度 + // 禁用 LOD 跳跃以获得更好的清晰度 skipLevelOfDetail: config.style?.skipLevelOfDetail ?? false, preferLeaves: config.style?.preferLeaves ?? true, @@ -229,7 +229,7 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { // 存储引用 tilesetsRef.current.set(config.id, tileset); - // 更新状态为loaded + // 更新状态为 loaded setTilesets(prev => { const newMap = new Map(prev); newMap.set(config.id, { @@ -241,11 +241,11 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { return newMap; }); - console.log(`3D Tiles模型 [${config.name}] 加载成功`); + console.log(`3D Tiles 模型 [${config.name}] 加载成功`); return tileset; } catch (error: any) { - console.error(`3D Tiles模型 [${config.name}] 加载失败:`, error); + console.error(`3D Tiles 模型 [${config.name}] 加载失败:`, error); setTilesets(prev => { const newMap = new Map(prev); @@ -287,13 +287,13 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { const unloadAllTilesets = useCallback((viewer: any) => { if (!viewer) return; - tilesetsRef.current.forEach((tileset, id) => { + tilesetsRef.current.forEach((tileset) => { viewer.scene.primitives.remove(tileset); }); tilesetsRef.current.clear(); setTilesets(new Map()); - console.log('所有3D Tiles模型已卸载'); + console.log('所有 3D Tiles 模型已卸载'); }, []); /** @@ -304,14 +304,12 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { if (!tileset || !viewer || !Cesium) return; const boundingSphere = tileset.boundingSphere; - const center = boundingSphere.center; const radius = boundingSphere.radius; - // 计算合适的观察距离 const offset = new Cesium.HeadingPitchRange( - Cesium.Math.toRadians(0), // heading - Cesium.Math.toRadians(-45), // pitch (45度俯视) - radius * 2.5 // 距离 + Cesium.Math.toRadians(0), + Cesium.Math.toRadians(-45), + radius * 2.5 ); viewer.camera.flyToBoundingSphere(boundingSphere, { @@ -337,7 +335,6 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { const tileset = tilesetsRef.current.get(id); if (!tileset || !Cesium) return; - // 示例: 设置建筑颜色 tileset.style = new Cesium.Cesium3DTileStyle({ color: style.color || "color('white')", show: style.show !== false, diff --git a/zlt-web/react-web-next/src/services/boatRoute.ts b/zlt-web/react-web-next/src/services/boatRoute.ts new file mode 100644 index 00000000..f4bef97f --- /dev/null +++ b/zlt-web/react-web-next/src/services/boatRoute.ts @@ -0,0 +1,134 @@ +import { request } from 'umi'; + +export interface BoatWaypointAction { + actionType?: string; + duration?: number; + params?: any; +} + +export interface BoatWaypoint { + waypointId?: string; + waypointIndex?: number; + longitude?: number; + latitude?: number; + speed?: number; + stayDuration?: number; + headingAngle?: number; + turnMode?: string; + isKeyPoint?: boolean; + pointName?: string; + actions?: BoatWaypointAction[] | null; + remark?: string; +} + +export interface BoatRouteItem { + routeId: string; + routeName: string; + deviceSn?: string; + deviceName?: string; + waypointCount?: number; + totalDistance?: number; + totalDurationStr?: string; + cruiseSpeed?: number; + status?: number; + statusDesc?: string; + isTemplate?: boolean; + showInModel?: number; + boundaryId?: string; + routeFileUrl?: string; + createTime?: string; +} + +export interface BoatRouteDetail extends BoatRouteItem { + scenicId?: number; + totalDuration?: number; + loopEnabled?: boolean; + loopCount?: number; + returnMode?: string; + safeDistance?: number; + startPoint?: string; + endPoint?: string; + remark?: string; + waypoints?: BoatWaypoint[]; + updateTime?: string; +} + +export interface BoatRoutePayload { + routeName: string; + deviceSn?: string; + scenicId?: number; + cruiseSpeed?: number; + loopEnabled?: boolean; + loopCount?: number; + returnMode?: string; + safeDistance?: number; + boundaryId?: string; + remark?: string; + showInModel?: number; + waypoints: BoatWaypoint[]; +} + +const unwrapData = (res: any) => res?.data ?? res; + +const normalizeRouteItem = (item: any): BoatRouteItem => ({ + routeId: item?.routeId ?? item?.route_id ?? '', + routeName: item?.routeName ?? item?.route_name ?? item?.name ?? '', + deviceSn: item?.deviceSn ?? item?.device_sn, + deviceName: item?.deviceName ?? item?.device_name, + waypointCount: item?.waypointCount ?? item?.waypoint_count, + totalDistance: item?.totalDistance ?? item?.total_distance, + totalDurationStr: item?.totalDurationStr ?? item?.total_duration_str, + cruiseSpeed: item?.cruiseSpeed ?? item?.cruise_speed, + status: item?.status, + statusDesc: item?.statusDesc ?? item?.status_desc, + isTemplate: item?.isTemplate ?? item?.is_template, + showInModel: item?.showInModel ?? item?.show_in_model, + boundaryId: item?.boundaryId ?? item?.boundary_id, + routeFileUrl: item?.routeFileUrl ?? item?.route_file_url, + createTime: item?.createTime ?? item?.create_time, +}); + +export const boatRouteApi = { + page: async (params: { current?: number; pageSize?: number; createTimeRange?: string[]; [key: string]: any }) => { + const { current, pageSize, createTimeRange, ...rest } = params || {}; + const [startTime, endTime] = createTimeRange || []; + const res = await request('/api-device/device/boat/route/page', { + method: 'GET', + params: { + page: current, + size: pageSize, + startTime, + endTime, + ...rest, + }, + }); + const pageData = unwrapData(res); + return { + data: (pageData?.records || []).map(normalizeRouteItem), + total: pageData?.total || 0, + } as { data: BoatRouteItem[]; total: number }; + }, + + detail: async (routeId: string) => { + const res = await request(`/api-device/device/boat/route/${routeId}`, { method: 'GET' }); + return { + ...unwrapData(res), + ...normalizeRouteItem(unwrapData(res)), + } as BoatRouteDetail; + }, + + create: async (data: BoatRoutePayload) => { + const res = await request('/api-device/device/boat/route/create', { method: 'POST', data }); + return unwrapData(res) as string; + }, + + update: async (routeId: string, data: Partial) => { + const res = await request(`/api-device/device/boat/route/${routeId}`, { method: 'PUT', data }); + return unwrapData(res); + }, + + remove: async (routeId: string) => { + const res = await request(`/api-device/device/boat/route/${routeId}`, { method: 'DELETE' }); + return unwrapData(res); + }, +}; diff --git a/zlt-web/yingyan/src/pages/client/components/CenterView/index.tsx b/zlt-web/yingyan/src/pages/client/components/CenterView/index.tsx index 86247115..d134f9f1 100644 --- a/zlt-web/yingyan/src/pages/client/components/CenterView/index.tsx +++ b/zlt-web/yingyan/src/pages/client/components/CenterView/index.tsx @@ -1,4 +1,4 @@ -import React, { useCallback, useEffect, useRef, useState } from 'react'; +import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { App } from 'antd'; import { useTilesetLoader } from '@/pages/map3d/components/MapContainer/3d/hooks/useTilesetLoader'; import { useCesiumRouteLibraryRenderer } from '@/pages/map3d/components/RouteEditor/hooks/useCesiumRouteLibraryRenderer'; @@ -27,6 +27,22 @@ interface CenterViewProps { const ACTUAL_TRACK_ID = 'client-actual-track'; +const toFiniteNumber = (value: unknown): number | undefined => { + if (value === null || value === undefined || value === '') return undefined; + const numeric = Number(value); + return Number.isFinite(numeric) ? numeric : undefined; +}; + +const getBoatPosition = (data: BoatTelemetryData | null) => { + const longitude = toFiniteNumber((data as any)?.longitude); + const latitude = toFiniteNumber((data as any)?.latitude); + if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return null; + if (Math.abs(longitude!) > 180 || Math.abs(latitude!) > 90) return null; + // 设备未上报 GPS 时常见默认值为 0,0,客户端不显示船位。 + if (longitude === 0 && latitude === 0) return null; + return { longitude: longitude!, latitude: latitude! }; +}; + const CenterView: React.FC = ({ deviceSn, routes, @@ -68,7 +84,8 @@ const CenterView: React.FC = ({ getRouteSurfaceGeometry, }); - const hasBoatPosition = Number.isFinite(boatData?.longitude) && Number.isFinite(boatData?.latitude); + const boatPosition = useMemo(() => getBoatPosition(boatData), [boatData?.longitude, boatData?.latitude]); + const hasBoatPosition = !!boatPosition; useEffect(() => { onPreviewChange?.(isPreviewing); @@ -148,7 +165,9 @@ const CenterView: React.FC = ({ if (!Cesium || !viewerRef.current || viewerRef.current.isDestroyed?.()) return; if (!hasBoatPosition || isPreviewing || isSailing) return; - const position = resolveBoatWorldPosition(boatData!.longitude, boatData!.latitude); + if (!boatPosition) return; + + const position = resolveBoatWorldPosition(boatPosition.longitude, boatPosition.latitude); if (!position) return; try { @@ -166,7 +185,7 @@ const CenterView: React.FC = ({ } catch { // 忽略相机异常 } - }, [boatData, hasBoatPosition, isPreviewing, isSailing, resolveBoatWorldPosition]); + }, [boatPosition, hasBoatPosition, isPreviewing, isSailing, resolveBoatWorldPosition]); const flyToModelOverview = useCallback((duration = 1.2) => { if (!Cesium || !viewerRef.current || viewerRef.current.isDestroyed?.()) return; @@ -624,7 +643,9 @@ const CenterView: React.FC = ({ return; } - const liftedPosition = resolveBoatWorldPosition(boatData!.longitude, boatData!.latitude); + if (!boatPosition) return; + + const liftedPosition = resolveBoatWorldPosition(boatPosition.longitude, boatPosition.latitude); if (!liftedPosition) return; const headingRad = Cesium.Math.toRadians(boatData?.heading || 0); @@ -679,7 +700,7 @@ const CenterView: React.FC = ({ } viewer.scene.requestRender?.(); - }, [viewerReady, boatData, hasBoatPosition, isPreviewing, resolveBoatWorldPosition]); + }, [viewerReady, boatData?.heading, boatPosition, hasBoatPosition, isPreviewing, resolveBoatWorldPosition]); useEffect(() => { if (!viewerReady || !Cesium) return; @@ -695,24 +716,24 @@ const CenterView: React.FC = ({ } }; - if (!isSailing || !selectedRouteId) { + if (isPreviewing) { activeTrackRouteRef.current = null; clearTrack(); return; } - if (activeTrackRouteRef.current !== selectedRouteId) { - activeTrackRouteRef.current = selectedRouteId; + if (activeTrackRouteRef.current !== deviceSn) { + activeTrackRouteRef.current = deviceSn; clearTrack(); } - }, [viewerReady, isSailing, selectedRouteId]); + }, [viewerReady, deviceSn, isPreviewing]); useEffect(() => { - if (!viewerReady || !Cesium || !isSailing || isPreviewing || !hasBoatPosition) return; + if (!viewerReady || !Cesium || isPreviewing || !hasBoatPosition || !boatPosition) return; const viewer = viewerRef.current; if (!viewer || viewer.isDestroyed?.()) return; - const position = Cesium.Cartesian3.fromDegrees(boatData!.longitude, boatData!.latitude, 0); + const position = Cesium.Cartesian3.fromDegrees(boatPosition.longitude, boatPosition.latitude, 0); const lastPosition = trackPositionsRef.current[trackPositionsRef.current.length - 1]; if (!lastPosition || Cesium.Cartesian3.distance(lastPosition, position) > 0.3) { trackPositionsRef.current.push(position); @@ -723,7 +744,7 @@ const CenterView: React.FC = ({ } let trackEntity = viewer.entities.getById(ACTUAL_TRACK_ID); - if (!trackEntity) { + if (!trackEntity && trackPositionsRef.current.length >= 2) { trackEntity = viewer.entities.add({ id: ACTUAL_TRACK_ID, polyline: { @@ -739,7 +760,7 @@ const CenterView: React.FC = ({ } viewer.scene.requestRender?.(); - }, [viewerReady, boatData, hasBoatPosition, isSailing, isPreviewing]); + }, [viewerReady, boatPosition, hasBoatPosition, isPreviewing]); return (
@@ -779,7 +800,7 @@ const CenterView: React.FC = ({ 当前坐标: {hasBoatPosition - ? ` ${boatData!.longitude.toFixed(4)}°E, ${boatData!.latitude.toFixed(4)}°N` + ? ` ${boatPosition!.longitude.toFixed(4)}°E, ${boatPosition!.latitude.toFixed(4)}°N` : ' --'} | diff --git a/zlt-web/yingyan/src/pages/client/components/RightPanel/index.tsx b/zlt-web/yingyan/src/pages/client/components/RightPanel/index.tsx index c902e420..b113b8ad 100644 --- a/zlt-web/yingyan/src/pages/client/components/RightPanel/index.tsx +++ b/zlt-web/yingyan/src/pages/client/components/RightPanel/index.tsx @@ -15,10 +15,26 @@ interface RightPanelProps { sseConnected: boolean; } +const toFiniteNumber = (value: unknown): number | undefined => { + if (value === null || value === undefined || value === '') return undefined; + const numeric = Number(value); + return Number.isFinite(numeric) ? numeric : undefined; +}; + +const getBoatPosition = (data: BoatTelemetryData | null) => { + const longitude = toFiniteNumber((data as any)?.longitude); + const latitude = toFiniteNumber((data as any)?.latitude); + if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return null; + if (Math.abs(longitude!) > 180 || Math.abs(latitude!) > 90) return null; + if (longitude === 0 && latitude === 0) return null; + return { longitude: longitude!, latitude: latitude! }; +}; + 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 boatPosition = useMemo(() => getBoatPosition(boatData), [boatData?.longitude, boatData?.latitude]); const [targetSpeed, setTargetSpeed] = useState(5); const activeCommandRef = useRef(null); @@ -219,8 +235,8 @@ const RightPanel: React.FC = ({ deviceInfo, boatData, sseConnec
GPS - {boatData?.longitude != null - ? `${boatData.longitude.toFixed(4)}, ${boatData.latitude?.toFixed(4)}` + {boatPosition + ? `${boatPosition.longitude.toFixed(4)}, ${boatPosition.latitude.toFixed(4)}` : '--'}
diff --git a/zlt-web/yingyan/src/pages/client/hooks/useClientSSE.ts b/zlt-web/yingyan/src/pages/client/hooks/useClientSSE.ts index cfea77ff..166e8c26 100644 --- a/zlt-web/yingyan/src/pages/client/hooks/useClientSSE.ts +++ b/zlt-web/yingyan/src/pages/client/hooks/useClientSSE.ts @@ -7,6 +7,42 @@ import type { BoatTelemetryData } from '@/types/boatRoute'; const IDLE_TIMEOUT_MS = 30 * 60 * 1000; +const toFiniteNumber = (value: unknown): number | undefined => { + if (value === null || value === undefined || value === '') return undefined; + const numeric = Number(value); + return Number.isFinite(numeric) ? numeric : undefined; +}; + +const isValidCoordinate = (longitude?: number, latitude?: number) => { + if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return false; + if (Math.abs(longitude!) > 180 || Math.abs(latitude!) > 90) return false; + // 设备未上报 GPS 时常见默认值为 0,0,客户端不应把船显示到几内亚湾。 + return !(longitude === 0 && latitude === 0); +}; + +const normalizeTelemetryData = (rawData: any, deviceSn: string): BoatTelemetryData => { + const longitude = toFiniteNumber( + rawData?.longitude ?? rawData?.lng ?? rawData?.lon ?? rawData?.gps?.longitude ?? rawData?.position?.longitude, + ); + const latitude = toFiniteNumber( + rawData?.latitude ?? rawData?.lat ?? rawData?.gps?.latitude ?? rawData?.position?.latitude, + ); + const hasValidPosition = isValidCoordinate(longitude, latitude); + + return { + ...rawData, + deviceSn: rawData?.deviceSn || deviceSn, + longitude: hasValidPosition ? longitude : undefined, + latitude: hasValidPosition ? latitude : undefined, + heading: toFiniteNumber(rawData?.heading ?? rawData?.direction ?? rawData?.yaw) ?? 0, + speed: toFiniteNumber(rawData?.speed) ?? 0, + battery: toFiniteNumber(rawData?.battery ?? rawData?.batteryPercent) ?? 0, + signalStrength: toFiniteNumber(rawData?.signalStrength), + status: rawData?.status ?? rawData?.deviceStatus ?? '', + recordTime: rawData?.recordTime ?? new Date().toISOString(), + } as BoatTelemetryData; +}; + export interface UseClientSSEReturn { boatData: BoatTelemetryData | null; sseConnected: boolean; @@ -135,12 +171,14 @@ export const useClientSSE = (): UseClientSSEReturn => { const decoder = new TextDecoder(); let buffer = ''; + let currentEvent = 'message'; + let currentData = ''; const handleSSEEvent = (eventName: string, data: string) => { if (eventName === 'boat-telemetry') { try { - const parsed = JSON.parse(data) as BoatTelemetryData; - setBoatData(parsed); + const parsed = JSON.parse(data); + setBoatData(normalizeTelemetryData(parsed, deviceSn)); } catch (e) { console.warn('[ClientSSE] 解析遥测数据失败:', e); } @@ -164,14 +202,13 @@ export const useClientSSE = (): UseClientSSEReturn => { const lines = buffer.split('\n'); buffer = lines.pop() || ''; - let currentEvent = 'message'; - let currentData = ''; - - for (const line of lines) { + for (const rawLine of lines) { + const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine; if (line.startsWith('event:')) { currentEvent = line.substring(6).trim(); } else if (line.startsWith('data:')) { - currentData = line.substring(5).trim(); + const lineData = line.substring(5).trim(); + currentData = currentData ? `${currentData}\n${lineData}` : lineData; } else if (line === '') { if (currentData) { handleSSEEvent(currentEvent, currentData);