feat:添加无人船航线管理页面
This commit is contained in:
@@ -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模型管理
|
||||
|
||||
+115
@@ -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<boolean>;
|
||||
}
|
||||
|
||||
const readFileText = (file: File) =>
|
||||
new Promise<string>((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<BoatRouteCreateModalProps> = ({ visible, onVisibleChange, onFinish }) => {
|
||||
const [fileList, setFileList] = useState<UploadFile[]>([]);
|
||||
const [parsedPayload, setParsedPayload] = useState<BoatRoutePayload | null>(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 (
|
||||
<ModalForm<{ routeName: string }>
|
||||
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;
|
||||
}}
|
||||
>
|
||||
<ProFormText
|
||||
name="routeName"
|
||||
label="航线名称"
|
||||
placeholder="请输入航线名称"
|
||||
rules={[{ required: true, message: '请输入航线名称' }]}
|
||||
fieldProps={{
|
||||
value: routeName,
|
||||
onChange: (event) => {
|
||||
setRouteName(event.target.value);
|
||||
setParsedPayload(null);
|
||||
setFileList([]);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
|
||||
<Upload accept=".json,application/json" maxCount={1} fileList={fileList} beforeUpload={handleFile} onRemove={() => {
|
||||
setParsedPayload(null);
|
||||
setFileList([]);
|
||||
}}>
|
||||
<Button icon={<UploadOutlined />}>选择航线 JSON 文件</Button>
|
||||
</Upload>
|
||||
|
||||
<Alert style={{ marginTop: 16 }} type="info" showIcon message="上传示例结构可参考后端 doc/waypoints.json,系统会读取 waypoints、设备 SN、巡航速度、循环设置等字段。" />
|
||||
|
||||
{parsedPayload && (
|
||||
<Descriptions size="small" column={2} bordered style={{ marginTop: 16 }}>
|
||||
<Descriptions.Item label="设备 SN">{parsedPayload.deviceSn || '--'}</Descriptions.Item>
|
||||
<Descriptions.Item label="航点数量">{parsedPayload.waypoints.length}</Descriptions.Item>
|
||||
<Descriptions.Item label="巡航速度">{parsedPayload.cruiseSpeed ?? '--'} m/s</Descriptions.Item>
|
||||
<Descriptions.Item label="安全距离">{parsedPayload.safeDistance ?? '--'} m</Descriptions.Item>
|
||||
<Descriptions.Item label="循环航行">{parsedPayload.loopEnabled ? '是' : '否'}</Descriptions.Item>
|
||||
<Descriptions.Item label="结束动作">{parsedPayload.returnMode || '--'}</Descriptions.Item>
|
||||
</Descriptions>
|
||||
)}
|
||||
|
||||
<Space style={{ display: 'none' }} />
|
||||
</ModalForm>
|
||||
);
|
||||
};
|
||||
|
||||
export default BoatRouteCreateModal;
|
||||
@@ -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<BoatRoutePayload>) => Promise<boolean>;
|
||||
}
|
||||
|
||||
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<BoatRouteEditModalProps> = ({ 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<BoatRouteDetail | null>(null);
|
||||
const [waypoints, setWaypoints] = useState<BoatWaypoint[]>([]);
|
||||
const [waypointOpen, setWaypointOpen] = useState(false);
|
||||
const [editingWaypointIndex, setEditingWaypointIndex] = useState<number | null>(null);
|
||||
const [actionOpen, setActionOpen] = useState(false);
|
||||
const [editingActionIndex, setEditingActionIndex] = useState<number | null>(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<BoatWaypoint> = [
|
||||
{ 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) => (
|
||||
<Space>
|
||||
<a onClick={() => openWaypoint(record, index)}><EditOutlined /> 编辑</a>
|
||||
<a style={{ color: '#ff4d4f' }} onClick={() => removeWaypoint(index)}><DeleteOutlined /> 删除</a>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const actionColumns: ColumnsType<any> = [
|
||||
{ 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) => (
|
||||
<Space>
|
||||
<a onClick={() => openAction(record, index)}>编辑</a>
|
||||
<a style={{ color: '#ff4d4f' }} onClick={() => removeAction(index)}>删除</a>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<ModalForm
|
||||
form={form}
|
||||
title="编辑无人船航线"
|
||||
visible={visible}
|
||||
width={1100}
|
||||
modalProps={{ destroyOnClose: true }}
|
||||
onVisibleChange={(nextVisible) => {
|
||||
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);
|
||||
}}
|
||||
>
|
||||
<Tabs defaultActiveKey="base">
|
||||
<Tabs.TabPane tab="基础信息" key="base">
|
||||
{loading ? <Card loading size="small" /> : null}
|
||||
<ProFormText name="routeName" label="航线名称" rules={[{ required: true, message: '请输入航线名称' }]} />
|
||||
<ProFormDigit name="cruiseSpeed" label="巡航速度(m/s)" min={0.1} fieldProps={{ precision: 2 }} />
|
||||
<ProFormSwitch name="loopEnabled" label="循环航行" />
|
||||
<ProFormDigit name="loopCount" label="循环次数" min={-1} />
|
||||
<ProFormSelect name="returnMode" label="结束动作" options={RETURN_MODE_OPTIONS} />
|
||||
<ProFormDigit name="safeDistance" label="安全距离(米)" min={0} fieldProps={{ precision: 2 }} />
|
||||
<ProFormSelect name="showInModel" label="模型中显示" options={[{ label: '否', value: 0 }, { label: '是', value: 1 }]} />
|
||||
<ProFormText name="boundaryId" label="水域边界ID" />
|
||||
<ProFormTextArea name="remark" label="备注" />
|
||||
</Tabs.TabPane>
|
||||
|
||||
<Tabs.TabPane tab={`航点与动作(${waypoints.length})`} key="waypoints">
|
||||
<Card
|
||||
size="small"
|
||||
title={<Space>航点列表<Tag color="blue">{waypoints.length} 个航点</Tag></Space>}
|
||||
extra={<Button type="primary" icon={<PlusOutlined />} onClick={() => openWaypoint()}>新增航点</Button>}
|
||||
>
|
||||
<Table
|
||||
rowKey={(record, index) => 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 ? (
|
||||
<Table rowKey={(_, index) => String(index)} columns={actionColumns.slice(0, 3)} dataSource={record.actions} pagination={false} size="small" />
|
||||
) : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无航点动作" />
|
||||
),
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
</Tabs.TabPane>
|
||||
</Tabs>
|
||||
</ModalForm>
|
||||
|
||||
<Modal title={editingWaypointIndex === null ? '新增航点' : '编辑航点'} visible={waypointOpen} width={820} onOk={saveWaypoint} onCancel={closeWaypoint} destroyOnClose>
|
||||
<Form form={waypointForm} layout="vertical">
|
||||
<Form.Item name="waypointIndex" label="航点序号"><InputNumber min={0} style={{ width: '100%' }} /></Form.Item>
|
||||
<Form.Item name="pointName" label="航点名称"><Input /></Form.Item>
|
||||
<Form.Item name="longitude" label="经度" rules={[{ required: true, message: '请输入经度' }]}><InputNumber precision={8} style={{ width: '100%' }} /></Form.Item>
|
||||
<Form.Item name="latitude" label="纬度" rules={[{ required: true, message: '请输入纬度' }]}><InputNumber precision={8} style={{ width: '100%' }} /></Form.Item>
|
||||
<Form.Item name="speed" label="速度(m/s)"><InputNumber min={0} precision={2} style={{ width: '100%' }} /></Form.Item>
|
||||
<Form.Item name="stayDuration" label="停留时间(秒)"><InputNumber min={0} style={{ width: '100%' }} /></Form.Item>
|
||||
<Form.Item name="turnMode" label="转弯模式"><ProFormSelect noStyle options={TURN_MODE_OPTIONS} /></Form.Item>
|
||||
<Form.Item name="isKeyPoint" label="关键点"><ProFormSwitch noStyle /></Form.Item>
|
||||
<Form.Item name="remark" label="备注"><Input.TextArea rows={2} /></Form.Item>
|
||||
<Form.Item name="actions" hidden><Input /></Form.Item>
|
||||
|
||||
<Collapse>
|
||||
<Collapse.Panel header={`航点动作(${currentActions.length})`} key="actions" extra={<Button size="small" type="link" icon={<PlusOutlined />} onClick={(event) => { event.stopPropagation(); openAction(); }}>新增动作</Button>}>
|
||||
<Table rowKey={(_, index) => String(index)} columns={actionColumns} dataSource={currentActions} pagination={false} size="small" />
|
||||
</Collapse.Panel>
|
||||
</Collapse>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal title={editingActionIndex === null ? '新增动作' : '编辑动作'} visible={actionOpen} onOk={saveAction} onCancel={() => setActionOpen(false)} destroyOnClose>
|
||||
<Form form={actionForm} layout="vertical">
|
||||
<Form.Item name="actionType" label="动作类型" rules={[{ required: true, message: '请选择动作类型' }]}>
|
||||
<ProFormSelect noStyle options={ACTION_TYPE_OPTIONS} />
|
||||
</Form.Item>
|
||||
<Form.Item name="duration" label="持续时间(秒)"><InputNumber min={0} style={{ width: '100%' }} /></Form.Item>
|
||||
<Form.Item name="paramsText" label="动作参数(JSON)"><Input.TextArea rows={5} placeholder='例如:{"volume":80}' /></Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default BoatRouteEditModal;
|
||||
@@ -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<BoatRoutePayload> => ({
|
||||
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)),
|
||||
});
|
||||
@@ -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<ActionType>();
|
||||
const [query, setQuery] = useState<Record<string, any>>({});
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [currentRouteId, setCurrentRouteId] = useState<string>();
|
||||
|
||||
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<BoatRoutePayload>) => {
|
||||
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<BoatRouteItem>[] = [
|
||||
{ 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) => (
|
||||
<Tag color={record.status === 1 ? 'green' : 'blue'}>
|
||||
{record.statusDesc || record.status || '未知'}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{ title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', width: 180 },
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
valueType: 'option',
|
||||
width: 130,
|
||||
fixed: 'right',
|
||||
render: (_, record) => (
|
||||
<Space>
|
||||
<a
|
||||
onClick={() => {
|
||||
setCurrentRouteId(record.routeId);
|
||||
setEditOpen(true);
|
||||
}}
|
||||
>
|
||||
编辑
|
||||
</a>
|
||||
<a style={{ color: '#ff4d4f' }} onClick={() => del(record)}>
|
||||
删除
|
||||
</a>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<PageContainer header={{ title: '无人船航线管理' }}>
|
||||
<SearchBarPlus
|
||||
defaultCollapsed
|
||||
split
|
||||
span={6}
|
||||
showTenant={false}
|
||||
onTenantChanged={() => actionRef.current?.reload()}
|
||||
onFinish={async (values) => setQuery(values)}
|
||||
>
|
||||
<ProFormText name="routeName" label="航线名称" />
|
||||
<ProFormText name="deviceSn" label="设备 SN" />
|
||||
<ProFormDateTimeRangePicker name="createTimeRange" label="创建时间" />
|
||||
</SearchBarPlus>
|
||||
|
||||
<ActionBar
|
||||
left={
|
||||
<GradientButton
|
||||
size="middle"
|
||||
type="primary"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() => setCreateOpen(true)}
|
||||
>
|
||||
新增航线
|
||||
</GradientButton>
|
||||
}
|
||||
/>
|
||||
|
||||
<GlassCard>
|
||||
<ProTable<BoatRouteItem>
|
||||
rowKey="routeId"
|
||||
headerTitle="航线列表"
|
||||
actionRef={actionRef}
|
||||
request={(params) => boatRouteApi.page({ ...params, ...query })}
|
||||
columns={columns}
|
||||
search={false}
|
||||
scroll={{ x: 1300 }}
|
||||
pagination={{ showSizeChanger: true, showQuickJumper: true }}
|
||||
/>
|
||||
</GlassCard>
|
||||
|
||||
<BoatRouteCreateModal
|
||||
visible={createOpen}
|
||||
onVisibleChange={setCreateOpen}
|
||||
onFinish={add}
|
||||
/>
|
||||
<BoatRouteEditModal
|
||||
visible={editOpen}
|
||||
routeId={currentRouteId}
|
||||
onVisibleChange={(visible) => {
|
||||
setEditOpen(visible);
|
||||
if (!visible) setCurrentRouteId(undefined);
|
||||
}}
|
||||
onFinish={edit}
|
||||
/>
|
||||
</PageContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default BoatRoutePage;
|
||||
+26
-29
@@ -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<string, TilesetState>;
|
||||
loadTileset: (config: TilesetConfig, viewer: any, Cesium: any, currentTerrainType?: string) => Promise<any>;
|
||||
@@ -58,10 +58,10 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
|
||||
const tilesetsRef = useRef<Map<string, any>>(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<any> => {
|
||||
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,
|
||||
|
||||
@@ -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<BoatRoutePayload>) => {
|
||||
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);
|
||||
},
|
||||
};
|
||||
@@ -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<CenterViewProps> = ({
|
||||
deviceSn,
|
||||
routes,
|
||||
@@ -68,7 +84,8 @@ const CenterView: React.FC<CenterViewProps> = ({
|
||||
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<CenterViewProps> = ({
|
||||
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<CenterViewProps> = ({
|
||||
} 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<CenterViewProps> = ({
|
||||
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<CenterViewProps> = ({
|
||||
}
|
||||
|
||||
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<CenterViewProps> = ({
|
||||
}
|
||||
};
|
||||
|
||||
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<CenterViewProps> = ({
|
||||
}
|
||||
|
||||
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<CenterViewProps> = ({
|
||||
}
|
||||
|
||||
viewer.scene.requestRender?.();
|
||||
}, [viewerReady, boatData, hasBoatPosition, isSailing, isPreviewing]);
|
||||
}, [viewerReady, boatPosition, hasBoatPosition, isPreviewing]);
|
||||
|
||||
return (
|
||||
<div className={styles.wrapper}>
|
||||
@@ -779,7 +800,7 @@ const CenterView: React.FC<CenterViewProps> = ({
|
||||
<span className={styles.mapBottomText}>
|
||||
当前坐标:
|
||||
{hasBoatPosition
|
||||
? ` ${boatData!.longitude.toFixed(4)}°E, ${boatData!.latitude.toFixed(4)}°N`
|
||||
? ` ${boatPosition!.longitude.toFixed(4)}°E, ${boatPosition!.latitude.toFixed(4)}°N`
|
||||
: ' --'}
|
||||
</span>
|
||||
<span className={styles.mapBottomSep}>|</span>
|
||||
|
||||
@@ -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<RightPanelProps> = ({ deviceInfo, boatData, sseConnected }) => {
|
||||
const heading = useMemo(() => boatData?.heading ?? 0, [boatData?.heading]);
|
||||
const speed = useMemo(() => boatData?.speed ?? 0, [boatData?.speed]);
|
||||
const battery = useMemo(() => boatData?.battery ?? 0, [boatData?.battery]);
|
||||
const boatPosition = useMemo(() => getBoatPosition(boatData), [boatData?.longitude, boatData?.latitude]);
|
||||
const [targetSpeed, setTargetSpeed] = useState(5);
|
||||
const activeCommandRef = useRef<string | null>(null);
|
||||
|
||||
@@ -219,8 +235,8 @@ const RightPanel: React.FC<RightPanelProps> = ({ deviceInfo, boatData, sseConnec
|
||||
<div className={styles.dataRow}>
|
||||
<span className={styles.dataLabel}>GPS</span>
|
||||
<span className={styles.dataValue}>
|
||||
{boatData?.longitude != null
|
||||
? `${boatData.longitude.toFixed(4)}, ${boatData.latitude?.toFixed(4)}`
|
||||
{boatPosition
|
||||
? `${boatPosition.longitude.toFixed(4)}, ${boatPosition.latitude.toFixed(4)}`
|
||||
: '--'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user