45 changed files with 4737 additions and 1226 deletions
+5
View File
@@ -16,3 +16,8 @@ zlt-web/react-web-next/public/cesium/
zlt-web/yingyan/public/cesium/ zlt-web/yingyan/public/cesium/
zlt-web/react-web-next/dist.zip
zlt-web/yingyan/dist.zip
@@ -49,7 +49,7 @@ public class BoatCommandManager {
* 发送命令 * 发送命令
* *
* @param deviceSn 设备SN * @param deviceSn 设备SN
* @param commandType 命令类型(flighttask_prepare/flighttask_pause/flighttask_recovery/flighttask_undo) * @param commandType 命令类型(flighttask_prepare/flighttask_pause/flighttask_recovery/flighttask_undo/flighttask_slowly)
* @param params 命令参数 * @param params 命令参数
* @return 命令ID * @return 命令ID
*/ */
@@ -187,6 +187,12 @@ public class BoatCommandManager {
} }
break; break;
case "flighttask_slowly":
// 慢速行驶
data.put("order_no", params.getString("order_no"));
data.put("speed", params.getInteger("speed"));
break;
default: default:
data = params; data = params;
break; break;
@@ -2,6 +2,7 @@ package com.central.device.controller;
import com.central.common.model.Result; import com.central.common.model.Result;
import com.central.device.model.dto.BoatManualControlDTO; import com.central.device.model.dto.BoatManualControlDTO;
import com.central.device.model.dto.BoatSlowlyDriveDTO;
import com.central.device.service.IBoatControlService; import com.central.device.service.IBoatControlService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
@@ -61,6 +62,15 @@ public class BoatCommandController {
return Result.succeed(null, "终止任务指令已下发"); return Result.succeed(null, "终止任务指令已下发");
} }
@Operation(summary = "慢速行驶")
@PostMapping("/slowly")
public Result<Void> slowly(
@Parameter(description = "设备SN") @RequestParam String deviceSn,
@RequestBody @Validated BoatSlowlyDriveDTO dto) {
boatControlService.slowly(deviceSn, dto);
return Result.succeed(null, "慢速行驶指令已下发");
}
@Operation(summary = "返回起点") @Operation(summary = "返回起点")
@PostMapping("/return") @PostMapping("/return")
public Result<Void> returnToStart( public Result<Void> returnToStart(
@@ -13,13 +13,23 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated; 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; import java.util.List;
/** /**
* 无人船航线管理Controller * 无人船航线管理 Controller
* *
* @author dzc * @author dzc
* @date 2026-01-05 * @date 2026-01-05
@@ -56,6 +66,21 @@ public class BoatRouteController {
return Result.succeed(detail); return Result.succeed(detail);
} }
@Operation(summary = "分页查询无人船航线列表")
@GetMapping("/page")
public Result<Page<BoatRouteListVO>> 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<BoatRouteListVO> pageResult = boatRouteService.pageRoutes(routeName, deviceSn, startTime, endTime, page, size);
return Result.succeed(pageResult);
}
@Operation(summary = "获取设备绑定的航线列表") @Operation(summary = "获取设备绑定的航线列表")
@GetMapping("/list/device/{deviceSn}") @GetMapping("/list/device/{deviceSn}")
public Result<List<BoatRouteListVO>> listByDeviceSn( public Result<List<BoatRouteListVO>> listByDeviceSn(
@@ -0,0 +1,25 @@
package com.central.device.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
/**
* 无人船慢速行驶DTO
*
* @author Codex
* @date 2026-04-20
*/
@Data
@Schema(description = "无人船慢速行驶请求")
public class BoatSlowlyDriveDTO {
@Schema(description = "任务编码(对应 order_no)", required = true, example = "562026040600002")
@NotBlank(message = "任务编码不能为空")
private String missionCode;
@Schema(description = "慢速行驶速度", required = true, example = "30")
@NotNull(message = "速度不能为空")
private Integer speed;
}
@@ -1,6 +1,7 @@
package com.central.device.service; package com.central.device.service;
import com.central.device.model.dto.BoatManualControlDTO; import com.central.device.model.dto.BoatManualControlDTO;
import com.central.device.model.dto.BoatSlowlyDriveDTO;
/** /**
* 无人船控制服务接口 * 无人船控制服务接口
@@ -44,6 +45,14 @@ public interface IBoatControlService {
*/ */
void undoTask(String deviceSn, String missionCode); void undoTask(String deviceSn, String missionCode);
/**
* 慢速行驶
*
* @param deviceSn 设备SN
* @param dto 慢速行驶参数
*/
void slowly(String deviceSn, BoatSlowlyDriveDTO dto);
/** /**
* 返回起点 * 返回起点
* *
@@ -9,6 +9,7 @@ import com.central.device.model.vo.BoatRouteDetailVO;
import com.central.device.model.vo.BoatRouteListVO; import com.central.device.model.vo.BoatRouteListVO;
import com.central.device.model.vo.RouteValidateResultVO; import com.central.device.model.vo.RouteValidateResultVO;
import java.time.LocalDateTime;
import java.util.List; import java.util.List;
/** /**
@@ -69,6 +70,20 @@ public interface IBoatRouteService extends IService<BoatRoute> {
*/ */
Page<BoatRouteListVO> listByScenicId(Long scenicId, Integer page, Integer size); Page<BoatRouteListVO> listByScenicId(Long scenicId, Integer page, Integer size);
/**
* 分页查询无人船航线列表
*
* @param routeName 航线名称
* @param deviceSn 设备SN
* @param startTime 创建开始时间
* @param endTime 创建结束时间
* @param page 页码
* @param size 每页数量
* @return 航线分页列表
*/
Page<BoatRouteListVO> pageRoutes(String routeName, String deviceSn, LocalDateTime startTime, LocalDateTime endTime,
Integer page, Integer size);
/** /**
* 绑定航线到设备 * 绑定航线到设备
* *
@@ -6,6 +6,7 @@ import com.central.device.boat.entity.BoatRoute;
import com.central.device.boat.manager.BoatCommandManager; import com.central.device.boat.manager.BoatCommandManager;
import com.central.device.model.AgeDevice; import com.central.device.model.AgeDevice;
import com.central.device.model.dto.BoatManualControlDTO; import com.central.device.model.dto.BoatManualControlDTO;
import com.central.device.model.dto.BoatSlowlyDriveDTO;
import com.central.device.service.IAgeDeviceService; import com.central.device.service.IAgeDeviceService;
import com.central.device.service.IBoatControlService; import com.central.device.service.IBoatControlService;
import com.central.device.service.IBoatRouteService; import com.central.device.service.IBoatRouteService;
@@ -86,6 +87,18 @@ public class BoatControlServiceImpl implements IBoatControlService {
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", params); boatCommandManager.sendCommand(deviceSn, "flighttask_undo", params);
} }
@Override
public void slowly(String deviceSn, BoatSlowlyDriveDTO dto) {
log.info("无人船慢速行驶: deviceSn={}, missionCode={}, speed={}",
deviceSn, dto.getMissionCode(), dto.getSpeed());
JSONObject params = new JSONObject();
params.put("order_no", dto.getMissionCode());
params.put("speed", dto.getSpeed());
boatCommandManager.sendCommand(deviceSn, "flighttask_slowly", params);
}
@Override @Override
public void returnToStart(String deviceSn) { public void returnToStart(String deviceSn) {
log.info("无人船返回起点: deviceSn={}", deviceSn); log.info("无人船返回起点: deviceSn={}", deviceSn);
@@ -35,6 +35,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.RoundingMode; import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@@ -314,6 +315,34 @@ public class BoatRouteServiceImpl extends ServiceImpl<BoatRouteMapper, BoatRoute
return resultPage; return resultPage;
} }
@Override
public Page<BoatRouteListVO> 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<BoatRoute> pageParam = new Page<>(page, size);
LambdaQueryWrapper<BoatRoute> 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<BoatRoute> routePage = this.page(pageParam, wrapper);
Page<BoatRouteListVO> resultPage = new Page<>(page, size, routePage.getTotal());
resultPage.setRecords(convertToListVO(routePage.getRecords()));
return resultPage;
}
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void bindToDevice(String routeId, String deviceSn) { public void bindToDevice(String routeId, String deviceSn) {
File diff suppressed because it is too large Load Diff
@@ -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"
}
@@ -78,6 +78,22 @@
} }
``` ```
### 2.5 慢速行驶(flighttask_slowly)
```json
{
"messageType": "WRITE_PROPERTY",
"deviceId": "12345678",
"properties": {
"data": {
"order_no": "562026040600002",
"speed": 30
},
"method": "flighttask_slowly"
}
}
```
## 三、架构设计原则 ## 三、架构设计原则
### 3.1 核心原则:不修改无人机代码,独立 boat 包 ### 3.1 核心原则:不修改无人机代码,独立 boat 包
@@ -169,9 +185,11 @@
| 文件 | 改动内容 | | 文件 | 改动内容 |
|------|----------| |------|----------|
| `ControlEnum.java` | 新增 `FLIGHTTASK_UNDO` 枚举值 | | `ControlEnum.java` | 新增 `FLIGHTTASK_UNDO` 枚举值 |
| `IBoatControlService.java` | `pause`/`resume` 增加 missionCode 参数;新增 `undoTask` 方法 | | `BoatCommandManager.java` | 新增 `flighttask_slowly` 指令组包逻辑,向设备透传 `order_no` 和 `speed` |
| `BoatControlServiceImpl.java` | **重写**:Mock 实现替换为通过 `BoatCommandManager` 发送真实 IoT 指令 | | `BoatSlowlyDriveDTO.java` | 新增慢速行驶请求模型,封装 `missionCode` 和 `speed` |
| `BoatCommandController.java` | pause/resume 接口增加 missionCode 参数;新增 undo 接口 | | `IBoatControlService.java` | `pause`/`resume` 增加 missionCode 参数;新增 `undoTask`、`slowly` 方法 |
| `BoatControlServiceImpl.java` | **重写**:Mock 实现替换为通过 `BoatCommandManager` 发送真实 IoT 指令;新增慢速行驶实现 |
| `BoatCommandController.java` | pause/resume 接口增加 missionCode 参数;新增 undo、slowly 接口 |
## 五、详细实现方案 ## 五、详细实现方案
@@ -279,6 +297,10 @@ public class BoatCommandManager {
case "flighttask_undo": case "flighttask_undo":
data.put("order_no", params.getString("order_no")); data.put("order_no", params.getString("order_no"));
break; break;
case "flighttask_slowly":
data.put("order_no", params.getString("order_no"));
data.put("speed", params.getInteger("speed"));
break;
default: default:
data = params; data = params;
break; break;
@@ -406,6 +428,7 @@ void resume(String deviceSn, String missionCode);
```java ```java
void undoTask(String deviceSn, String missionCode); void undoTask(String deviceSn, String missionCode);
void slowly(String deviceSn, BoatSlowlyDriveDTO dto);
``` ```
--- ---
@@ -463,6 +486,14 @@ public class BoatControlServiceImpl implements IBoatControlService {
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", params); boatCommandManager.sendCommand(deviceSn, "flighttask_undo", params);
} }
@Override
public void slowly(String deviceSn, BoatSlowlyDriveDTO dto) {
JSONObject params = new JSONObject();
params.put("order_no", dto.getMissionCode());
params.put("speed", dto.getSpeed());
boatCommandManager.sendCommand(deviceSn, "flighttask_slowly", params);
}
@Override @Override
public void returnToStart(String deviceSn) { public void returnToStart(String deviceSn) {
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", new JSONObject()); boatCommandManager.sendCommand(deviceSn, "flighttask_undo", new JSONObject());
@@ -512,6 +543,17 @@ public Result<Void> undoTask(@RequestParam String deviceSn, @RequestParam String
} }
``` ```
#### 新增慢速行驶接口
```java
@PostMapping("/slowly")
public Result<Void> slowly(@RequestParam String deviceSn,
@RequestBody @Validated BoatSlowlyDriveDTO dto) {
boatControlService.slowly(deviceSn, dto);
return Result.succeed(null, "慢速行驶指令已下发");
}
```
--- ---
## 六、接口变更汇总 ## 六、接口变更汇总
@@ -521,6 +563,7 @@ public Result<Void> undoTask(@RequestParam String deviceSn, @RequestParam String
| 方法 | 路径 | 参数 | 说明 | | 方法 | 路径 | 参数 | 说明 |
|------|------|------|------| |------|------|------|------|
| POST | `/device/boat/command/undo` | deviceSn, missionCode | 终止任务 | | POST | `/device/boat/command/undo` | deviceSn, missionCode | 终止任务 |
| POST | `/device/boat/command/slowly` | `deviceSn` + Body(`missionCode`,`speed`) | 下发慢速行驶指令 |
### 修改接口 ### 修改接口
@@ -549,6 +592,7 @@ public Result<Void> undoTask(@RequestParam String deviceSn, @RequestParam String
| 1 | `boat/model/BoatSubscriptionTopic.java` | **新建** | 无人船订阅主题枚举 | | 1 | `boat/model/BoatSubscriptionTopic.java` | **新建** | 无人船订阅主题枚举 |
| 2 | `boat/manager/BoatCommandManager.java` | **新建** | 无人船命令管理器 | | 2 | `boat/manager/BoatCommandManager.java` | **新建** | 无人船命令管理器 |
| 3 | `boat/manager/BoatSubscriptionManager.java` | **新建** | 无人船订阅管理器 | | 3 | `boat/manager/BoatSubscriptionManager.java` | **新建** | 无人船订阅管理器 |
| 4 | `model/dto/BoatSlowlyDriveDTO.java` | **新建** | 无人船慢速行驶请求模型 |
## 八、修改文件清单 ## 八、修改文件清单
@@ -556,9 +600,10 @@ public Result<Void> undoTask(@RequestParam String deviceSn, @RequestParam String
|---|---------|----------|------| |---|---------|----------|------|
| 1 | `websocket/client/JetLinksWebSocketClient.java` | 最小改动 | `extractDeviceSn()` 通用化(唯一共享改动) | | 1 | `websocket/client/JetLinksWebSocketClient.java` | 最小改动 | `extractDeviceSn()` 通用化(唯一共享改动) |
| 2 | `message/ControlEnum.java` | 追加 | 新增 `FLIGHTTASK_UNDO` 枚举值 | | 2 | `message/ControlEnum.java` | 追加 | 新增 `FLIGHTTASK_UNDO` 枚举值 |
| 3 | `service/IBoatControlService.java` | 修改 | 接口签名调整 + 新增方法 | | 3 | `boat/manager/BoatCommandManager.java` | 修改 | 新增 `flighttask_slowly` 组包逻辑 |
| 4 | `service/impl/BoatControlServiceImpl.java` | **重写** | Mock → 真实 IoT 指令下发 | | 4 | `service/IBoatControlService.java` | 修改 | 接口签名调整 + 新增 `slowly` 方法 |
| 5 | `controller/BoatCommandController.java` | 修改 | 接口参数调整 + 新增 undo | | 5 | `service/impl/BoatControlServiceImpl.java` | **重写** | Mock → 真实 IoT 指令下发,并新增慢速行驶实现 |
| 6 | `controller/BoatCommandController.java` | 修改 | 接口参数调整 + 新增 undo、slowly |
--- ---
@@ -600,10 +645,32 @@ public Result<Void> undoTask(@RequestParam String deviceSn, @RequestParam String
} }
``` ```
### 无人船慢速行驶指令(新增)
```json
{
"type": "sub",
"topic": "/device-message-sender/ship/{deviceSn}",
"parameter": {
"messageType": "WRITE_PROPERTY",
"properties": {
"method": "flighttask_slowly",
"data": {
"order_no": "562026040600002",
"speed": 30
}
},
"headers": { "async": false }
},
"id": "{commandId}"
}
```
**区别**: **区别**:
1. topic 路径中产品标识不同:`AutoDock3` vs `ship` 1. topic 路径中产品标识不同:`AutoDock3` vs `ship`
2. 无人船的暂停/恢复/终止 data 中需要携带 `order_no` 2. 无人船的暂停/恢复/终止 data 中需要携带 `order_no`
3. 无人船的开始任务 data 中需要携带 `order_no`、`wayline_link_url`、`file_md5`、`stream_urls` 3. 无人船的开始任务 data 中需要携带 `order_no`、`wayline_link_url`、`file_md5`、`stream_urls`
4. 无人船的慢速行驶指令 data 中需要携带 `order_no`、`speed`
--- ---
@@ -689,3 +756,4 @@ data: ping
2. **返航/紧急停止指令**:目前映射到 `flighttask_undo`。如果无人船有专用的返航指令,后续需要替换。 2. **返航/紧急停止指令**:目前映射到 `flighttask_undo`。如果无人船有专用的返航指令,后续需要替换。
3. **手动控制协议**:`manualControl()` 方法暂保留接口,待后续提供手动控制协议后对接。 3. **手动控制协议**:`manualControl()` 方法暂保留接口,待后续提供手动控制协议后对接。
4. **设备在线状态/设备状态查询**:`isDeviceOnline()` 和 `getDeviceStatus()` 暂返回默认值,后续可对接 DeviceMessageHandler 中的实时数据。 4. **设备在线状态/设备状态查询**:`isDeviceOnline()` 和 `getDeviceStatus()` 暂返回默认值,后续可对接 DeviceMessageHandler 中的实时数据。
5. **慢速行驶速度的单位和范围**:当前按设备协议直接透传 `speed`,示例值为 `30`。如果设备端对单位、最小值、最大值有明确限制,需要继续补充参数校验。
+4
View File
@@ -47,3 +47,7 @@ build
zlt-web/react-web-next/public/cesium/ zlt-web/react-web-next/public/cesium/
zlt-web/yingyan/public/cesium/ zlt-web/yingyan/public/cesium/
zlt-web/react-web-next/dist.zip
zlt-web/yingyan/dist.zip
+1
View File
@@ -51,6 +51,7 @@ export default [
{ {
path: '/device', path: '/device',
routes: [ routes: [
{ path: '/device/boatRoute.html', name: '无人船航线管理', component: '@/pages/device/BoatRoute' },
{ path: '/device/wayline.html', component: '@/pages/device/Wayline' }, { path: '/device/wayline.html', component: '@/pages/device/Wayline' },
{ path: '/device/device.html', component: '@/pages/device/Device' }, { path: '/device/device.html', component: '@/pages/device/Device' },
// 3D模型管理 // 3D模型管理
Binary file not shown.
+3 -3
View File
@@ -15,8 +15,8 @@
"prebuild:test:mgnt": "npm run copy:cesium", "prebuild:test:mgnt": "npm run copy:cesium",
"prebuild:pre:mgnt": "npm run copy:cesium", "prebuild:pre:mgnt": "npm run copy:cesium",
"prebuild:prod:mgnt": "npm run copy:cesium", "prebuild:prod:mgnt": "npm run copy:cesium",
"start": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9900 umi dev", "start": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9901 umi dev",
"start:dev": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9900 umi dev", "start:dev": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9901 umi dev",
"start:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test GATEWAY_ORIGIN=https://test.goflytec.com umi dev", "start:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test GATEWAY_ORIGIN=https://test.goflytec.com umi dev",
"start:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre GATEWAY_ORIGIN=http://119.45.169.13:9900 umi dev", "start:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre GATEWAY_ORIGIN=http://119.45.169.13:9900 umi dev",
"build": "cross-env NODE_OPTIONS=--openssl-legacy-provider umi build", "build": "cross-env NODE_OPTIONS=--openssl-legacy-provider umi build",
@@ -24,7 +24,7 @@
"build:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre API_PREFIX=http://119.45.169.13:9900 umi build", "build:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre API_PREFIX=http://119.45.169.13:9900 umi build",
"build:prod": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=prod umi build", "build:prod": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=prod umi build",
"build:test:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test APP_BASE=/mgnt API_PREFIX=https://test.goflytec.com umi build", "build:test:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test APP_BASE=/mgnt API_PREFIX=https://test.goflytec.com umi build",
"build:pre:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre APP_BASE=/mgnt API_PREFIX=https://local.goflytec.com umi build", "build:pre:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre APP_BASE=/mgnt API_PREFIX=https://yeehaitec.com umi build",
"build:prod:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=prod APP_BASE=/mgnt umi build", "build:prod:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=prod APP_BASE=/mgnt umi build",
"lint": "eslint --ext .ts,.tsx src", "lint": "eslint --ext .ts,.tsx src",
"tsc": "tsc --noEmit" "tsc": "tsc --noEmit"
@@ -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;
@@ -1,6 +1,6 @@
/** /**
* 3D Tiles 倾斜摄影模型加载器 Hook * 3D Tiles 倾斜摄影模型加载器 Hook
* 用于加载大疆建图等工具生成的3D Tiles模型 * 用于加载大疆建图等工具生成的 3D Tiles 模型
*/ */
import { useState, useCallback, useRef } from 'react'; import { useState, useCallback, useRef } from 'react';
@@ -8,26 +8,26 @@ import { useState, useCallback, useRef } from 'react';
export interface TilesetConfig { export interface TilesetConfig {
id: string; // 模型唯一标识 id: string; // 模型唯一标识
name: string; // 模型名称 name: string; // 模型名称
url: string; // tileset.json 的URL地址 url: string; // tileset.json 的 URL 地址
tourismId?: number; // 关联的景区ID tourismId?: number; // 关联的景区 ID
position?: { // 模型位置调整 position?: { // 模型位置调整
longitude?: number; // 经度偏移 longitude?: number; // 经度偏移
latitude?: number; // 纬度偏移 latitude?: number; // 纬度偏移
height?: number; // 高度偏移(通用) height?: number; // 高度偏移(通用)
cesiumHeight?: number; // Cesium Ion地形对应的高度偏移 cesiumHeight?: number; // Cesium Ion 地形对应的高度偏移
arcgisHeight?: number; // ArcGIS地形对应的高度偏移 arcgisHeight?: number; // ArcGIS 地形对应的高度偏移
terrainType?: string; // 高度标定时使用的地形服务: cesium_ion/arcgis/ellipsoid terrainType?: string; // 高度标定时使用的地形服务: cesium_ion/arcgis/ellipsoid
}; };
transform?: { // 模型变换 transform?: { // 模型变换
scale?: number; // 缩放比例 scale?: number; // 缩放比例
rotationX?: number; // X轴旋转(弧度) rotationX?: number; // X 轴旋转(弧度)
rotationY?: number; // Y轴旋转 rotationY?: number; // Y 轴旋转
rotationZ?: number; // Z轴旋转 rotationZ?: number; // Z 轴旋转
}; };
style?: { // 渲染样式 style?: { // 渲染样式
maximumScreenSpaceError?: number; // LOD精度控制(默认16) maximumScreenSpaceError?: number; // LOD 精度控制(默认16)
maximumMemoryUsage?: number; // 最大内存使用(MB) maximumMemoryUsage?: number; // 最大内存使用(MB)
skipLevelOfDetail?: boolean; // 是否跳过LOD skipLevelOfDetail?: boolean; // 是否跳过 LOD
preferLeaves?: boolean; // 优先加载叶子节点 preferLeaves?: boolean; // 优先加载叶子节点
}; };
visible?: boolean; // 是否可见 visible?: boolean; // 是否可见
@@ -42,7 +42,7 @@ export interface TilesetState {
tileset?: any; // Cesium3DTileset 实例 tileset?: any; // Cesium3DTileset 实例
} }
// Hook返回类型 // Hook 返回类型
export interface UseTilesetLoaderResult { export interface UseTilesetLoaderResult {
tilesets: Map<string, TilesetState>; tilesets: Map<string, TilesetState>;
loadTileset: (config: TilesetConfig, viewer: any, Cesium: any, currentTerrainType?: string) => Promise<any>; 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()); const tilesetsRef = useRef<Map<string, any>>(new Map());
/** /**
* 加载3D Tiles模型 * 加载 3D Tiles 模型
* @param config 模型配置 * @param config 模型配置
* @param viewer Cesium Viewer实例 * @param viewer Cesium Viewer 实例
* @param Cesium Cesium模块 * @param Cesium Cesium 模块
* @param currentTerrainType 当前使用的地形类型,用于选择对应的高度偏移 * @param currentTerrainType 当前使用的地形类型,用于选择对应的高度偏移
*/ */
const loadTileset = useCallback(async ( const loadTileset = useCallback(async (
@@ -71,7 +71,7 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
currentTerrainType?: string currentTerrainType?: string
): Promise<any> => { ): Promise<any> => {
if (!viewer || !Cesium) { if (!viewer || !Cesium) {
console.error('Viewer或Cesium未初始化'); console.error('Viewer 或 Cesium 未初始化');
return null; return null;
} }
@@ -81,7 +81,7 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
return tilesetsRef.current.get(config.id); return tilesetsRef.current.get(config.id);
} }
// 更新状态为loading // 更新状态为 loading
setTilesets(prev => { setTilesets(prev => {
const newMap = new Map(prev); const newMap = new Map(prev);
newMap.set(config.id, { newMap.set(config.id, {
@@ -101,13 +101,13 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
console.log('[Tileset] 使用代理路径:', tilesetUrl); console.log('[Tileset] 使用代理路径:', tilesetUrl);
} }
// 创建3DTileset - 高清晰度渲染配置 // 创建 3D Tileset - 高清晰度渲染配置
const tileset = await Cesium.Cesium3DTileset.fromUrl(tilesetUrl, { const tileset = await Cesium.Cesium3DTileset.fromUrl(tilesetUrl, {
// 核心清晰度控制 - 值越小越清晰(大疆司空使用约1-2) // 核心清晰度控制 - 值越小越清晰(大疆司空使用约1-2)
maximumScreenSpaceError: config.style?.maximumScreenSpaceError ?? 1, maximumScreenSpaceError: config.style?.maximumScreenSpaceError ?? 1,
maximumMemoryUsage: config.style?.maximumMemoryUsage ?? 2048, // 增加内存以加载更多高精度瓦片 maximumMemoryUsage: config.style?.maximumMemoryUsage ?? 2048, // 增加内存以加载更多高精度瓦片
// 禁用LOD跳跃以获得更好的清晰度 // 禁用 LOD 跳跃以获得更好的清晰度
skipLevelOfDetail: config.style?.skipLevelOfDetail ?? false, skipLevelOfDetail: config.style?.skipLevelOfDetail ?? false,
preferLeaves: config.style?.preferLeaves ?? true, preferLeaves: config.style?.preferLeaves ?? true,
@@ -229,7 +229,7 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
// 存储引用 // 存储引用
tilesetsRef.current.set(config.id, tileset); tilesetsRef.current.set(config.id, tileset);
// 更新状态为loaded // 更新状态为 loaded
setTilesets(prev => { setTilesets(prev => {
const newMap = new Map(prev); const newMap = new Map(prev);
newMap.set(config.id, { newMap.set(config.id, {
@@ -241,11 +241,11 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
return newMap; return newMap;
}); });
console.log(`3D Tiles模型 [${config.name}] 加载成功`); console.log(`3D Tiles 模型 [${config.name}] 加载成功`);
return tileset; return tileset;
} catch (error: any) { } catch (error: any) {
console.error(`3D Tiles模型 [${config.name}] 加载失败:`, error); console.error(`3D Tiles 模型 [${config.name}] 加载失败:`, error);
setTilesets(prev => { setTilesets(prev => {
const newMap = new Map(prev); const newMap = new Map(prev);
@@ -287,13 +287,13 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
const unloadAllTilesets = useCallback((viewer: any) => { const unloadAllTilesets = useCallback((viewer: any) => {
if (!viewer) return; if (!viewer) return;
tilesetsRef.current.forEach((tileset, id) => { tilesetsRef.current.forEach((tileset) => {
viewer.scene.primitives.remove(tileset); viewer.scene.primitives.remove(tileset);
}); });
tilesetsRef.current.clear(); tilesetsRef.current.clear();
setTilesets(new Map()); setTilesets(new Map());
console.log('所有3D Tiles模型已卸载'); console.log('所有 3D Tiles 模型已卸载');
}, []); }, []);
/** /**
@@ -304,14 +304,12 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
if (!tileset || !viewer || !Cesium) return; if (!tileset || !viewer || !Cesium) return;
const boundingSphere = tileset.boundingSphere; const boundingSphere = tileset.boundingSphere;
const center = boundingSphere.center;
const radius = boundingSphere.radius; const radius = boundingSphere.radius;
// 计算合适的观察距离
const offset = new Cesium.HeadingPitchRange( const offset = new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(0), // heading Cesium.Math.toRadians(0),
Cesium.Math.toRadians(-45), // pitch (45度俯视) Cesium.Math.toRadians(-45),
radius * 2.5 // 距离 radius * 2.5
); );
viewer.camera.flyToBoundingSphere(boundingSphere, { viewer.camera.flyToBoundingSphere(boundingSphere, {
@@ -337,7 +335,6 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
const tileset = tilesetsRef.current.get(id); const tileset = tilesetsRef.current.get(id);
if (!tileset || !Cesium) return; if (!tileset || !Cesium) return;
// 示例: 设置建筑颜色
tileset.style = new Cesium.Cesium3DTileStyle({ tileset.style = new Cesium.Cesium3DTileStyle({
color: style.color || "color('white')", color: style.color || "color('white')",
show: style.show !== false, 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);
},
};
Binary file not shown.
+3 -3
View File
@@ -13,13 +13,13 @@
"prebuild:test": "npm run copy:cesium", "prebuild:test": "npm run copy:cesium",
"prebuild:pre": "npm run copy:cesium", "prebuild:pre": "npm run copy:cesium",
"prebuild:prod": "npm run copy:cesium", "prebuild:prod": "npm run copy:cesium",
"start": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9900 umi dev", "start": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9901 umi dev",
"start:dev": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9900 umi dev", "start:dev": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9901 umi dev",
"start:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test GATEWAY_ORIGIN=https://test.goflytec.com umi dev", "start:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test GATEWAY_ORIGIN=https://test.goflytec.com umi dev",
"start:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre GATEWAY_ORIGIN=http://119.45.169.13:9900 umi dev", "start:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre GATEWAY_ORIGIN=http://119.45.169.13:9900 umi dev",
"build": "cross-env NODE_OPTIONS=--openssl-legacy-provider umi build", "build": "cross-env NODE_OPTIONS=--openssl-legacy-provider umi build",
"build:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test APP_BASE=/web API_PREFIX=https://test.goflytec.com umi build", "build:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test APP_BASE=/web API_PREFIX=https://test.goflytec.com umi build",
"build:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre APP_BASE=/web API_PREFIX=https://local.goflytec.com umi build", "build:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre APP_BASE=/web API_PREFIX=https://yeehaitec.com umi build",
"build:prod": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=prod APP_BASE=/web umi build", "build:prod": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=prod APP_BASE=/web umi build",
"lint": "eslint --ext .ts,.tsx src", "lint": "eslint --ext .ts,.tsx src",
"tsc": "tsc --noEmit" "tsc": "tsc --noEmit"
Binary file not shown.
@@ -36,6 +36,36 @@
border: 1px solid rgba(34, 211, 238, 0.3); border: 1px solid rgba(34, 211, 238, 0.3);
} }
.viewSwitchBar {
position: absolute;
top: 18px;
right: 18px;
display: flex;
align-items: center;
gap: 10px;
z-index: 30;
}
.viewSwitchBtn {
height: 34px;
padding: 0 14px;
border: 1px solid rgba(34, 211, 238, 0.35);
border-radius: 999px;
background: rgba(8, 15, 28, 0.82);
color: #d8f6ff;
font-size: 12px;
font-weight: 600;
cursor: pointer;
backdrop-filter: blur(8px);
transition: all 0.2s ease;
&:hover {
border-color: rgba(34, 211, 238, 0.7);
color: #fff;
box-shadow: 0 0 0 1px rgba(34, 211, 238, 0.18), 0 8px 22px rgba(0, 0, 0, 0.22);
}
}
.loadingSpinner { .loadingSpinner {
width: 16px; width: 16px;
height: 16px; height: 16px;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,395 @@
@bg-sidebar: #0f172a;
@bg-card: #1e293b;
@bg-deep: #0a0f1c;
@border-color: #1e3a5f;
@accent-cyan: #22d3ee;
@accent-orange: #f97316;
@text-primary: #ffffff;
@text-secondary: #94a3b8;
@text-dim: #64748b;
@font-mono: 'JetBrains Mono', 'Courier New', monospace;
@font-sans: 'Inter', -apple-system, sans-serif;
.panel {
width: 340px;
height: 100%;
background: @bg-sidebar;
border-left: 1px solid @border-color;
padding: 16px;
display: flex;
flex-direction: column;
gap: 14px;
overflow-y: auto;
overflow-x: hidden;
flex-shrink: 0;
&::-webkit-scrollbar {
width: 4px;
}
&::-webkit-scrollbar-thumb {
background: rgba(34, 211, 238, 0.22);
border-radius: 999px;
}
}
.section {
background: linear-gradient(180deg, rgba(30, 41, 59, 0.92), rgba(15, 23, 42, 0.96));
border: 1px solid @border-color;
border-radius: 14px;
padding: 14px;
display: flex;
flex-direction: column;
gap: 12px;
}
.sectionHeader {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.sectionTitle {
display: inline-flex;
align-items: center;
gap: 8px;
color: @text-primary;
font-size: 13px;
font-weight: 700;
font-family: @font-sans;
}
.sectionTag {
padding: 4px 8px;
border-radius: 999px;
border: 1px solid rgba(34, 211, 238, 0.28);
background: rgba(34, 211, 238, 0.08);
color: @accent-cyan;
font-size: 10px;
font-family: @font-mono;
}
.videoCard {
border-radius: 12px;
overflow: hidden;
background: #050a14;
height: 196px;
}
.videoPlaceholder {
min-height: 196px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
color: @text-secondary;
background:
radial-gradient(circle at top, rgba(34, 211, 238, 0.10), transparent 52%),
linear-gradient(180deg, rgba(7, 11, 21, 0.96), rgba(4, 8, 15, 0.98));
}
.placeholderIcon {
font-size: 26px;
color: @accent-cyan;
}
.placeholderTitle {
font-size: 13px;
font-weight: 700;
color: @text-primary;
}
.placeholderDesc {
font-size: 11px;
color: @text-dim;
text-align: center;
}
.mockVideoCard {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
background:
radial-gradient(circle at 50% 18%, rgba(34, 211, 238, 0.24), transparent 28%),
linear-gradient(180deg, #0a1830 0%, #08111f 38%, #06111a 100%);
}
.mockVideoGlow {
position: absolute;
inset: -10% -20% auto;
height: 65%;
background: radial-gradient(circle, rgba(34, 211, 238, 0.18), transparent 60%);
pointer-events: none;
}
.mockVideoScanline {
position: absolute;
inset: 0;
background:
linear-gradient(180deg, transparent 0%, rgba(34, 211, 238, 0.1) 48%, transparent 100%),
repeating-linear-gradient(
180deg,
rgba(255, 255, 255, 0.02) 0,
rgba(255, 255, 255, 0.02) 2px,
transparent 2px,
transparent 6px
);
animation: videoSweep 4.2s linear infinite;
pointer-events: none;
}
.mockVideoHud {
position: absolute;
top: 12px;
left: 12px;
right: 12px;
display: flex;
align-items: center;
justify-content: space-between;
z-index: 2;
}
.mockVideoBadge,
.mockVideoMeta {
padding: 4px 8px;
border-radius: 999px;
background: rgba(8, 15, 28, 0.68);
border: 1px solid rgba(34, 211, 238, 0.28);
color: @accent-cyan;
font-size: 10px;
font-family: @font-mono;
}
.mockVideoScene {
position: absolute;
inset: 0;
}
.mockHorizon {
position: absolute;
left: 0;
right: 0;
top: 42%;
height: 1px;
background: rgba(255, 255, 255, 0.24);
box-shadow: 0 0 14px rgba(34, 211, 238, 0.3);
}
.mockWave {
position: absolute;
left: -12%;
right: -12%;
bottom: 18%;
height: 44%;
border-radius: 42% 58% 0 0 / 20% 24% 0 0;
background:
linear-gradient(180deg, rgba(34, 211, 238, 0.22), rgba(8, 47, 73, 0.82)),
radial-gradient(circle at 50% 0, rgba(255, 255, 255, 0.18), transparent 45%);
animation: waveFloat 6s ease-in-out infinite;
}
.mockBoatMarker {
position: absolute;
right: 18px;
bottom: 28px;
display: inline-flex;
align-items: center;
gap: 8px;
padding: 7px 10px;
border-radius: 10px;
background: rgba(8, 15, 28, 0.72);
border: 1px solid rgba(34, 211, 238, 0.28);
color: @text-primary;
font-size: 11px;
font-weight: 600;
}
.mockBoatDot {
width: 8px;
height: 8px;
border-radius: 50%;
background: @accent-orange;
box-shadow: 0 0 0 5px rgba(249, 115, 22, 0.18);
}
.mockVideoFooter {
position: absolute;
left: 12px;
right: 12px;
bottom: 12px;
display: flex;
justify-content: space-between;
gap: 8px;
color: @text-secondary;
font-size: 10px;
font-family: @font-mono;
z-index: 2;
}
.lidarCard {
display: flex;
flex-direction: column;
gap: 12px;
}
.lidarCanvas {
position: relative;
width: 100%;
height: 220px;
border-radius: 12px;
background:
radial-gradient(circle at center, rgba(34, 211, 238, 0.08), transparent 55%),
linear-gradient(180deg, rgba(6, 12, 24, 0.98), rgba(10, 15, 28, 0.98));
border: 1px solid rgba(34, 211, 238, 0.16);
overflow: hidden;
}
.lidarSvg {
width: 100%;
height: 100%;
}
.lidarRing {
fill: none;
stroke: rgba(148, 163, 184, 0.18);
stroke-width: 1;
}
.lidarAxis {
stroke: rgba(148, 163, 184, 0.14);
stroke-width: 1;
}
.lidarPoint {
fill: @accent-orange;
opacity: 0.92;
}
.lidarSweep {
stroke: rgba(34, 211, 238, 0.58);
stroke-width: 1.5;
stroke-linecap: round;
filter: drop-shadow(0 0 6px rgba(34, 211, 238, 0.45));
}
.lidarEmpty {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
color: @text-secondary;
font-size: 12px;
}
.lidarMetrics {
display: flex;
flex-direction: column;
gap: 10px;
}
.metricItem,
.metricMini {
background: rgba(10, 15, 28, 0.82);
border: 1px solid rgba(30, 58, 95, 0.7);
border-radius: 10px;
padding: 10px 12px;
display: flex;
flex-direction: column;
gap: 4px;
}
.metricRow {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
}
.metricLabel {
font-size: 10px;
color: @text-dim;
font-family: @font-sans;
}
.metricValue {
font-size: 14px;
color: @text-primary;
font-family: @font-mono;
font-weight: 700;
}
.summaryGrid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
}
.summaryCard {
min-height: 86px;
border-radius: 12px;
border: 1px solid rgba(30, 58, 95, 0.78);
background: rgba(10, 15, 28, 0.84);
padding: 12px;
display: flex;
flex-direction: column;
gap: 6px;
}
.summaryIcon {
font-size: 16px;
}
.summaryLabel {
color: @text-dim;
font-size: 10px;
font-family: @font-sans;
}
.summaryValue {
color: @text-primary;
font-size: 13px;
line-height: 1.4;
font-family: @font-mono;
font-weight: 700;
word-break: break-word;
}
@media (max-width: 1366px) {
.panel {
width: 300px;
padding: 12px;
}
.videoCard {
height: 168px;
}
.lidarCanvas {
height: 190px;
}
}
@keyframes videoSweep {
0% {
transform: translateY(-100%);
}
100% {
transform: translateY(100%);
}
}
@keyframes waveFloat {
0%, 100% {
transform: translateY(0) scaleX(1);
}
50% {
transform: translateY(5px) scaleX(1.03);
}
}
@@ -0,0 +1,302 @@
import React, { useEffect, useMemo, useState } from 'react';
import {
VideoCameraOutlined,
RadarChartOutlined,
EnvironmentOutlined,
ThunderboltOutlined,
WifiOutlined,
} from '@ant-design/icons';
import WhepPlayer from '@/pages/map3d/components/MapContainer/3d/BottomPanel/WhepPlayer';
import type { BoatRouteListVO, BoatTelemetryData } from '@/types/boatRoute';
import { getValidCoordinate } from '@/utils/geo';
import styles from './index.less';
interface ExecRightPanelProps {
deviceInfo: any;
boatData: BoatTelemetryData | null;
activeRouteInfo: BoatRouteListVO | null;
sseConnected: boolean;
videoStreamUrl?: string;
isPreviewing?: boolean;
}
interface LidarSample {
angle: number;
distance: number;
}
const clampNumber = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));
const extractLidarSamples = (deviceInfo: any, boatData: BoatTelemetryData | null): LidarSample[] => {
const raw =
(boatData as any)?.lidarSamples ||
(boatData as any)?.lidarPoints ||
(boatData as any)?.lidarDistances ||
(deviceInfo as any)?.lidarSamples ||
(deviceInfo as any)?.lidarPoints ||
(deviceInfo as any)?.lidarDistances ||
[];
if (!Array.isArray(raw) || raw.length === 0) return [];
if (typeof raw[0] === 'number') {
return raw.map((distance: number, index: number) => ({
angle: (index / raw.length) * 360,
distance: Number(distance) || 0,
}));
}
return raw
.map((item: any, index: number) => ({
angle: Number(item?.angle ?? item?.deg ?? item?.theta ?? (index / raw.length) * 360),
distance: Number(item?.distance ?? item?.range ?? item?.value ?? 0),
}))
.filter((item) => Number.isFinite(item.angle) && Number.isFinite(item.distance));
};
const createMockLidarSamples = (phase: number): LidarSample[] => (
Array.from({ length: 72 }, (_, index) => {
const angle = index * 5;
const wave = Math.sin((angle + phase * 28) * Math.PI / 180);
const ripple = Math.cos((angle * 2 + phase * 36) * Math.PI / 180);
const bump = (index % 9 === 0 ? 4.5 : 0) + (index % 13 === 0 ? 2.6 : 0);
const distance = clampNumber(16 + wave * 6 + ripple * 3 + bump, 3.6, 31);
return { angle, distance };
})
);
const ExecRightPanel: React.FC<ExecRightPanelProps> = ({
deviceInfo,
boatData,
activeRouteInfo,
sseConnected,
videoStreamUrl,
isPreviewing = false,
}) => {
const [mockPhase, setMockPhase] = useState(0);
useEffect(() => {
if (!isPreviewing) return undefined;
const timer = window.setInterval(() => {
setMockPhase((value) => (value + 1) % 360);
}, 900);
return () => window.clearInterval(timer);
}, [isPreviewing]);
const realLidarSamples = useMemo(() => extractLidarSamples(deviceInfo, boatData), [deviceInfo, boatData]);
const lidarSamples = useMemo(
() => (isPreviewing ? createMockLidarSamples(mockPhase) : realLidarSamples),
[isPreviewing, mockPhase, realLidarSamples],
);
const boatPosition = getValidCoordinate(boatData?.longitude, boatData?.latitude);
const hasBoatPosition = !!boatPosition;
const lidarMetrics = useMemo(() => {
if (!lidarSamples.length) {
return {
minDistance: null,
frontDistance: null,
leftDistance: null,
rightDistance: null,
};
}
const pickClosest = (targetAngle: number) => {
const matched = lidarSamples.reduce((best, current) => {
const delta = Math.abs((((current.angle - targetAngle) % 360) + 540) % 360 - 180);
return delta < best.delta ? { delta, distance: current.distance } : best;
}, { delta: Number.POSITIVE_INFINITY, distance: 0 });
return matched.distance;
};
return {
minDistance: Math.min(...lidarSamples.map((item) => item.distance)),
frontDistance: pickClosest(0),
leftDistance: pickClosest(270),
rightDistance: pickClosest(90),
};
}, [lidarSamples]);
const lidarPoints = useMemo(() => {
if (!lidarSamples.length) return [];
const maxDistance = Math.max(10, ...lidarSamples.map((item) => item.distance));
const radius = 88;
return lidarSamples.slice(0, 72).map((sample) => {
const normalized = clampNumber(sample.distance / maxDistance, 0.08, 1);
const actualRadius = normalized * radius;
const angleRad = (sample.angle - 90) * Math.PI / 180;
return {
x: 110 + Math.cos(angleRad) * actualRadius,
y: 110 + Math.sin(angleRad) * actualRadius,
};
});
}, [lidarSamples]);
const statusItems = [
{
label: '设备状态',
value: isPreviewing ? '模拟预览' : (sseConnected ? '在线' : '离线'),
icon: <WifiOutlined />,
accent: isPreviewing ? '#22d3ee' : (sseConnected ? '#10b981' : '#ef4444'),
},
{
label: '剩余电量',
value: `${boatData?.battery ?? (isPreviewing ? 86 : 0)}%`,
icon: <ThunderboltOutlined />,
accent: (boatData?.battery ?? 86) > 20 ? '#22d3ee' : '#f59e0b',
},
{
label: '当前位置',
value: hasBoatPosition ? `${boatData!.longitude.toFixed(4)}, ${boatData!.latitude.toFixed(4)}` : '--',
icon: <EnvironmentOutlined />,
accent: '#94a3b8',
},
];
const formatMeters = (distance: number | null) => (distance == null ? '--' : `${distance.toFixed(distance >= 10 ? 0 : 1)} m`);
return (
<div className={styles.panel}>
<div className={styles.section}>
<div className={styles.sectionHeader}>
<span className={styles.sectionTitle}>
<VideoCameraOutlined />
视频回传
</span>
<span className={styles.sectionTag}>
{isPreviewing ? '模拟流' : (videoStreamUrl ? '实时流' : '未接入')}
</span>
</div>
<div className={styles.videoCard}>
{isPreviewing ? (
<div className={styles.mockVideoCard}>
<div className={styles.mockVideoGlow} />
<div className={styles.mockVideoScanline} />
<div className={styles.mockVideoHud}>
<span className={styles.mockVideoBadge}>SIM CAM</span>
<span className={styles.mockVideoMeta}>1080P / 25 FPS</span>
</div>
<div className={styles.mockVideoScene}>
<div className={styles.mockHorizon} />
<div className={styles.mockWave} />
<div className={styles.mockBoatMarker}>
<span className={styles.mockBoatDot} />
<span>航线预览目标</span>
</div>
</div>
<div className={styles.mockVideoFooter}>
<span>模拟海况:2级</span>
<span>光照:良好</span>
<span>延迟:42ms</span>
</div>
</div>
) : videoStreamUrl ? (
<WhepPlayer url={videoStreamUrl} autoPlay={true} muted={true} videoOnly={true} />
) : (
<div className={styles.videoPlaceholder}>
<VideoCameraOutlined className={styles.placeholderIcon} />
<div className={styles.placeholderTitle}>暂无视频流</div>
<div className={styles.placeholderDesc}>设备未配置 `videoStreamUrl` 或 `whepUrl`</div>
</div>
)}
</div>
</div>
<div className={styles.section}>
<div className={styles.sectionHeader}>
<span className={styles.sectionTitle}>
<RadarChartOutlined />
激光雷达
</span>
<span className={styles.sectionTag}>
{isPreviewing ? `模拟 ${lidarSamples.length} 点` : (lidarSamples.length > 0 ? `${lidarSamples.length} 点` : '未接入')}
</span>
</div>
<div className={styles.lidarCard}>
<div className={styles.lidarCanvas}>
<svg viewBox="0 0 220 220" className={styles.lidarSvg}>
<circle cx="110" cy="110" r="88" className={styles.lidarRing} />
<circle cx="110" cy="110" r="58" className={styles.lidarRing} />
<circle cx="110" cy="110" r="28" className={styles.lidarRing} />
<line x1="110" y1="14" x2="110" y2="206" className={styles.lidarAxis} />
<line x1="14" y1="110" x2="206" y2="110" className={styles.lidarAxis} />
<line
x1="110"
y1="110"
x2={110 + Math.cos((mockPhase - 90) * Math.PI / 180) * 96}
y2={110 + Math.sin((mockPhase - 90) * Math.PI / 180) * 96}
className={styles.lidarSweep}
/>
{lidarPoints.map((point, index) => (
<circle key={`${point.x}-${point.y}-${index}`} cx={point.x} cy={point.y} r="2.6" className={styles.lidarPoint} />
))}
</svg>
{lidarPoints.length === 0 && (
<div className={styles.lidarEmpty}>
<RadarChartOutlined className={styles.placeholderIcon} />
<span>暂无激光雷达数据</span>
</div>
)}
</div>
<div className={styles.lidarMetrics}>
<div className={styles.metricItem}>
<span className={styles.metricLabel}>最近障碍距离</span>
<span className={styles.metricValue}>{formatMeters(lidarMetrics.minDistance)}</span>
</div>
<div className={styles.metricRow}>
<div className={styles.metricMini}>
<span className={styles.metricLabel}>前方</span>
<span className={styles.metricValue}>{formatMeters(lidarMetrics.frontDistance)}</span>
</div>
<div className={styles.metricMini}>
<span className={styles.metricLabel}>左侧</span>
<span className={styles.metricValue}>{formatMeters(lidarMetrics.leftDistance)}</span>
</div>
<div className={styles.metricMini}>
<span className={styles.metricLabel}>右侧</span>
<span className={styles.metricValue}>{formatMeters(lidarMetrics.rightDistance)}</span>
</div>
</div>
</div>
</div>
</div>
<div className={styles.section}>
<div className={styles.sectionHeader}>
<span className={styles.sectionTitle}>执行摘要</span>
<span className={styles.sectionTag}>{activeRouteInfo?.routeName || '未选择航线'}</span>
</div>
<div className={styles.summaryGrid}>
{statusItems.map((item) => (
<div key={item.label} className={styles.summaryCard}>
<div className={styles.summaryIcon} style={{ color: item.accent }}>{item.icon}</div>
<div className={styles.summaryLabel}>{item.label}</div>
<div className={styles.summaryValue}>{item.value}</div>
</div>
))}
<div className={styles.summaryCard}>
<div className={styles.summaryLabel}>规划总长</div>
<div className={styles.summaryValue}>
{activeRouteInfo ? `${(activeRouteInfo.totalDistance / 1000).toFixed(2)} km` : '--'}
</div>
</div>
<div className={styles.summaryCard}>
<div className={styles.summaryLabel}>预计时长</div>
<div className={styles.summaryValue}>{activeRouteInfo?.totalDurationStr || '--'}</div>
</div>
<div className={styles.summaryCard}>
<div className={styles.summaryLabel}>航向 / 速度</div>
<div className={styles.summaryValue}>
{boatData ? `${Math.round(boatData.heading || 0)}° / ${boatData.speed?.toFixed(1) || '0.0'} m/s` : '--'}
</div>
</div>
</div>
</div>
</div>
);
};
export default ExecRightPanel;
@@ -11,6 +11,7 @@ import {
DownOutlined, DownOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import type { BoatRouteListVO, BoatWaypointVO, BoatTelemetryData } from '@/types/boatRoute'; import type { BoatRouteListVO, BoatWaypointVO, BoatTelemetryData } from '@/types/boatRoute';
import { getValidCoordinate } from '@/utils/geo';
import styles from './index.less'; import styles from './index.less';
interface LeftPanelProps { interface LeftPanelProps {
@@ -27,13 +28,11 @@ interface LeftPanelProps {
sailingLoading: boolean; sailingLoading: boolean;
} }
/** 格式化距离 */
const formatDistance = (meters?: number) => { const formatDistance = (meters?: number) => {
if (!meters || meters <= 0) return null; if (!meters || meters <= 0) return null;
return meters >= 1000 ? `${(meters / 1000).toFixed(1)}km` : `${Math.round(meters)}m`; return meters >= 1000 ? `${(meters / 1000).toFixed(1)}km` : `${Math.round(meters)}m`;
}; };
/** 格式化时间(秒 → "XX分钟") */
const formatDuration = (seconds?: number) => { const formatDuration = (seconds?: number) => {
if (!seconds || seconds <= 0) return null; if (!seconds || seconds <= 0) return null;
const min = Math.round(seconds / 60); const min = Math.round(seconds / 60);
@@ -55,10 +54,11 @@ const LeftPanel: React.FC<LeftPanelProps> = ({
}) => { }) => {
const battery = boatData?.battery ?? 0; const battery = boatData?.battery ?? 0;
const isOnline = sseConnected; const isOnline = sseConnected;
const boatPosition = getValidCoordinate(boatData?.longitude, boatData?.latitude);
const hasBoatPosition = !!boatPosition;
return ( return (
<div className={styles.panel}> <div className={styles.panel}>
{/* ========== 设备状态卡片 ========== */}
<div className={`${styles.infoCard} ${styles.deviceCard}`}> <div className={`${styles.infoCard} ${styles.deviceCard}`}>
<div className={styles.cardHeader}> <div className={styles.cardHeader}>
<span className={styles.cardTitle}>设备状态</span> <span className={styles.cardTitle}>设备状态</span>
@@ -74,7 +74,7 @@ const LeftPanel: React.FC<LeftPanelProps> = ({
GPS 信号 GPS 信号
</span> </span>
<span className={`${styles.cardValue} ${styles.cardValueGreen}`}> <span className={`${styles.cardValue} ${styles.cardValueGreen}`}>
{boatData?.longitude ? '强' : '弱'} {hasBoatPosition ? '已定位' : '未定位'}
</span> </span>
</div> </div>
@@ -84,8 +84,8 @@ const LeftPanel: React.FC<LeftPanelProps> = ({
当前位置 当前位置
</span> </span>
<span className={`${styles.cardValue} ${styles.cardValueCyan}`}> <span className={`${styles.cardValue} ${styles.cardValueCyan}`}>
{boatData?.longitude {hasBoatPosition
? `${boatData.longitude.toFixed(2)}°E ${boatData.latitude.toFixed(2)}°N` ? `${boatPosition!.longitude.toFixed(4)}°E ${boatPosition!.latitude.toFixed(4)}°N`
: '--'} : '--'}
</span> </span>
</div> </div>
@@ -131,12 +131,10 @@ const LeftPanel: React.FC<LeftPanelProps> = ({
</div> </div>
</div> </div>
{/* ========== 分隔线 ========== */}
<div className={styles.divider} /> <div className={styles.divider} />
{/* ========== 航线区域 ========== */}
<div className={styles.routeHeader}> <div className={styles.routeHeader}>
<span className={styles.routeHeaderTitle}>浏览线路</span> <span className={styles.routeHeaderTitle}>航线列表</span>
<span className={styles.routeCountBadge}> <span className={styles.routeCountBadge}>
{routes.length} 条航线 {routes.length} 条航线
<DownOutlined style={{ fontSize: 8 }} /> <DownOutlined style={{ fontSize: 8 }} />
@@ -172,11 +170,13 @@ const LeftPanel: React.FC<LeftPanelProps> = ({
</div> </div>
<span className={`${styles.badge} ${styles.badgeGreen}`}>就绪</span> <span className={`${styles.badge} ${styles.badgeGreen}`}>就绪</span>
</div> </div>
<div className={styles.routeMeta}> <div className={styles.routeMeta}>
{wpCount}个航点{distance ? ` · 约${distance}` : ''}{duration ? ` · 预计${duration}` : ''} {wpCount} 个航点
{distance ? ` · 约 ${distance}` : ''}
{duration ? ` · 预计 ${duration}` : ''}
</div> </div>
{/* 选中时显示操作按钮 */}
{isSelected && ( {isSelected && (
<div className={styles.routeActions} onClick={(e) => e.stopPropagation()}> <div className={styles.routeActions} onClick={(e) => e.stopPropagation()}>
<button <button
@@ -191,7 +191,12 @@ const LeftPanel: React.FC<LeftPanelProps> = ({
className={styles.btnExecute} className={styles.btnExecute}
disabled={sailingLoading} disabled={sailingLoading}
onClick={(e) => { e.stopPropagation(); onStartSailing(route.routeId); }} onClick={(e) => { e.stopPropagation(); onStartSailing(route.routeId); }}
onTouchEnd={(e) => { if (sailingLoading) return; e.stopPropagation(); e.preventDefault(); onStartSailing(route.routeId); }} onTouchEnd={(e) => {
if (sailingLoading) return;
e.stopPropagation();
e.preventDefault();
onStartSailing(route.routeId);
}}
> >
<PlayCircleOutlined /> <PlayCircleOutlined />
{sailingLoading ? '启动中...' : '执行航线'} {sailingLoading ? '启动中...' : '执行航线'}
@@ -203,6 +208,7 @@ const LeftPanel: React.FC<LeftPanelProps> = ({
})} })}
</div> </div>
)} )}
{routes.length > 2 && <div className={styles.scrollHint}>上下滑动查看更多航线</div>} {routes.length > 2 && <div className={styles.scrollHint}>上下滑动查看更多航线</div>}
</div> </div>
</div> </div>
@@ -15,10 +15,26 @@ interface RightPanelProps {
sseConnected: boolean; 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 RightPanel: React.FC<RightPanelProps> = ({ deviceInfo, boatData, sseConnected }) => {
const heading = useMemo(() => boatData?.heading ?? 0, [boatData?.heading]); const heading = useMemo(() => boatData?.heading ?? 0, [boatData?.heading]);
const speed = useMemo(() => boatData?.speed ?? 0, [boatData?.speed]); const speed = useMemo(() => boatData?.speed ?? 0, [boatData?.speed]);
const battery = useMemo(() => boatData?.battery ?? 0, [boatData?.battery]); const battery = useMemo(() => boatData?.battery ?? 0, [boatData?.battery]);
const boatPosition = useMemo(() => getBoatPosition(boatData), [boatData?.longitude, boatData?.latitude]);
const [targetSpeed, setTargetSpeed] = useState(5); const [targetSpeed, setTargetSpeed] = useState(5);
const activeCommandRef = useRef<string | null>(null); const activeCommandRef = useRef<string | null>(null);
@@ -219,8 +235,8 @@ const RightPanel: React.FC<RightPanelProps> = ({ deviceInfo, boatData, sseConnec
<div className={styles.dataRow}> <div className={styles.dataRow}>
<span className={styles.dataLabel}>GPS</span> <span className={styles.dataLabel}>GPS</span>
<span className={styles.dataValue}> <span className={styles.dataValue}>
{boatData?.longitude != null {boatPosition
? `${boatData.longitude.toFixed(4)}, ${boatData.latitude?.toFixed(4)}` ? `${boatPosition.longitude.toFixed(4)}, ${boatPosition.latitude.toFixed(4)}`
: '--'} : '--'}
</span> </span>
</div> </div>
@@ -4,9 +4,48 @@
*/ */
import { useState, useRef, useEffect, useCallback } from 'react'; import { useState, useRef, useEffect, useCallback } from 'react';
import type { BoatTelemetryData } from '@/types/boatRoute'; import type { BoatTelemetryData } from '@/types/boatRoute';
import { getValidCoordinate } from '@/utils/geo';
const IDLE_TIMEOUT_MS = 30 * 60 * 1000; const IDLE_TIMEOUT_MS = 30 * 60 * 1000;
const toNumberOrZero = (value: unknown): number => {
const numeric = Number(value);
return Number.isFinite(numeric) ? numeric : 0;
};
const unusedToFiniteNumber = (value: unknown): number | undefined => {
if (value === null || value === undefined || value === '') return undefined;
const numeric = Number(value);
return Number.isFinite(numeric) ? numeric : undefined;
};
const unusedIsValidCoordinate = (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 position = getValidCoordinate(
rawData?.longitude ?? rawData?.lng ?? rawData?.lon ?? rawData?.gps?.longitude ?? rawData?.position?.longitude,
rawData?.latitude ?? rawData?.lat ?? rawData?.gps?.latitude ?? rawData?.position?.latitude,
);
return {
...rawData,
deviceSn: rawData?.deviceSn || deviceSn,
longitude: position?.longitude,
latitude: position?.latitude,
heading: toNumberOrZero(rawData?.heading ?? rawData?.direction ?? rawData?.yaw),
speed: toNumberOrZero(rawData?.speed),
battery: toNumberOrZero(rawData?.battery ?? rawData?.batteryPercent),
signalStrength: toNumberOrZero(rawData?.signalStrength),
status: rawData?.status ?? rawData?.deviceStatus ?? '',
recordTime: rawData?.recordTime ?? new Date().toISOString(),
} as BoatTelemetryData;
};
export interface UseClientSSEReturn { export interface UseClientSSEReturn {
boatData: BoatTelemetryData | null; boatData: BoatTelemetryData | null;
sseConnected: boolean; sseConnected: boolean;
@@ -135,12 +174,14 @@ export const useClientSSE = (): UseClientSSEReturn => {
const decoder = new TextDecoder(); const decoder = new TextDecoder();
let buffer = ''; let buffer = '';
let currentEvent = 'message';
let currentData = '';
const handleSSEEvent = (eventName: string, data: string) => { const handleSSEEvent = (eventName: string, data: string) => {
if (eventName === 'boat-telemetry') { if (eventName === 'boat-telemetry') {
try { try {
const parsed = JSON.parse(data) as BoatTelemetryData; const parsed = JSON.parse(data);
setBoatData(parsed); setBoatData(normalizeTelemetryData(parsed, deviceSn));
} catch (e) { } catch (e) {
console.warn('[ClientSSE] 解析遥测数据失败:', e); console.warn('[ClientSSE] 解析遥测数据失败:', e);
} }
@@ -164,14 +205,13 @@ export const useClientSSE = (): UseClientSSEReturn => {
const lines = buffer.split('\n'); const lines = buffer.split('\n');
buffer = lines.pop() || ''; buffer = lines.pop() || '';
let currentEvent = 'message'; for (const rawLine of lines) {
let currentData = ''; const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
for (const line of lines) {
if (line.startsWith('event:')) { if (line.startsWith('event:')) {
currentEvent = line.substring(6).trim(); currentEvent = line.substring(6).trim();
} else if (line.startsWith('data:')) { } 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 === '') { } else if (line === '') {
if (currentData) { if (currentData) {
handleSSEEvent(currentEvent, currentData); handleSSEEvent(currentEvent, currentData);
@@ -5,7 +5,8 @@
* 暂停/恢复/结束:调用真实无人船控制API,携带missionCode * 暂停/恢复/结束:调用真实无人船控制API,携带missionCode
*/ */
import { useState, useCallback, useRef } from 'react'; import { useState, useCallback, useRef } from 'react';
import { Modal, message } from 'antd'; import { Modal } from 'antd';
import type { MessageInstance } from 'antd/es/message/interface';
import { import {
createBoatMission, createBoatMission,
pauseBoatMission, pauseBoatMission,
@@ -46,6 +47,8 @@ export function useNavigationState(
selectedRouteId: string | null, selectedRouteId: string | null,
setSelectedRouteId: (id: string | null) => void, setSelectedRouteId: (id: string | null) => void,
routes: BoatRouteListVO[], routes: BoatRouteListVO[],
messageApi?: MessageInstance,
modalApi?: { confirm: (config: any) => void },
): UseNavigationStateReturn { ): UseNavigationStateReturn {
const [activeRoute, setActiveRoute] = useState<ActiveRouteState>({ mode: null, routeId: null }); const [activeRoute, setActiveRoute] = useState<ActiveRouteState>({ mode: null, routeId: null });
const [isPaused, setIsPaused] = useState(false); const [isPaused, setIsPaused] = useState(false);
@@ -64,12 +67,12 @@ export function useNavigationState(
const handleStartSailing = useCallback(async (routeId: string) => { const handleStartSailing = useCallback(async (routeId: string) => {
if (!deviceSn) { if (!deviceSn) {
message.error('设备SN缺失,无法开始航行'); messageApi?.error('设备SN缺失,无法开始航行');
return; return;
} }
const route = routes.find((r) => r.routeId === routeId); const route = routes.find((r) => r.routeId === routeId);
if (!route) { if (!route) {
message.error('航线信息不存在'); messageApi?.error('航线信息不存在');
return; return;
} }
@@ -88,13 +91,13 @@ export function useNavigationState(
}); });
if (res.resp_code !== 0) { if (res.resp_code !== 0) {
message.error(res.resp_msg || '创建任务失败'); messageApi?.error(res.resp_msg || '创建任务失败');
return; return;
} }
const code = res.data?.missionCode; const code = res.data?.missionCode;
if (!code) { if (!code) {
message.error('任务创建成功但未返回任务编码'); messageApi?.error('任务创建成功但未返回任务编码');
return; return;
} }
@@ -104,45 +107,45 @@ export function useNavigationState(
setSelectedRouteId(routeId); setSelectedRouteId(routeId);
setIsPaused(false); setIsPaused(false);
setCurrentWaypointIndex(0); setCurrentWaypointIndex(0);
message.success('航行任务已启动'); messageApi?.success('航行任务已启动');
} catch (e: any) { } catch (e: any) {
message.error(e?.message || '启动航行失败,请重试'); messageApi?.error(e?.message || '启动航行失败,请重试');
} finally { } finally {
setSailingLoading(false); setSailingLoading(false);
} }
}, [deviceSn, routes, activeRoute.mode, setSelectedRouteId]); }, [deviceSn, routes, activeRoute.mode, setSelectedRouteId, messageApi]);
const handlePauseSailing = useCallback(() => { const handlePauseSailing = useCallback(() => {
if (!isSailing) return; if (!isSailing) return;
const code = missionCodeRef.current; const code = missionCodeRef.current;
if (!code) { if (!code) {
message.warning('任务编码缺失,无法暂停'); messageApi?.warning('任务编码缺失,无法暂停');
return; return;
} }
setIsPaused(true); setIsPaused(true);
pauseBoatMission(deviceSn, code).catch(() => { pauseBoatMission(deviceSn, code).catch(() => {
message.error('暂停指令发送失败'); messageApi?.error('暂停指令发送失败');
setIsPaused(false); setIsPaused(false);
}); });
}, [deviceSn, isSailing]); }, [deviceSn, isSailing, messageApi]);
const handleResumeSailing = useCallback(() => { const handleResumeSailing = useCallback(() => {
if (!isSailing) return; if (!isSailing) return;
const code = missionCodeRef.current; const code = missionCodeRef.current;
if (!code) { if (!code) {
message.warning('任务编码缺失,无法恢复'); messageApi?.warning('任务编码缺失,无法恢复');
return; return;
} }
setIsPaused(false); setIsPaused(false);
resumeBoatMission(deviceSn, code).catch(() => { resumeBoatMission(deviceSn, code).catch(() => {
message.error('恢复航行指令发送失败'); messageApi?.error('恢复航行指令发送失败');
setIsPaused(true); setIsPaused(true);
}); });
}, [deviceSn, isSailing]); }, [deviceSn, isSailing, messageApi]);
const handleStopSailing = useCallback(() => { const handleStopSailing = useCallback(() => {
const code = missionCodeRef.current; const code = missionCodeRef.current;
Modal.confirm({ (modalApi || Modal).confirm({
title: '确认结束航行', title: '确认结束航行',
content: '结束后将退出导航模式,返回线路选择', content: '结束后将退出导航模式,返回线路选择',
okText: '结束航行', okText: '结束航行',
@@ -155,12 +158,12 @@ export function useNavigationState(
setMissionCode(null); setMissionCode(null);
if (code) { if (code) {
undoBoatMission(deviceSn, code).catch(() => { undoBoatMission(deviceSn, code).catch(() => {
message.warning('终止指令发送失败,但已退出导航模式'); messageApi?.warning('终止指令发送失败,但已退出导航模式');
}); });
} }
}, },
}); });
}, [deviceSn]); }, [deviceSn, modalApi, messageApi]);
const handleStopPreview = useCallback(() => { const handleStopPreview = useCallback(() => {
setPreviewStopSignal((prev) => prev + 1); setPreviewStopSignal((prev) => prev + 1);
@@ -175,11 +178,11 @@ export function useNavigationState(
setMissionCode(null); setMissionCode(null);
if (code) { if (code) {
undoBoatMission(deviceSn, code).catch(() => { undoBoatMission(deviceSn, code).catch(() => {
message.warning('紧急停靠指令发送失败'); messageApi?.warning('紧急停靠指令发送失败');
}); });
} }
message.warning('已执行紧急停靠'); messageApi?.warning('已执行紧急停靠');
}, [deviceSn]); }, [deviceSn, messageApi]);
const handlePreviewChange = useCallback((previewing: boolean) => { const handlePreviewChange = useCallback((previewing: boolean) => {
setActiveRoute((prev) => { setActiveRoute((prev) => {
File diff suppressed because it is too large Load Diff
@@ -189,6 +189,17 @@
flex: 1; flex: 1;
height: 100%; height: 100%;
position: relative; position: relative;
min-width: 0;
}
.execRightPanel {
width: 340px;
height: 100%;
flex-shrink: 0;
@media (max-width: 1366px) {
width: 300px;
}
} }
/* ========== 沉浸模式标记 ========== */ /* ========== 沉浸模式标记 ========== */
+282 -200
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useCallback, useState, useRef, useMemo } from 'react'; import React, { useEffect, useCallback, useState, useRef, useMemo } from 'react';
import { ConfigProvider, Button, Spin } from 'antd'; import { App as AntdApp, ConfigProvider, Button, Spin, message, Modal } from 'antd';
import { import {
LogoutOutlined, LogoutOutlined,
DisconnectOutlined, DisconnectOutlined,
@@ -19,14 +19,15 @@ import LeftPanel from './components/LeftPanel';
import CenterView from './components/CenterView'; import CenterView from './components/CenterView';
import ExecLeftPanel from './components/ExecLeftPanel'; import ExecLeftPanel from './components/ExecLeftPanel';
import ExecBottomStrip from './components/ExecBottomStrip'; import ExecBottomStrip from './components/ExecBottomStrip';
import ExecRightPanel from './components/ExecRightPanel';
import { useClientAuth } from './hooks/useClientAuth'; import { useClientAuth } from './hooks/useClientAuth';
import { useClientSSE } from './hooks/useClientSSE'; import { useClientSSE } from './hooks/useClientSSE';
import { useRouteData } from './hooks/useRouteData'; import { useRouteData } from './hooks/useRouteData';
import { useNavigationState } from './hooks/useNavigationState'; import { useNavigationState } from './hooks/useNavigationState';
import { useNavigationData } from './hooks/useNavigationData'; import { useNavigationData } from './hooks/useNavigationData';
import { getValidCoordinate } from '@/utils/geo';
import styles from './index.less'; import styles from './index.less';
/** 船 Logo SVG */
const ShipLogoIcon: React.FC = () => ( const ShipLogoIcon: React.FC = () => (
<svg width="20" height="20" viewBox="0 0 36 36" fill="none"> <svg width="20" height="20" viewBox="0 0 36 36" fill="none">
<path d="M6 27L8.4 21H27.6L30 27C30 27 25.5 30 18 30C10.5 30 6 27 6 27Z" fill="white" fillOpacity="0.9" /> <path d="M6 27L8.4 21H27.6L30 27C30 27 25.5 30 18 30C10.5 30 6 27 6 27Z" fill="white" fillOpacity="0.9" />
@@ -36,7 +37,6 @@ const ShipLogoIcon: React.FC = () => (
</svg> </svg>
); );
/** 格式化秒数为 HH:MM:SS */
const formatElapsed = (totalSec: number) => { const formatElapsed = (totalSec: number) => {
const h = Math.floor(totalSec / 3600).toString().padStart(2, '0'); const h = Math.floor(totalSec / 3600).toString().padStart(2, '0');
const m = Math.floor((totalSec % 3600) / 60).toString().padStart(2, '0'); const m = Math.floor((totalSec % 3600) / 60).toString().padStart(2, '0');
@@ -44,18 +44,58 @@ const formatElapsed = (totalSec: number) => {
return `${h}:${m}:${s}`; return `${h}:${m}:${s}`;
}; };
const calculateDistanceMeters = (
from: { longitude: number; latitude: number },
to: { longitude: number; latitude: number },
) => {
const earthRadius = 6371000;
const dLat = (to.latitude - from.latitude) * Math.PI / 180;
const dLon = (to.longitude - from.longitude) * Math.PI / 180;
const lat1 = from.latitude * Math.PI / 180;
const lat2 = to.latitude * Math.PI / 180;
const a = Math.sin(dLat / 2) ** 2
+ Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2;
return earthRadius * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
};
const ClientPage: React.FC = () => { const ClientPage: React.FC = () => {
// ── 认证 ── const [messageApi, messageContextHolder] = message.useMessage();
const { boatData: sseBoatData, sseConnected, loading: sseLoading, deviceOffline, connectSSE, disconnectSSE } = useClientSSE(); const [modalApi, modalContextHolder] = Modal.useModal();
const {
boatData: sseBoatData,
sseConnected,
loading: sseLoading,
deviceOffline,
connectSSE,
disconnectSSE,
} = useClientSSE();
const { deviceSn, deviceInfo, handleLogout } = useClientAuth(disconnectSSE); const { deviceSn, deviceInfo, handleLogout } = useClientAuth(disconnectSSE);
// ── 航线数据 ── const {
const { routes, routeWaypointsMap, selectedRouteId, setSelectedRouteId, routeLoading } = routes,
useRouteData(deviceSn); routeWaypointsMap,
selectedRouteId,
setSelectedRouteId,
routeLoading,
} = useRouteData(deviceSn);
const boatData = sseBoatData; const boatData = sseBoatData;
const boatPosition = useMemo(
() => getValidCoordinate(boatData?.longitude, boatData?.latitude),
[boatData?.longitude, boatData?.latitude],
);
const hasBoatPosition = !!boatPosition;
const videoStreamUrl = useMemo(() => {
const rawInfo = deviceInfo as any;
return rawInfo?.videoStreamUrl
|| rawInfo?.whepUrl
|| rawInfo?.streamUrl
|| rawInfo?.videoUrl
|| rawInfo?.liveStreamUrl
|| undefined;
}, [deviceInfo]);
// ── 沉浸模式状态机 ──
const { const {
isPaused, isPaused,
currentWaypointIndex, currentWaypointIndex,
@@ -70,43 +110,85 @@ const ClientPage: React.FC = () => {
handleResumeSailing, handleResumeSailing,
handleStopSailing, handleStopSailing,
handleStopPreview, handleStopPreview,
handleEmergencyStop,
handlePreviewChange, handlePreviewChange,
} = useNavigationState(deviceSn, selectedRouteId, setSelectedRouteId, routes); } = useNavigationState(deviceSn, selectedRouteId, setSelectedRouteId, routes, messageApi, modalApi);
// ── SSE 连接 ──
useEffect(() => { useEffect(() => {
if (!deviceSn) return; if (!deviceSn) return;
connectSSE(deviceSn); connectSSE(deviceSn);
return () => { disconnectSSE(); }; return () => {
}, [deviceSn]); disconnectSSE();
};
}, [deviceSn, connectSSE, disconnectSSE]);
// ── 沉浸模式计时器 ──
const [elapsed, setElapsed] = useState(0); const [elapsed, setElapsed] = useState(0);
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null); const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const [previewStartSignal, setPreviewStartSignal] = useState(0); const [previewStartSignal, setPreviewStartSignal] = useState(0);
useEffect(() => { useEffect(() => {
if (isImmersive && !isPaused) { if (isImmersive && !isPaused) {
timerRef.current = setInterval(() => setElapsed((s) => s + 1), 1000); timerRef.current = setInterval(() => setElapsed((seconds) => seconds + 1), 1000);
} else if (timerRef.current) { } else if (timerRef.current) {
clearInterval(timerRef.current); clearInterval(timerRef.current);
timerRef.current = null; timerRef.current = null;
} }
if (!isImmersive) setElapsed(0);
return () => { if (timerRef.current) clearInterval(timerRef.current); }; if (!isImmersive) {
setElapsed(0);
}
return () => {
if (timerRef.current) clearInterval(timerRef.current);
};
}, [isImmersive, isPaused]); }, [isImmersive, isPaused]);
// ── 预览航线回调 ──
const handlePreviewRoute = useCallback((routeId: string) => { const handlePreviewRoute = useCallback((routeId: string) => {
if (routeId !== selectedRouteId) { if (routeId !== selectedRouteId) {
setSelectedRouteId(routeId); setSelectedRouteId(routeId);
} }
// 延迟递增信号,让 selectedRouteId 先生效触发航点加载 setTimeout(() => setPreviewStartSignal((signal) => signal + 1), 200);
setTimeout(() => setPreviewStartSignal((s) => s + 1), 200);
}, [selectedRouteId, setSelectedRouteId]); }, [selectedRouteId, setSelectedRouteId]);
// ── 预先计算航线基础信息(不依赖 boatData) ── const handleExecuteRoute = useCallback(async (routeId: string) => {
const firstWaypoint = routeWaypointsMap[routeId]?.[0];
if (!firstWaypoint) {
messageApi.warning('当前航线缺少起始航点,无法执行');
return;
}
if (!hasBoatPosition) {
messageApi.warning('尚未收到无人船实时位置,暂时不能执行航线');
return;
}
const distance = calculateDistanceMeters(
boatPosition!,
{ longitude: firstWaypoint.longitude, latitude: firstWaypoint.latitude },
);
if (distance > 200) {
modalApi.warning({
title: '无法执行航线',
centered: true,
width: 500,
okText: '知道了',
content: (
<div style={{ paddingTop: 8, textAlign: 'center', lineHeight: 1.9, fontSize: 16 }}>
<div>
无人船距离航线起点约
<span style={{ color: '#ff7875', fontWeight: 700, margin: '0 6px' }}>
{Math.round(distance)} 米
</span>
</div>
<div>已超过 200 米,请先将无人船驶近起点后再执行。</div>
</div>
),
});
return;
}
await handleStartSailing(routeId);
}, [routeWaypointsMap, boatPosition, hasBoatPosition, handleStartSailing, messageApi, modalApi]);
const activeWaypointsRaw = useMemo(() => { const activeWaypointsRaw = useMemo(() => {
if (!activeRouteId) return []; if (!activeRouteId) return [];
return routeWaypointsMap[activeRouteId] || []; return routeWaypointsMap[activeRouteId] || [];
@@ -114,45 +196,40 @@ const ClientPage: React.FC = () => {
const activeRouteInfoRaw = useMemo(() => { const activeRouteInfoRaw = useMemo(() => {
if (!activeRouteId) return null; if (!activeRouteId) return null;
return routes.find((r) => r.routeId === activeRouteId) || null; return routes.find((route) => route.routeId === activeRouteId) || null;
}, [activeRouteId, routes]); }, [activeRouteId, routes]);
// ── 预览模式假数据 ──
const effectiveBoatData = useMemo(() => { const effectiveBoatData = useMemo(() => {
if (!isPreviewing) return boatData; if (!isPreviewing) return boatData;
// 如果有真实 SSE 数据,优先使用 if (hasBoatPosition) return boatData;
if (boatData?.longitude) return boatData;
// 预览模式下根据航线航点和经过时间生成模拟遥测数据
if (activeWaypointsRaw.length === 0) return null; if (activeWaypointsRaw.length === 0) return null;
const previewSpeed = 2; // m/s,与预览动画速度一致 const previewSpeed = 2;
const totalDist = activeRouteInfoRaw?.totalDistance || 1000; const totalDist = activeRouteInfoRaw?.totalDistance || 1000;
const traveled = elapsed * previewSpeed; const traveled = elapsed * previewSpeed;
const fraction = Math.min(traveled / totalDist, 0.99); const fraction = Math.min(traveled / totalDist, 0.99);
const wpIdx = Math.min( const waypointIdx = Math.min(
Math.floor(fraction * (activeWaypointsRaw.length - 1)), Math.floor(fraction * (activeWaypointsRaw.length - 1)),
activeWaypointsRaw.length - 2, activeWaypointsRaw.length - 2,
); );
const wp = activeWaypointsRaw[wpIdx]; const waypoint = activeWaypointsRaw[waypointIdx];
const nextWp = activeWaypointsRaw[wpIdx + 1] || wp; const nextWaypoint = activeWaypointsRaw[waypointIdx + 1] || waypoint;
// 航段内插值 const segFraction = (fraction * (activeWaypointsRaw.length - 1)) - waypointIdx;
const segFrac = (fraction * (activeWaypointsRaw.length - 1)) - wpIdx; const longitude = waypoint.longitude + (nextWaypoint.longitude - waypoint.longitude) * segFraction;
const lon = wp.longitude + (nextWp.longitude - wp.longitude) * segFrac; const latitude = waypoint.latitude + (nextWaypoint.latitude - waypoint.latitude) * segFraction;
const lat = wp.latitude + (nextWp.latitude - wp.latitude) * segFrac;
// 计算航向 const dLon = (nextWaypoint.longitude - waypoint.longitude) * Math.PI / 180;
const dLon = (nextWp.longitude - wp.longitude) * Math.PI / 180; const lat1 = waypoint.latitude * Math.PI / 180;
const lat1 = wp.latitude * Math.PI / 180; const lat2 = nextWaypoint.latitude * Math.PI / 180;
const lat2 = nextWp.latitude * Math.PI / 180;
const y = Math.sin(dLon) * Math.cos(lat2); const y = Math.sin(dLon) * Math.cos(lat2);
const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon); const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
const heading = ((Math.atan2(y, x) * 180 / Math.PI) + 360) % 360; const heading = ((Math.atan2(y, x) * 180 / Math.PI) + 360) % 360;
return { return {
deviceSn: deviceSn || '', deviceSn: deviceSn || '',
longitude: lon, longitude,
latitude: lat, latitude,
heading, heading,
speed: previewSpeed, speed: previewSpeed,
battery: 85, battery: 85,
@@ -160,9 +237,8 @@ const ClientPage: React.FC = () => {
status: 'preview', status: 'preview',
recordTime: new Date().toISOString(), recordTime: new Date().toISOString(),
} as import('@/types/boatRoute').BoatTelemetryData; } as import('@/types/boatRoute').BoatTelemetryData;
}, [isPreviewing, boatData, activeWaypointsRaw, activeRouteInfoRaw, elapsed, deviceSn]); }, [isPreviewing, boatData, hasBoatPosition, activeWaypointsRaw, activeRouteInfoRaw, elapsed, deviceSn]);
// ── 导航计算(使用 effectiveBoatData 以便预览模式也有数据) ──
const { const {
activeWaypoints, activeWaypoints,
activeRouteInfo, activeRouteInfo,
@@ -178,190 +254,196 @@ const ClientPage: React.FC = () => {
return ( return (
<ConfigProvider theme={darkTheme}> <ConfigProvider theme={darkTheme}>
<div className={`${styles.container} ${isImmersive ? styles.sailing : ''}`}> <AntdApp>
{messageContextHolder}
{/* ========== 普通模式 - 顶部导航栏 ========== */} {modalContextHolder}
{!isImmersive && ( <div className={`${styles.container} ${isImmersive ? styles.sailing : ''}`}>
<div className={styles.navBar}> {!isImmersive && (
<div className={styles.navLogo}> <div className={styles.navBar}>
<div className={styles.navLogoIcon}><ShipLogoIcon /></div> <div className={styles.navLogo}>
<span className={styles.navLogoText}>WAVE PILOT</span> <div className={styles.navLogoIcon}><ShipLogoIcon /></div>
</div> <span className={styles.navLogoText}>WAVE PILOT</span>
<div className={styles.navSpacer} />
<div className={styles.navTabs}>
<div className={`${styles.navTab} ${styles.navTabActive}`}>
<EnvironmentOutlined />
<span>航线管理</span>
</div> </div>
<div className={styles.navTab}>
<EyeOutlined />
<span>实时监控</span>
</div>
<div className={styles.navTab}>
<HistoryOutlined />
<span>历史记录</span>
</div>
</div>
<div className={styles.navSpacer} /> <div className={styles.navSpacer} />
<div className={styles.navRight}> <div className={styles.navTabs}>
<WifiOutlined className={styles.navIconBtn} /> <div className={`${styles.navTab} ${styles.navTabActive}`}>
<ThunderboltOutlined className={styles.navIconBtn} /> <EnvironmentOutlined />
<div className={styles.devIndicator}> <span>航线管理</span>
<span </div>
className={styles.devDot} <div className={styles.navTab}>
style={{ background: sseConnected ? '#10b981' : '#ff4d4f' }} <EyeOutlined />
<span>实时监控</span>
</div>
<div className={styles.navTab}>
<HistoryOutlined />
<span>历史记录</span>
</div>
</div>
<div className={styles.navSpacer} />
<div className={styles.navRight}>
<WifiOutlined className={styles.navIconBtn} />
<ThunderboltOutlined className={styles.navIconBtn} />
<div className={styles.devIndicator}>
<span
className={styles.devDot}
style={{ background: sseConnected ? '#10b981' : '#ff4d4f' }}
/>
<span className={styles.devSn}>{deviceInfo.deviceName || deviceSn}</span>
</div>
<Button
type="text"
icon={<LogoutOutlined />}
onClick={handleLogout}
className={styles.navLogoutBtn}
size="small"
/> />
<span className={styles.devSn}>{deviceInfo.deviceName || deviceSn}</span>
</div>
<Button
type="text"
icon={<LogoutOutlined />}
onClick={handleLogout}
className={styles.navLogoutBtn}
size="small"
/>
</div>
</div>
)}
{/* ========== 沉浸模式 - 执行导航栏 ========== */}
{isImmersive && (
<div className={styles.execNav}>
<button
className={styles.execBackBtn}
onClick={isPreviewing ? handleStopPreview : handleStopSailing}
>
<LeftOutlined />
</button>
<div className={styles.execTitleArea}>
<div className={styles.execTitle}>
{activeRouteInfo?.routeName || '航线'} · {modeLabel}
</div>
<div className={styles.execSubtitle}>
{deviceInfo.deviceName || deviceSn} · 已{isPreviewing ? '预览' : '执行'} {formatElapsed(elapsed)}
</div> </div>
</div> </div>
)}
<div className={styles.execBadge}> {isImmersive && (
<span className={styles.execBadgeDot} /> <div className={styles.execNav}>
<span>{modeLabel} {modeTag}</span>
</div>
<div className={styles.execSpacer} />
<div className={styles.execRight}>
{isSailing && (
<button
className={styles.execPauseBtn}
onClick={isPaused ? handleResumeSailing : handlePauseSailing}
>
{isPaused ? <CaretRightOutlined /> : <PauseOutlined />}
<span>{isPaused ? '继续' : '暂停'}</span>
</button>
)}
<button <button
className={styles.execStopBtn} className={styles.execBackBtn}
onClick={isPreviewing ? handleStopPreview : handleStopSailing} onClick={isPreviewing ? handleStopPreview : handleStopSailing}
> >
<StopOutlined /> <LeftOutlined />
<span>终止</span>
</button> </button>
</div>
</div>
)}
{/* ========== 主体区域 ========== */} <div className={styles.execTitleArea}>
<div className={styles.mainBody}> <div className={styles.execTitle}>
{activeRouteInfo?.routeName || '航线'} · {modeLabel}
{/* 设备离线遮罩 */}
{deviceOffline && !sseConnected && (
<div className={styles.offlineOverlay}>
<div className={styles.offlineCard}>
<DisconnectOutlined className={styles.offlineIcon} />
<div className={styles.offlineTitle}>设备不在线</div>
<div className={styles.offlineDesc}>
无法订阅设备 <span className={styles.offlineSn}>{deviceInfo.deviceName || deviceSn}</span> 的实时数据
<br />
{sseLoading ? '正在重新连接...' : '请检查设备是否已开机并接入网络'}
</div> </div>
{sseLoading ? ( <div className={styles.execSubtitle}>
<Spin size="small" style={{ marginTop: 16 }} /> {deviceInfo.deviceName || deviceSn} · {isPreviewing ? '预览' : '执行'} · {formatElapsed(elapsed)}
) : ( </div>
<Button </div>
icon={<ReloadOutlined />}
onClick={() => connectSSE(deviceSn)} <div className={styles.execBadge}>
style={{ marginTop: 16, borderColor: 'rgba(34,211,238,0.4)', color: '#22d3ee' }} <span className={styles.execBadgeDot} />
ghost <span>{modeLabel} {modeTag}</span>
</div>
<div className={styles.execSpacer} />
<div className={styles.execRight}>
{isSailing && (
<button
className={styles.execPauseBtn}
onClick={isPaused ? handleResumeSailing : handlePauseSailing}
> >
重试连接 {isPaused ? <CaretRightOutlined /> : <PauseOutlined />}
</Button> <span>{isPaused ? '继续' : '暂停'}</span>
</button>
)} )}
<button
className={styles.execStopBtn}
onClick={isPreviewing ? handleStopPreview : handleStopSailing}
>
<StopOutlined />
<span>终止</span>
</button>
</div> </div>
</div> </div>
)} )}
{/* 左侧边栏 - 普通模式 */} <div className={styles.mainBody}>
{!isImmersive && ( {deviceOffline && !sseConnected && (
<div className={styles.leftPanel}> <div className={styles.offlineOverlay}>
<LeftPanel <div className={styles.offlineCard}>
routes={routes} <DisconnectOutlined className={styles.offlineIcon} />
routeWaypointsMap={routeWaypointsMap} <div className={styles.offlineTitle}>设备不在线</div>
loading={routeLoading} <div className={styles.offlineDesc}>
selectedRouteId={selectedRouteId} 无法订阅设备 <span className={styles.offlineSn}>{deviceInfo.deviceName || deviceSn}</span> 的实时数据
onSelectRoute={setSelectedRouteId} <br />
deviceInfo={deviceInfo} {sseLoading ? '正在重新连接...' : '请检查设备是否已开机并接入网络'}
boatData={boatData} </div>
sseConnected={sseConnected} {sseLoading ? (
onStartSailing={handleStartSailing} <Spin size="small" style={{ marginTop: 16 }} />
onPreviewRoute={handlePreviewRoute} ) : (
sailingLoading={sailingLoading} <Button
/> icon={<ReloadOutlined />}
</div> onClick={() => connectSSE(deviceSn)}
)} style={{ marginTop: 16, borderColor: 'rgba(34,211,238,0.4)', color: '#22d3ee' }}
ghost
>
重试连接
</Button>
)}
</div>
</div>
)}
{/* 左侧面板 - 沉浸模式 (仪表盘 + 航点列表) */} {!isImmersive && (
{isImmersive && ( <div className={styles.leftPanel}>
<ExecLeftPanel <LeftPanel
boatData={effectiveBoatData} routes={routes}
waypoints={activeWaypoints} routeWaypointsMap={routeWaypointsMap}
currentWaypointIndex={currentWaypointIndex} loading={routeLoading}
/> selectedRouteId={selectedRouteId}
)} onSelectRoute={setSelectedRouteId}
deviceInfo={deviceInfo}
boatData={boatData}
sseConnected={sseConnected}
onStartSailing={handleExecuteRoute}
onPreviewRoute={handlePreviewRoute}
sailingLoading={sailingLoading}
/>
</div>
)}
{/* 地图区域 */}
<div className={styles.centerView}>
<CenterView
deviceSn={deviceSn}
routes={routes}
selectedRouteId={selectedRouteId}
boatData={boatData}
isSailing={isSailing}
sailingLoading={sailingLoading}
previewStartSignal={previewStartSignal}
previewStopSignal={previewStopSignal}
onStartSailing={handleStartSailing}
onPreviewChange={handlePreviewChange}
/>
{/* 沉浸模式 - 底部航线信息条 */}
{isImmersive && ( {isImmersive && (
<ExecBottomStrip <ExecLeftPanel
progress={progress} boatData={effectiveBoatData}
waypoints={activeWaypoints}
currentWaypointIndex={currentWaypointIndex} currentWaypointIndex={currentWaypointIndex}
totalWaypoints={activeWaypoints.length}
remainingDistance={remainingDistance}
estimatedRemainingTime={estimatedRemainingTime}
/> />
)} )}
</div>
<div className={styles.centerView}>
<CenterView
deviceSn={deviceSn}
routes={routes}
selectedRouteId={selectedRouteId}
boatData={boatData}
isSailing={isSailing}
sailingLoading={sailingLoading}
previewStartSignal={previewStartSignal}
previewStopSignal={previewStopSignal}
onStartSailing={handleStartSailing}
onPreviewChange={handlePreviewChange}
/>
{isSailing && (
<ExecBottomStrip
progress={progress}
currentWaypointIndex={currentWaypointIndex}
totalWaypoints={activeWaypoints.length}
remainingDistance={remainingDistance}
estimatedRemainingTime={estimatedRemainingTime}
/>
)}
</div>
{isImmersive && (
<div className={styles.execRightPanel}>
<ExecRightPanel
deviceInfo={deviceInfo}
boatData={effectiveBoatData}
activeRouteInfo={activeRouteInfo}
sseConnected={sseConnected}
videoStreamUrl={videoStreamUrl}
isPreviewing={isPreviewing}
/>
</div>
)}
</div>
</div> </div>
</div> </AntdApp>
</ConfigProvider> </ConfigProvider>
); );
}; };
@@ -457,11 +457,11 @@ const LayerPanel: React.FC<LayerPanelProps> = ({
// 忽略 // 忽略
} }
const positions = poly.outer.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)); const positions = poly.outer.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)).filter(Boolean);
if (positions.length < 3) return; if (positions.length < 3) return;
const holes = poly.holes const holes = poly.holes
.map((ring) => ring.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0))) .map((ring) => ring.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)).filter(Boolean))
.filter((ring) => ring.length >= 3) .filter((ring) => ring.length >= 3)
.map((ring) => new Cesium.PolygonHierarchy(ring)); .map((ring) => new Cesium.PolygonHierarchy(ring));
@@ -490,11 +490,13 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
? Cesium.Color.fromCssColorString('#52c41a').withAlpha(0.9) // 绿色 - 无人船 ? Cesium.Color.fromCssColorString('#52c41a').withAlpha(0.9) // 绿色 - 无人船
: Cesium.Color.fromCssColorString('#1890ff').withAlpha(0.9); // 蓝色 - 无人机 : Cesium.Color.fromCssColorString('#1890ff').withAlpha(0.9); // 蓝色 - 无人机
// 绘制航线 // 绘制航线(确保 positions 不含 undefined/null 值)
const validPolylinePositions = polylinePositions.filter(Boolean);
if (validPolylinePositions.length < 2) return;
waylineEntityRef.current = viewer.entities.add({ waylineEntityRef.current = viewer.entities.add({
name: isBoatRoute ? '无人船航线' : '无人机航线', name: isBoatRoute ? '无人船航线' : '无人机航线',
polyline: { polyline: {
positions: polylinePositions, positions: validPolylinePositions,
width: 6, width: 6,
material: routeColor, material: routeColor,
clampToGround: false, // 已经手动贴地,不需要clampToGround clampToGround: false, // 已经手动贴地,不需要clampToGround
@@ -6,6 +6,7 @@
*/ */
import { useEffect, useRef, useCallback, useMemo } from 'react'; import { useEffect, useRef, useCallback, useMemo } from 'react';
import { useBoatSSE } from './useBoatSSE'; import { useBoatSSE } from './useBoatSSE';
import { getValidCoordinate } from '@/utils/geo';
interface UseCesiumBoatTrackOptions { interface UseCesiumBoatTrackOptions {
viewerRef: React.RefObject<any>; viewerRef: React.RefObject<any>;
@@ -39,6 +40,9 @@ export function useCesiumBoatTrack({
return (window as any).Cesium; return (window as any).Cesium;
}, []); }, []);
// GLB 模型自身朝向补偿(模型建模方向与 Cesium 北向的偏差)
const MODEL_HEADING_OFFSET = -Math.PI / 2;
/** /**
* 飞到无人船位置 * 飞到无人船位置
*/ */
@@ -46,13 +50,14 @@ export function useCesiumBoatTrack({
const viewer = viewerRef.current; const viewer = viewerRef.current;
const Cesium = getCesium(); const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.()) return; if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
if (!boatData?.longitude || !boatData?.latitude) return; const boatPosition = getValidCoordinate(boatData?.longitude, boatData?.latitude);
if (!boatPosition) return;
try { try {
viewer.camera.flyTo({ viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees( destination: Cesium.Cartesian3.fromDegrees(
boatData.longitude, boatPosition.longitude,
boatData.latitude, boatPosition.latitude,
1000 // 视角高度1000米 1000 // 视角高度1000米
), ),
orientation: { orientation: {
@@ -119,9 +124,12 @@ export function useCesiumBoatTrack({
*/ */
const realtimePosition = useMemo(() => { const realtimePosition = useMemo(() => {
if (!boatData) return null; if (!boatData) return null;
const boatPosition = getValidCoordinate(boatData.longitude, boatData.latitude);
if (!boatPosition) return null;
return { return {
longitude: boatData.longitude, longitude: boatPosition.longitude,
latitude: boatData.latitude, latitude: boatPosition.latitude,
heading: boatData.heading ?? 0, heading: boatData.heading ?? 0,
speed: boatData.speed ?? 0, speed: boatData.speed ?? 0,
battery: boatData.battery ?? 0, battery: boatData.battery ?? 0,
@@ -138,7 +146,6 @@ export function useCesiumBoatTrack({
if (!viewer || !Cesium || viewer.isDestroyed?.()) return; if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
if (!realtimePosition) return; if (!realtimePosition) return;
if (!realtimePosition.longitude || !realtimePosition.latitude) return;
const now = Date.now(); const now = Date.now();
const currentPos = { const currentPos = {
@@ -170,6 +177,13 @@ export function useCesiumBoatTrack({
realtimePosition.latitude, realtimePosition.latitude,
0 // 无人船在水面,高度为0 0 // 无人船在水面,高度为0
); );
const headingRad = Cesium.Math.toRadians(realtimePosition.heading || 0);
const orientation = Cesium.Transforms?.headingPitchRollQuaternion
? Cesium.Transforms.headingPitchRollQuaternion(
position,
new Cesium.HeadingPitchRoll(headingRad + MODEL_HEADING_OFFSET, 0, 0)
)
: undefined;
// 构建标签文本 // 构建标签文本
const labelText = [ const labelText = [
@@ -182,19 +196,26 @@ export function useCesiumBoatTrack({
// 更新或创建船位置Entity // 更新或创建船位置Entity
if (boatEntityRef.current) { if (boatEntityRef.current) {
boatEntityRef.current.position = position; boatEntityRef.current.position = position;
if (orientation) {
boatEntityRef.current.orientation = orientation;
}
if (boatEntityRef.current.label) { if (boatEntityRef.current.label) {
boatEntityRef.current.label.text = labelText; boatEntityRef.current.label.text = labelText;
} }
} else { } else {
boatEntityRef.current = viewer.entities.add({ boatEntityRef.current = viewer.entities.add({
name: '无人船实时位置', name: '无人船实时位置',
position: position, position,
point: { orientation,
pixelSize: 16, model: {
color: Cesium.Color.BLUE, uri: `${process.env.CESIUM_BASE_URL || '/'}chuan-model.glb`,
outlineColor: Cesium.Color.WHITE, scale: 0.001,
outlineWidth: 3, minimumPixelSize: 64,
disableDepthTestDistance: Number.POSITIVE_INFINITY, maximumScale: 200,
runAnimations: true,
colorBlendMode: Cesium.ColorBlendMode.HIGHLIGHT,
color: Cesium.Color.WHITE,
silhouetteSize: 0,
}, },
label: { label: {
text: labelText, text: labelText,
@@ -204,7 +225,7 @@ export function useCesiumBoatTrack({
outlineWidth: 2, outlineWidth: 2,
outlineColor: Cesium.Color.BLACK, outlineColor: Cesium.Color.BLACK,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM, verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -20), pixelOffset: new Cesium.Cartesian2(0, -28),
disableDepthTestDistance: Number.POSITIVE_INFINITY, disableDepthTestDistance: Number.POSITIVE_INFINITY,
}, },
properties: { properties: {
@@ -224,21 +245,21 @@ export function useCesiumBoatTrack({
} }
// 绘制飞行轨迹(至少2个点才能绘制线) // 绘制飞行轨迹(至少2个点才能绘制线)
if (trackPositionsRef.current.length >= 2) { const validTrackPositions = trackPositionsRef.current.filter(Boolean);
if (validTrackPositions.length >= 2) {
if (trackEntityRef.current) { if (trackEntityRef.current) {
trackEntityRef.current.polyline.positions = [...trackPositionsRef.current]; trackEntityRef.current.polyline.positions = validTrackPositions;
} else { } else {
trackEntityRef.current = viewer.entities.add({ trackEntityRef.current = viewer.entities.add({
name: '无人船航行轨迹', name: '无人船航行轨迹',
polyline: { polyline: {
positions: [...trackPositionsRef.current], positions: validTrackPositions,
width: 4, width: 4,
material: new Cesium.PolylineGlowMaterialProperty({ material: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.3, glowPower: 0.3,
color: Cesium.Color.BLUE, color: Cesium.Color.BLUE,
}), }),
clampToGround: true, clampToGround: true,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
}, },
properties: { properties: {
type: 'boat-track', type: 'boat-track',
@@ -56,6 +56,8 @@ export interface UseTilesetLoaderResult {
export const useTilesetLoader = (): UseTilesetLoaderResult => { export const useTilesetLoader = (): UseTilesetLoaderResult => {
const [tilesets, setTilesets] = useState<Map<string, TilesetState>>(new Map()); const [tilesets, setTilesets] = useState<Map<string, TilesetState>>(new Map());
const tilesetsRef = useRef<Map<string, any>>(new Map()); const tilesetsRef = useRef<Map<string, any>>(new Map());
// 存储 loadProgress 事件移除函数,防止监听器泄漏
const progressListenersRef = useRef<Map<string, () => void>>(new Map());
/** /**
* 加载3D Tiles模型 * 加载3D Tiles模型
@@ -139,8 +141,8 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
show: config.visible !== false, show: config.visible !== false,
}); });
// 监听加载进度 // 监听加载进度(保存移除函数以便清理)
tileset.loadProgress.addEventListener((numberOfPendingRequests: number, numberOfTilesProcessing: number) => { const progressHandler = (numberOfPendingRequests: number, numberOfTilesProcessing: number) => {
const total = numberOfPendingRequests + numberOfTilesProcessing; const total = numberOfPendingRequests + numberOfTilesProcessing;
const progress = total > 0 ? Math.min(99, 100 - (total * 2)) : 100; const progress = total > 0 ? Math.min(99, 100 - (total * 2)) : 100;
@@ -152,7 +154,9 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
} }
return newMap; return newMap;
}); });
}); };
const removeListener = tileset.loadProgress.addEventListener(progressHandler);
progressListenersRef.current.set(config.id, removeListener);
// 模型位置调整 - 根据当前地形类型选择对应的高度偏移 // 模型位置调整 - 根据当前地形类型选择对应的高度偏移
if (config.position) { if (config.position) {
@@ -271,6 +275,13 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
* 卸载指定模型 * 卸载指定模型
*/ */
const unloadTileset = useCallback((id: string, viewer: any) => { const unloadTileset = useCallback((id: string, viewer: any) => {
// 移除 loadProgress 监听器
const removeListener = progressListenersRef.current.get(id);
if (removeListener) {
try { removeListener(); } catch { /* ignore */ }
progressListenersRef.current.delete(id);
}
const tileset = tilesetsRef.current.get(id); const tileset = tilesetsRef.current.get(id);
if (tileset && viewer && !viewer.isDestroyed?.() && viewer.scene) { if (tileset && viewer && !viewer.isDestroyed?.() && viewer.scene) {
viewer.scene.primitives.remove(tileset); viewer.scene.primitives.remove(tileset);
@@ -292,6 +303,12 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
const unloadAllTilesets = useCallback((viewer: any) => { const unloadAllTilesets = useCallback((viewer: any) => {
if (!viewer || viewer.isDestroyed?.() || !viewer.scene) return; if (!viewer || viewer.isDestroyed?.() || !viewer.scene) return;
// 移除所有 loadProgress 监听器
progressListenersRef.current.forEach((removeListener) => {
try { removeListener(); } catch { /* ignore */ }
});
progressListenersRef.current.clear();
tilesetsRef.current.forEach((tileset, id) => { tilesetsRef.current.forEach((tileset, id) => {
viewer.scene.primitives.remove(tileset); viewer.scene.primitives.remove(tileset);
}); });
@@ -11,6 +11,7 @@ import { useTilesetLoader, TilesetConfig } from './3d/hooks/useTilesetLoader';
import { useDroneSSE } from './3d/hooks/useDroneSSE'; import { useDroneSSE } from './3d/hooks/useDroneSSE';
import { getModelsByDeviceSn, convertToTilesetConfig } from '@/services/threeDModel'; import { getModelsByDeviceSn, convertToTilesetConfig } from '@/services/threeDModel';
import TilesetPanel from "@/pages/map3d/components/MapContainer/3d/TilesetPanel"; import TilesetPanel from "@/pages/map3d/components/MapContainer/3d/TilesetPanel";
import { getValidCoordinate } from '@/utils/geo';
// 动态导入Cesium // 动态导入Cesium
let Cesium: any = null; let Cesium: any = null;
@@ -95,10 +96,13 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
// 检查 viewer 是否已销毁 // 检查 viewer 是否已销毁
if (viewerRef.current.isDestroyed?.()) return; if (viewerRef.current.isDestroyed?.()) return;
const lon = parseFloat(device.longitude); let lon = parseFloat(device.longitude);
const lat = parseFloat(device.latitude); let lat = parseFloat(device.latitude);
if (isNaN(lon) || isNaN(lat)) return; const coordinate = getValidCoordinate(lon, lat);
if (!coordinate) return;
lon = coordinate.longitude;
lat = coordinate.latitude;
viewerRef.current.camera.flyTo({ viewerRef.current.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(lon, lat, 10000), // 10000m 高度 destination: Cesium.Cartesian3.fromDegrees(lon, lat, 10000), // 10000m 高度
@@ -492,9 +496,12 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
// 计算无人机实时位置 // 计算无人机实时位置
const realtimePosition = useMemo(() => { const realtimePosition = useMemo(() => {
if (!droneData) return null; if (!droneData) return null;
const coordinate = getValidCoordinate(droneData.longitude, droneData.latitude);
if (!coordinate) return null;
return { return {
longitude: droneData.longitude, longitude: coordinate.longitude,
latitude: droneData.latitude, latitude: coordinate.latitude,
height: droneData.height, // 相对高度(相对于起飞点) height: droneData.height, // 相对高度(相对于起飞点)
elevation: droneData.elevation, // 海拔高度(椭球高度) elevation: droneData.elevation, // 海拔高度(椭球高度)
// 3D地图显示用 height(相对高度),与航线的 height 对应 // 3D地图显示用 height(相对高度),与航线的 height 对应
@@ -605,14 +612,15 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
trackPositionsRef.current.push(pos); trackPositionsRef.current.push(pos);
// 绘制飞行轨迹 // 绘制飞行轨迹
if (trackPositionsRef.current.length >= 2) { const validTrackPositions = trackPositionsRef.current.filter(Boolean);
if (validTrackPositions.length >= 2) {
if (flightTrackEntityRef.current) { if (flightTrackEntityRef.current) {
flightTrackEntityRef.current.polyline.positions = [...trackPositionsRef.current]; flightTrackEntityRef.current.polyline.positions = validTrackPositions;
} else { } else {
flightTrackEntityRef.current = viewerRef.current.entities.add({ flightTrackEntityRef.current = viewerRef.current.entities.add({
name: '飞行轨迹', name: '飞行轨迹',
polyline: { polyline: {
positions: [...trackPositionsRef.current], positions: validTrackPositions,
width: 4, width: 4,
material: new Cesium.PolylineGlowMaterialProperty({ material: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.3, glowPower: 0.3,
@@ -823,6 +831,11 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
creditContainer.style.display = 'none'; creditContainer.style.display = 'none';
} }
// 捕获 Cesium 渲染循环中的错误,避免页面崩溃
viewerRef.current.scene.renderError.addEventListener((scene: any, error: any) => {
console.error('[CesiumContainer] 渲染循环错误:', error);
});
setLoading(false); setLoading(false);
setViewerReady(true); // Viewer 初始化完成 setViewerReady(true); // Viewer 初始化完成
console.log('[CesiumContainer] ✓ Viewer 初始化完成,viewerReady=true'); console.log('[CesiumContainer] ✓ Viewer 初始化完成,viewerReady=true');
@@ -861,7 +874,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
const validDevices = deviceList.filter((device) => { const validDevices = deviceList.filter((device) => {
const lat = parseFloat(device.latitude); const lat = parseFloat(device.latitude);
const lng = parseFloat(device.longitude); const lng = parseFloat(device.longitude);
return !isNaN(lat) && !isNaN(lng) && lat !== 0 && lng !== 0; return !!getValidCoordinate(lng, lat);
}); });
if (validDevices.length === 0) return; if (validDevices.length === 0) return;
@@ -1,6 +1,6 @@
/** /**
* Cesium 已规划航线渲染 Hook * Cesium 已规划航线渲�?Hook
* 负责在 Cesium 地图上渲染“航线库”里勾选显示的航线(只渲染线与起终点,避免太重) * 负责�?Cesium 地图上渲染“航线库”里勾选显示的航线(只渲染线与起终点,避免太重�?
*/ */
import { useCallback, useEffect, useMemo, useRef } from 'react'; import { useCallback, useEffect, useMemo, useRef } from 'react';
import type { BoatWaypointDTO } from '@/types/boatRoute'; import type { BoatWaypointDTO } from '@/types/boatRoute';
@@ -18,6 +18,11 @@ interface UseCesiumRouteLibraryRendererOptions {
routes: RouteLibraryRenderItem[]; routes: RouteLibraryRenderItem[];
} }
export interface RouteSurfaceGeometry {
polyline: any[];
waypointPositions: any[];
}
export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRendererOptions) { export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRendererOptions) {
const { viewerRef, routes } = options; const { viewerRef, routes } = options;
@@ -27,8 +32,8 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
const surfaceRetryRef = useRef<Map<string, { key: string; attempt: number; timer: any | null }>>(new Map()); const surfaceRetryRef = useRef<Map<string, { key: string; attempt: number; timer: any | null }>>(new Map());
const routesRef = useRef<RouteLibraryRenderItem[]>(routes); const routesRef = useRef<RouteLibraryRenderItem[]>(routes);
// 贴近模型表面,避免航线“悬浮” // 贴近模型表面,避免航线“悬浮�?
const ROUTE_RENDER_HEIGHT_OFFSET = 0.05; const ROUTE_RENDER_HEIGHT_OFFSET = 1.2;
const getCesium = useCallback(() => (window as any).Cesium, []); const getCesium = useCallback(() => (window as any).Cesium, []);
@@ -95,7 +100,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
return result; return result;
}, []); }, []);
const clampPositionsToModelSurface = useCallback(async (Cesium: any, positions: any[]) => { const clampPositionsToModelSurface = useCallback(async (Cesium: any, positions: any[], groundPositions?: any[]) => {
const viewer = viewerRef?.current; const viewer = viewerRef?.current;
if (!viewer || viewer.isDestroyed?.() || !Cesium) return null; if (!viewer || viewer.isDestroyed?.() || !Cesium) return null;
if (!Array.isArray(positions) || positions.length < 2) return null; if (!Array.isArray(positions) || positions.length < 2) return null;
@@ -108,21 +113,21 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
const clamped = await fn.call(scene, positions); const clamped = await fn.call(scene, positions);
if (!Array.isArray(clamped) || clamped.length !== positions.length) return null; if (!Array.isArray(clamped) || clamped.length !== positions.length) return null;
const fallbacks = groundPositions || positions;
let definedCount = 0; let definedCount = 0;
const merged = clamped.map((p: any, idx: number) => { const merged = clamped.map((p: any, idx: number) => {
if (p) definedCount++; if (p) definedCount++;
return p || positions[idx]; return p || fallbacks[idx];
}); });
if (definedCount < 2) return null; if (definedCount < 2) return merged.map((p: any) => applyHeightOffset(Cesium, p)).filter(Boolean); // If barely clamped, just return what we have (mixed with fallbacks) to prevent line breaks
return merged.map((p: any) => applyHeightOffset(Cesium, p)); return merged.map((p: any) => applyHeightOffset(Cesium, p)).filter(Boolean); } catch {
} catch {
return null; return null;
} }
}, [viewerRef, applyHeightOffset]); }, [viewerRef, applyHeightOffset]);
const clampWaypointsToModelSurface = useCallback(async (Cesium: any, positions: any[]) => { const clampWaypointsToModelSurface = useCallback(async (Cesium: any, positions: any[], groundPositions?: any[]) => {
const viewer = viewerRef?.current; const viewer = viewerRef?.current;
if (!viewer || viewer.isDestroyed?.() || !Cesium) return null; if (!viewer || viewer.isDestroyed?.() || !Cesium) return null;
if (!Array.isArray(positions) || positions.length < 1) return null; if (!Array.isArray(positions) || positions.length < 1) return null;
@@ -134,7 +139,11 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
try { try {
const clamped = await fn.call(scene, positions); const clamped = await fn.call(scene, positions);
if (!Array.isArray(clamped) || clamped.length !== positions.length) return null; if (!Array.isArray(clamped) || clamped.length !== positions.length) return null;
return clamped.map((p: any, idx: number) => applyHeightOffset(Cesium, p || positions[idx])); // �?clamp 失败时,用地面位置(高度0)而非 300m 探测位置
const fallbacks = groundPositions || positions;
const result = clamped.map((p: any, idx: number) => applyHeightOffset(Cesium, p || fallbacks[idx]));
// Ensure no undefined/null values leak into position arrays
return result.every(Boolean) ? result : null;
} catch { } catch {
return null; return null;
} }
@@ -240,7 +249,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
const key2 = buildWaypointsKey(cur2.waypoints); const key2 = buildWaypointsKey(cur2.waypoints);
if (key2 !== key) return; if (key2 !== key) return;
// 每次尝试前先触发一次渲染,让瓦片/深度尽量就绪 // 每次尝试前先触发一次渲染,让瓦�?深度尽量就绪
try { try {
viewer.scene?.requestRender?.(); viewer.scene?.requestRender?.();
} catch { } catch {
@@ -252,10 +261,12 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
const cartos = densifyWaypoints(Cesium2, cur2.waypoints); const cartos = densifyWaypoints(Cesium2, cur2.waypoints);
const densified = cartos.map((c: any) => Cesium2.Cartesian3.fromRadians(c.longitude, c.latitude, c.height || 300)); const densified = cartos.map((c: any) => Cesium2.Cartesian3.fromRadians(c.longitude, c.latitude, c.height || 300));
const clampedLine = await clampPositionsToModelSurface(Cesium2, densified); const densifiedGround = cartos.map((c: any) => Cesium2.Cartesian3.fromRadians(c.longitude, c.latitude, 0));
const clampedLine = await clampPositionsToModelSurface(Cesium2, densified, densifiedGround);
const wpAbove = cur2.waypoints.map((wp) => Cesium2.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 300)); const wpAbove = cur2.waypoints.map((wp) => Cesium2.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 300));
const clampedWp = await clampWaypointsToModelSurface(Cesium2, wpAbove); const wpGround = cur2.waypoints.map((wp) => Cesium2.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0));
const clampedWp = await clampWaypointsToModelSurface(Cesium2, wpAbove, wpGround);
if ((surfaceComputeSeqRef.current.get(routeId) || 0) !== seq) return; if ((surfaceComputeSeqRef.current.get(routeId) || 0) !== seq) return;
if (!clampedLine || clampedLine.length < 2) { if (!clampedLine || clampedLine.length < 2) {
@@ -271,7 +282,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
waypointPositions: Array.isArray(clampedWp) ? clampedWp : undefined, waypointPositions: Array.isArray(clampedWp) ? clampedWp : undefined,
}); });
// 触发一次增量更新(避免等下一轮effect) // 触发一次增量更新(避免等下一轮effect�?
try { try {
const pathId = `library-route-${routeId}-path`; const pathId = `library-route-${routeId}-path`;
const startId = `library-route-${routeId}-start`; const startId = `library-route-${routeId}-start`;
@@ -279,14 +290,19 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
const path = viewer.entities.getById?.(pathId); const path = viewer.entities.getById?.(pathId);
if (path?.polyline) { if (path?.polyline) {
path.polyline.positions = clampedLine; const validPolyline = clampedLine.filter(Boolean);
path.polyline.clampToGround = false; if (validPolyline.length >= 2) {
if (Cesium2?.ArcType) path.polyline.arcType = Cesium2.ArcType.NONE; path.polyline.positions = validPolyline;
path.polyline.clampToGround = false;
if (Cesium2?.ArcType) path.polyline.arcType = Cesium2.ArcType.NONE;
}
} }
const startPos = clampedLine[0];
const endPos = clampedLine[clampedLine.length - 1];
const start = viewer.entities.getById?.(startId); const start = viewer.entities.getById?.(startId);
if (start) start.position = clampedLine[0]; if (start && startPos) start.position = startPos;
const end = viewer.entities.getById?.(endId); const end = viewer.entities.getById?.(endId);
if (end) end.position = clampedLine[clampedLine.length - 1]; if (end && endPos) end.position = endPos;
if (Array.isArray(clampedWp)) { if (Array.isArray(clampedWp)) {
const total = cur2.waypoints.length; const total = cur2.waypoints.length;
@@ -295,7 +311,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
for (let i = 0; i < total; i += step) { for (let i = 0; i < total; i += step) {
const wpId = `library-route-${routeId}-wp-${i}`; const wpId = `library-route-${routeId}-wp-${i}`;
const wpEntity = viewer.entities.getById?.(wpId); const wpEntity = viewer.entities.getById?.(wpId);
if (wpEntity) wpEntity.position = clampedWp[i]; if (wpEntity && clampedWp[i]) wpEntity.position = clampedWp[i];
} }
} }
viewer.scene?.requestRender?.(); viewer.scene?.requestRender?.();
@@ -341,13 +357,14 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
color: baseColor, color: baseColor,
}) })
: baseColor; : baseColor;
const depthFailMaterial = item.highlighted ? baseColor.withAlpha(0.55) : baseColor.withAlpha(0.55); const depthFailMaterial = item.highlighted ? baseColor.withAlpha(0.65) : baseColor.withAlpha(0.65);
const cached = surfaceCacheRef.current.get(routeId); const cached = surfaceCacheRef.current.get(routeId);
const cachedPositions = cached && cached.key === waypointsKey ? cached.polyline : null; const cachedPositions = cached && cached.key === waypointsKey ? cached.polyline : null;
const fallbackPositions = item.waypoints.map((wp) => Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0)); const fallbackPositions = item.waypoints.map((wp) => Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0));
const positionsToUse = Array.isArray(cachedPositions) && cachedPositions.length >= 2 ? cachedPositions : fallbackPositions; const validCached = Array.isArray(cachedPositions) ? cachedPositions.filter(Boolean) : [];
const useClampToGround = !(Array.isArray(cachedPositions) && cachedPositions.length >= 2); const positionsToUse = validCached.length >= 2 ? validCached : fallbackPositions;
const useClampToGround = validCached.length < 2;
if (existing?.polyline) { if (existing?.polyline) {
existing.polyline.positions = positionsToUse; existing.polyline.positions = positionsToUse;
@@ -378,7 +395,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
}); });
} }
} catch (e) { } catch (e) {
console.error('渲染已规划航线失败:', e); console.error('渲染已规划航线失�?', e);
} }
// start / end // start / end
@@ -392,7 +409,8 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
const positionFromCache = cached && cached.key === waypointsKey const positionFromCache = cached && cached.key === waypointsKey
? (id === startId ? cached.start : cached.end) ? (id === startId ? cached.start : cached.end)
: null; : null;
const position = positionFromCache || Cesium.Cartesian3.fromDegrees(lon, lat, 0); const position = (positionFromCache && typeof positionFromCache === 'object') ? positionFromCache : Cesium.Cartesian3.fromDegrees(lon, lat, 0);
if (!position) return;
if (existing) { if (existing) {
existing.position = position; existing.position = position;
existing.show = true; existing.show = true;
@@ -454,7 +472,8 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
const existing = viewer.entities.getById?.(wpId); const existing = viewer.entities.getById?.(wpId);
const posFromCache = Array.isArray(cachedWp) ? cachedWp[i] : null; const posFromCache = Array.isArray(cachedWp) ? cachedWp[i] : null;
const pos = posFromCache || Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0); const pos = (posFromCache && typeof posFromCache === 'object') ? posFromCache : Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0);
if (!pos) continue;
if (existing) { if (existing) {
existing.position = pos; existing.position = pos;
@@ -513,7 +532,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
entityIdsByRouteRef.current.set(routeId, ids); entityIdsByRouteRef.current.set(routeId, ids);
// 贴模型:失败则自动重试(瓦片未就绪/不在视野时容易失败) // 贴模型:失败则自动重试(瓦片未就�?不在视野时容易失败)
scheduleSurfaceCompute(routeId); scheduleSurfaceCompute(routeId);
requestRender(); requestRender();
@@ -530,7 +549,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
return routes.filter((r) => r.visible && r.waypoints && r.waypoints.length >= 2); return routes.filter((r) => r.visible && r.waypoints && r.waypoints.length >= 2);
}, [routes]); }, [routes]);
// 同步渲染:增量更新 + 移除未显示的航线 // 同步渲染:增量更�?+ 移除未显示的航线
useEffect(() => { useEffect(() => {
const viewer = viewerRef?.current; const viewer = viewerRef?.current;
if (!viewer || viewer.isDestroyed?.()) return; if (!viewer || viewer.isDestroyed?.()) return;
@@ -571,7 +590,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
const Cesium = getCesium(); const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.()) return; if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
const item = routes.find((r) => r.routeId === routeId); const item = routesRef.current.find((r) => r.routeId === routeId);
if (!item?.waypoints || item.waypoints.length === 0) return; if (!item?.waypoints || item.waypoints.length === 0) return;
const bounds = calculateBounds(item.waypoints); const bounds = calculateBounds(item.waypoints);
try { try {
@@ -598,9 +617,20 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
} catch { } catch {
// 忽略 // 忽略
} }
}, [viewerRef, routes, getCesium, calculateBounds]); }, [viewerRef, getCesium, calculateBounds]);
const getRouteSurfaceGeometry = useCallback((routeId: string): RouteSurfaceGeometry | null => {
const cached = surfaceCacheRef.current.get(routeId);
if (!cached) return null;
return {
polyline: Array.isArray(cached.polyline) ? cached.polyline.filter(Boolean) : [],
waypointPositions: Array.isArray(cached.waypointPositions) ? cached.waypointPositions.filter(Boolean) : [],
};
}, []);
return { return {
flyToRoute, flyToRoute,
getRouteSurfaceGeometry,
}; };
} }
@@ -511,9 +511,8 @@ export function useCesiumRouteRenderer(options: UseCesiumRouteRendererOptions) {
const entityId = `route-waypoint-${index}`; const entityId = `route-waypoint-${index}`;
const cached = surfaceCacheRef.current; const cached = surfaceCacheRef.current;
const useCached = cached?.key === waypointsKey && Array.isArray(cached?.waypointPositions) && cached!.waypointPositions.length === waypoints.length; const useCached = cached?.key === waypointsKey && Array.isArray(cached?.waypointPositions) && cached!.waypointPositions.length === waypoints.length;
const position = useCached const cachedPos = useCached ? cached!.waypointPositions[index] : null;
? cached!.waypointPositions[index] const position = (cachedPos && typeof cachedPos === 'object') ? cachedPos : getFallbackPosition(wp);
: getFallbackPosition(wp);
if (!position) return; if (!position) return;
try { try {
@@ -654,9 +653,9 @@ export function useCesiumRouteRenderer(options: UseCesiumRouteRendererOptions) {
if (waypoints.length < 2) return; if (waypoints.length < 2) return;
const cached = surfaceCacheRef.current; const cached = surfaceCacheRef.current;
const useCached = cached?.key === waypointsKey && Array.isArray(cached?.polylinePositions) && cached!.polylinePositions.length >= 2; const cachedLine = cached?.key === waypointsKey && Array.isArray(cached?.polylinePositions) ? cached!.polylinePositions.filter(Boolean) : [];
const positions = useCached const positions = cachedLine.length >= 2
? cached!.polylinePositions ? cachedLine
: waypoints.map((wp) => getFallbackPosition(wp)).filter(Boolean); : waypoints.map((wp) => getFallbackPosition(wp)).filter(Boolean);
if (positions.length < 2) return; if (positions.length < 2) return;
@@ -675,7 +674,7 @@ export function useCesiumRouteRenderer(options: UseCesiumRouteRendererOptions) {
existing.polyline.material = material; existing.polyline.material = material;
existing.polyline.clampToGround = false; existing.polyline.clampToGround = false;
existing.polyline.arcType = Cesium.ArcType?.NONE; existing.polyline.arcType = Cesium.ArcType?.NONE;
existing.polyline.depthFailMaterial = depthFailMaterial; // removed depthFailMaterial to avoid rendering over boat model
existing.show = true; existing.show = true;
} else { } else {
viewer.entities.add({ viewer.entities.add({
@@ -686,11 +685,9 @@ export function useCesiumRouteRenderer(options: UseCesiumRouteRendererOptions) {
material, material,
clampToGround: false, clampToGround: false,
arcType: Cesium.ArcType?.NONE, arcType: Cesium.ArcType?.NONE,
depthFailMaterial,
} }
}); });
} } entityIdsRef.current.add(entityId);
entityIdsRef.current.add(entityId);
} catch (e) { } catch (e) {
console.error('添加航线polyline失败:', e); console.error('添加航线polyline失败:', e);
} }
@@ -494,9 +494,12 @@ const RouteEditor: React.FC<RouteEditorProps> = ({
const [isPreviewing, setIsPreviewing] = useState(false); const [isPreviewing, setIsPreviewing] = useState(false);
const previewAnimationRef = useRef<number | null>(null); const previewAnimationRef = useRef<number | null>(null);
const savedCameraStateRef = useRef<any>(null); const savedCameraStateRef = useRef<any>(null);
const previewBoatPartsRef = useRef<{ hull?: any; cabin?: any; mast?: any; marker?: any } | null>(null); const previewBoatPartsRef = useRef<{ boat?: any } | null>(null);
const waypointPreviewListRef = useRef<HTMLDivElement | null>(null); const waypointPreviewListRef = useRef<HTMLDivElement | null>(null);
// GLB 模型自身朝向补偿(模型建模方向与 Cesium 北向的偏差)
const MODEL_HEADING_OFFSET = -Math.PI / 2;
// 计算两点之间的航向角(度) // 计算两点之间的航向角(度)
const calculateHeading = useCallback((from: { longitude: number; latitude: number }, to: { longitude: number; latitude: number }) => { const calculateHeading = useCallback((from: { longitude: number; latitude: number }, to: { longitude: number; latitude: number }) => {
const dLon = (to.longitude - from.longitude) * Math.PI / 180; const dLon = (to.longitude - from.longitude) * Math.PI / 180;
@@ -529,11 +532,8 @@ const RouteEditor: React.FC<RouteEditorProps> = ({
try { try {
const viewer = viewerRef?.current; const viewer = viewerRef?.current;
if (viewer && !viewer.isDestroyed?.()) { if (viewer && !viewer.isDestroyed?.()) {
const { hull, cabin, mast, marker } = previewBoatPartsRef.current; const { boat } = previewBoatPartsRef.current;
if (hull) viewer.entities.remove(hull); if (boat) viewer.entities.remove(boat);
if (cabin) viewer.entities.remove(cabin);
if (mast) viewer.entities.remove(mast);
if (marker) viewer.entities.remove(marker);
} }
} catch { } catch {
// 忽略 // 忽略
@@ -611,23 +611,26 @@ const RouteEditor: React.FC<RouteEditorProps> = ({
const densifiedCartos = densify(); const densifiedCartos = densify();
if (densifiedCartos.length < 2) { if (densifiedCartos.length < 2) {
return points.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)).map(applyOffset); return points
.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0))
.map(applyOffset)
.filter(Boolean);
} }
const above = densifiedCartos.map((c: any) => Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, c.height || 300)); const above = densifiedCartos.map((c: any) => Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, c.height || 300));
const clampFn = viewer.scene?.clampToHeightMostDetailed; const clampFn = viewer.scene?.clampToHeightMostDetailed;
if (typeof clampFn !== 'function') { if (typeof clampFn !== 'function') {
return above.map(applyOffset); return above.map(applyOffset).filter(Boolean);
} }
try { try {
const clamped = await clampFn.call(viewer.scene, above); const clamped = await clampFn.call(viewer.scene, above);
const merged = (clamped || []).map((p: any, idx: number) => p || above[idx]); const merged = (clamped || []).map((p: any, idx: number) => p || above[idx]);
const okCount = (clamped || []).filter(Boolean).length; const okCount = (clamped || []).filter(Boolean).length;
if (okCount < 2) return above.map(applyOffset); if (okCount < 2) return above.map(applyOffset).filter(Boolean);
return merged.map(applyOffset); return merged.map(applyOffset).filter(Boolean);
} catch { } catch {
return above.map(applyOffset); return above.map(applyOffset).filter(Boolean);
} }
}, [viewerRef]); }, [viewerRef]);
@@ -635,16 +638,17 @@ const RouteEditor: React.FC<RouteEditorProps> = ({
const viewer = viewerRef?.current; const viewer = viewerRef?.current;
const Cesium = (window as any).Cesium; const Cesium = (window as any).Cesium;
if (!viewer || !Cesium || viewer.isDestroyed?.()) return; if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
if (!Array.isArray(polylinePositions) || polylinePositions.length < 2) return; polylinePositions = Array.isArray(polylinePositions) ? polylinePositions.filter(Boolean) : [];
if (polylinePositions.length < 2) {
message.warning('模型瓦片加载中,请稍后再试预览');
return;
}
// 预览开始前,清理上一次遗留的船只实体 // 预览开始前,清理上一次遗留的船只实体
if (previewBoatPartsRef.current) { if (previewBoatPartsRef.current) {
try { try {
const { hull, cabin, mast, marker } = previewBoatPartsRef.current; const { boat } = previewBoatPartsRef.current;
if (hull) viewer.entities.remove(hull); if (boat) viewer.entities.remove(boat);
if (cabin) viewer.entities.remove(cabin);
if (mast) viewer.entities.remove(mast);
if (marker) viewer.entities.remove(marker);
} catch { } catch {
// 忽略 // 忽略
} finally { } finally {
@@ -695,92 +699,34 @@ const RouteEditor: React.FC<RouteEditorProps> = ({
} }
}; };
// 创建预览船只实体:临时“3D船体”(用几何体拼装),后续可替换为 glb/gltf // 创建预览船只实体:使用 GLB 船模型
try { try {
const firstPos0 = polylinePositions[0]; const firstPos0 = polylinePositions[0];
// 抬高过大会产生“视差”,看起来像是偏离航线;因此尽量贴近航线,靠标记图标保证可见 // 抬高过大会产生“视差”,看起来像是偏离航线;因此尽量贴近航线,靠标记图标保证可见
const boatAboveRoute = 0.05; const boatAboveRoute = 0.5;
const firstPos = offsetUpFromCartesian(firstPos0, boatAboveRoute); const firstPos = offsetUpFromCartesian(firstPos0, boatAboveRoute);
const initialOrientation = Cesium.Transforms?.headingPitchRollQuaternion const initialOrientation = Cesium.Transforms?.headingPitchRollQuaternion
? Cesium.Transforms.headingPitchRollQuaternion(firstPos, new Cesium.HeadingPitchRoll(0, 0, 0)) ? Cesium.Transforms.headingPitchRollQuaternion(firstPos, new Cesium.HeadingPitchRoll(MODEL_HEADING_OFFSET, 0, 0))
: undefined; : undefined;
const hull = viewer.entities.add({ const boat = viewer.entities.add({
position: firstPos, position: firstPos,
orientation: initialOrientation, orientation: initialOrientation,
box: { model: {
dimensions: new Cesium.Cartesian3(1.35, 0.5, 0.2), uri: `${process.env.CESIUM_BASE_URL || '/'}chuan-model.glb`,
material: Cesium.Color.fromCssColorString('#0B3D91').withAlpha(0.92), scale: 0.001,
outline: true, minimumPixelSize: 64,
outlineColor: Cesium.Color.fromCssColorString('#E6F7FF').withAlpha(0.8), maximumScale: 200,
shadows: Cesium.ShadowMode.DISABLED, runAnimations: true,
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0), colorBlendMode: Cesium.ColorBlendMode.HIGHLIGHT,
color: Cesium.Color.WHITE,
silhouetteSize: 0,
}, },
}); });
const cabinOffset = (basePos: any, headingRad: number) => { previewBoatPartsRef.current = { boat };
if (!Cesium.Transforms?.eastNorthUpToFixedFrame || !Cesium.Matrix4?.multiplyByPoint) return basePos;
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(basePos);
const forwardMeters = 0.25;
const rightMeters = 0.0;
const upMeters = 0.16;
const localOffset = new Cesium.Cartesian3(
Math.sin(headingRad) * forwardMeters + Math.cos(headingRad) * rightMeters,
Math.cos(headingRad) * forwardMeters - Math.sin(headingRad) * rightMeters,
upMeters
);
return Cesium.Matrix4.multiplyByPoint(enu, localOffset, new Cesium.Cartesian3());
};
const cabinPos = cabinOffset(firstPos, 0);
const cabin = viewer.entities.add({
position: cabinPos,
orientation: initialOrientation,
box: {
dimensions: new Cesium.Cartesian3(0.55, 0.38, 0.24),
material: Cesium.Color.fromCssColorString('#F5F5F5').withAlpha(0.95),
outline: true,
outlineColor: Cesium.Color.fromCssColorString('#FA8C16').withAlpha(0.85),
shadows: Cesium.ShadowMode.DISABLED,
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0),
},
});
const mastPos = cabinOffset(firstPos, 0);
const mast = viewer.entities.add({
position: mastPos,
orientation: initialOrientation,
cylinder: {
length: 0.38,
topRadius: 0.015,
bottomRadius: 0.015,
material: Cesium.Color.fromCssColorString('#FFFFFF').withAlpha(0.9),
outline: true,
outlineColor: Cesium.Color.fromCssColorString('#FFFFFF').withAlpha(0.6),
shadows: Cesium.ShadowMode.DISABLED,
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0),
},
});
// 额外加一个“标记图标”,保证在复杂模型表面也能看清船的位置
const markerImageUrl = typeof Cesium.buildModuleUrl === 'function'
? Cesium.buildModuleUrl('Assets/Textures/maki/ferry.png')
: '/cesium/Assets/Textures/maki/ferry.png';
const marker = viewer.entities.add({
position: offsetUpFromCartesian(firstPos0, boatAboveRoute + 0.12),
billboard: {
image: markerImageUrl,
scale: 0.55,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scaleByDistance: new Cesium.NearFarScalar(20.0, 1.0, 200.0, 0.6),
},
});
previewBoatPartsRef.current = { hull, cabin, mast, marker };
(previewBoatPartsRef.current as any).boatAboveRoute = boatAboveRoute; (previewBoatPartsRef.current as any).boatAboveRoute = boatAboveRoute;
(previewBoatPartsRef.current as any).cabinOffset = cabinOffset;
} catch (e) { } catch (e) {
console.warn('创建预览船只实体失败:', e); console.warn('创建预览船只实体失败:', e);
} }
@@ -959,30 +905,16 @@ const RouteEditor: React.FC<RouteEditorProps> = ({
// 更新船只位置与朝向(尽量贴合航线) // 更新船只位置与朝向(尽量贴合航线)
try { try {
if (previewBoatPartsRef.current) { if (previewBoatPartsRef.current) {
const boatAboveRoute = Number((previewBoatPartsRef.current as any).boatAboveRoute) || 0.14; const boatAboveRoute = Number((previewBoatPartsRef.current as any).boatAboveRoute) || 0.5;
const basePos = offsetUpFromCartesian(scratchPosCur, boatAboveRoute); const basePos = offsetUpFromCartesian(scratchPosCur, boatAboveRoute);
const orientation = Cesium.Transforms?.headingPitchRollQuaternion const orientation = Cesium.Transforms?.headingPitchRollQuaternion
? Cesium.Transforms.headingPitchRollQuaternion(basePos, new Cesium.HeadingPitchRoll(headingRad, 0, 0)) ? Cesium.Transforms.headingPitchRollQuaternion(basePos, new Cesium.HeadingPitchRoll(headingRad + MODEL_HEADING_OFFSET, 0, 0))
: undefined; : undefined;
const { hull, cabin, mast } = previewBoatPartsRef.current; const { boat } = previewBoatPartsRef.current;
if (hull) { if (boat) {
hull.position = basePos; boat.position = basePos;
if (orientation) hull.orientation = orientation; if (orientation) boat.orientation = orientation;
}
const cabinOffset = (previewBoatPartsRef.current as any).cabinOffset as ((p: any, h: number) => any) | undefined;
const cabinPos = typeof cabinOffset === 'function' ? cabinOffset(basePos, headingRad) : basePos;
if (cabin) {
cabin.position = cabinPos;
if (orientation) cabin.orientation = orientation;
}
if (mast) {
mast.position = cabinPos;
if (orientation) mast.orientation = orientation;
}
if (previewBoatPartsRef.current.marker) {
previewBoatPartsRef.current.marker.position = offsetUpFromCartesian(scratchPosCur, boatAboveRoute + 0.12);
} }
} }
} catch { } catch {
@@ -1001,26 +933,15 @@ const RouteEditor: React.FC<RouteEditorProps> = ({
// 更新船只位置(兜底) // 更新船只位置(兜底)
try { try {
if (previewBoatPartsRef.current) { if (previewBoatPartsRef.current) {
const boatAboveRoute = Number((previewBoatPartsRef.current as any).boatAboveRoute) || 0.14; const boatAboveRoute = Number((previewBoatPartsRef.current as any).boatAboveRoute) || 0.5;
const basePos = offsetUpFromCartesian(scratchPosCur, boatAboveRoute); const basePos = offsetUpFromCartesian(scratchPosCur, boatAboveRoute);
const orientation = Cesium.Transforms?.headingPitchRollQuaternion const orientation = Cesium.Transforms?.headingPitchRollQuaternion
? Cesium.Transforms.headingPitchRollQuaternion(basePos, new Cesium.HeadingPitchRoll(headingRad, 0, 0)) ? Cesium.Transforms.headingPitchRollQuaternion(basePos, new Cesium.HeadingPitchRoll(headingRad + MODEL_HEADING_OFFSET, 0, 0))
: undefined; : undefined;
const { hull, cabin, mast } = previewBoatPartsRef.current; const { boat } = previewBoatPartsRef.current;
if (hull) { if (boat) {
hull.position = basePos; boat.position = basePos;
if (orientation) hull.orientation = orientation; if (orientation) boat.orientation = orientation;
}
if (cabin) {
cabin.position = basePos;
if (orientation) cabin.orientation = orientation;
}
if (mast) {
mast.position = basePos;
if (orientation) mast.orientation = orientation;
}
if (previewBoatPartsRef.current.marker) {
previewBoatPartsRef.current.marker.position = offsetUpFromCartesian(scratchPosCur, boatAboveRoute + 0.12);
} }
} }
} catch { } catch {
@@ -1109,11 +1030,8 @@ const RouteEditor: React.FC<RouteEditorProps> = ({
try { try {
const viewer = viewerRef?.current; const viewer = viewerRef?.current;
if (viewer && !viewer.isDestroyed?.()) { if (viewer && !viewer.isDestroyed?.()) {
const { hull, cabin, mast, marker } = previewBoatPartsRef.current; const { boat } = previewBoatPartsRef.current;
if (hull) viewer.entities.remove(hull); if (boat) viewer.entities.remove(boat);
if (cabin) viewer.entities.remove(cabin);
if (mast) viewer.entities.remove(mast);
if (marker) viewer.entities.remove(marker);
} }
} catch { } catch {
// 忽略 // 忽略
+32
View File
@@ -0,0 +1,32 @@
export interface Coordinate {
longitude: number;
latitude: number;
}
export const toFiniteNumber = (value: unknown): number | undefined => {
if (value === null || value === undefined || value === '') return undefined;
const numeric = Number(value);
return Number.isFinite(numeric) ? numeric : undefined;
};
export const isValidCoordinate = (longitude?: number, latitude?: number): boolean => {
if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return false;
if (Math.abs(longitude!) > 180 || Math.abs(latitude!) > 90) return false;
// 设备未上报定位时常见默认值是 0,0,不能当作真实位置使用。
return !(longitude === 0 && latitude === 0);
};
export const getValidCoordinate = (
longitudeValue: unknown,
latitudeValue: unknown,
): Coordinate | null => {
const longitude = toFiniteNumber(longitudeValue);
const latitude = toFiniteNumber(latitudeValue);
if (!isValidCoordinate(longitude, latitude)) return null;
return {
longitude: longitude!,
latitude: latitude!,
};
};