feat: 航线规划以及水域边界标绘

This commit is contained in:
2026-01-06 18:09:20 +08:00
parent 9a50476c62
commit a9f1e1f4d4
187 changed files with 14935 additions and 5334 deletions
@@ -0,0 +1,93 @@
package com.central.device.controller;
import com.central.common.model.Result;
import com.central.device.model.dto.BoatManualControlDTO;
import com.central.device.service.IBoatControlService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* 无人船控制命令Controller
*
* @author dzc
* @date 2026-01-05
*/
@Tag(name = "无人船控制命令")
@RestController
@RequestMapping("/device/boat/command")
@RequiredArgsConstructor
public class BoatCommandController {
private final IBoatControlService boatControlService;
@Operation(summary = "执行航线任务")
@PostMapping("/route/execute")
public Result<String> executeRoute(
@Parameter(description = "设备SN") @RequestParam String deviceSn,
@Parameter(description = "航线ID") @RequestParam String boatRouteId,
@Parameter(description = "任务编码") @RequestParam String missionCode) {
String taskId = boatControlService.executeRoute(deviceSn, boatRouteId, missionCode);
return Result.succeed(taskId, "任务已下发");
}
@Operation(summary = "暂停航行")
@PostMapping("/pause")
public Result<Void> pause(
@Parameter(description = "设备SN") @RequestParam String deviceSn) {
boatControlService.pause(deviceSn);
return Result.succeed(null, "暂停指令已下发");
}
@Operation(summary = "恢复航行")
@PostMapping("/resume")
public Result<Void> resume(
@Parameter(description = "设备SN") @RequestParam String deviceSn) {
boatControlService.resume(deviceSn);
return Result.succeed(null, "恢复指令已下发");
}
@Operation(summary = "返回起点")
@PostMapping("/return")
public Result<Void> returnToStart(
@Parameter(description = "设备SN") @RequestParam String deviceSn) {
boatControlService.returnToStart(deviceSn);
return Result.succeed(null, "返航指令已下发");
}
@Operation(summary = "紧急停止")
@PostMapping("/emergency-stop")
public Result<Void> emergencyStop(
@Parameter(description = "设备SN") @RequestParam String deviceSn) {
boatControlService.emergencyStop(deviceSn);
return Result.succeed(null, "紧急停止指令已下发");
}
@Operation(summary = "手动控制")
@PostMapping("/manual")
public Result<Void> manualControl(
@Parameter(description = "设备SN") @RequestParam String deviceSn,
@RequestBody @Validated BoatManualControlDTO dto) {
boatControlService.manualControl(deviceSn, dto);
return Result.succeed(null, "控制指令已发送");
}
@Operation(summary = "检查设备是否在线")
@GetMapping("/online/{deviceSn}")
public Result<Boolean> isDeviceOnline(
@Parameter(description = "设备SN") @PathVariable String deviceSn) {
boolean online = boatControlService.isDeviceOnline(deviceSn);
return Result.succeed(online);
}
@Operation(summary = "获取设备状态")
@GetMapping("/status/{deviceSn}")
public Result<String> getDeviceStatus(
@Parameter(description = "设备SN") @PathVariable String deviceSn) {
String status = boatControlService.getDeviceStatus(deviceSn);
return Result.succeed(status);
}
}
@@ -0,0 +1,133 @@
package com.central.device.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.model.Result;
import com.central.device.model.dto.BoatRouteCreateDTO;
import com.central.device.model.dto.BoatRouteUpdateDTO;
import com.central.device.model.vo.BoatRouteDetailVO;
import com.central.device.model.vo.BoatRouteListVO;
import com.central.device.model.vo.RouteValidateResultVO;
import com.central.device.service.IBoatRouteService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 无人船航线管理Controller
*
* @author dzc
* @date 2026-01-05
*/
@Tag(name = "无人船航线管理")
@RestController
@RequestMapping("/device/boat/route")
@RequiredArgsConstructor
public class BoatRouteController {
private final IBoatRouteService boatRouteService;
@Operation(summary = "创建航线")
@PostMapping("/create")
public Result<String> createRoute(@RequestBody @Validated BoatRouteCreateDTO dto) {
String routeId = boatRouteService.createRoute(dto);
return Result.succeed(routeId, "航线创建成功");
}
@Operation(summary = "更新航线")
@PutMapping("/{routeId}")
public Result<Void> updateRoute(
@Parameter(description = "航线ID") @PathVariable String routeId,
@RequestBody @Validated BoatRouteUpdateDTO dto) {
boatRouteService.updateRoute(routeId, dto);
return Result.succeed(null, "航线更新成功");
}
@Operation(summary = "获取航线详情")
@GetMapping("/{routeId}")
public Result<BoatRouteDetailVO> getRouteDetail(
@Parameter(description = "航线ID") @PathVariable String routeId) {
BoatRouteDetailVO detail = boatRouteService.getRouteDetail(routeId);
return Result.succeed(detail);
}
@Operation(summary = "获取设备绑定的航线列表")
@GetMapping("/list/device/{deviceSn}")
public Result<List<BoatRouteListVO>> listByDeviceSn(
@Parameter(description = "设备SN") @PathVariable String deviceSn) {
List<BoatRouteListVO> list = boatRouteService.listByDeviceSn(deviceSn);
return Result.succeed(list);
}
@Operation(summary = "获取景区航线列表(分页)")
@GetMapping("/list/scenic/{scenicId}")
public Result<Page<BoatRouteListVO>> listByScenicId(
@Parameter(description = "景区ID") @PathVariable Long scenicId,
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
@Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer size) {
Page<BoatRouteListVO> pageResult = boatRouteService.listByScenicId(scenicId, page, size);
return Result.succeed(pageResult);
}
@Operation(summary = "绑定航线到设备")
@PostMapping("/{routeId}/bind")
public Result<Void> bindToDevice(
@Parameter(description = "航线ID") @PathVariable String routeId,
@Parameter(description = "设备SN") @RequestParam String deviceSn) {
boatRouteService.bindToDevice(routeId, deviceSn);
return Result.succeed(null, "绑定成功");
}
@Operation(summary = "解绑航线和设备")
@PostMapping("/{routeId}/unbind")
public Result<Void> unbindDevice(
@Parameter(description = "航线ID") @PathVariable String routeId) {
boatRouteService.unbindDevice(routeId);
return Result.succeed(null, "解绑成功");
}
@Operation(summary = "校验航线")
@PostMapping("/validate")
public Result<RouteValidateResultVO> validateRoute(
@RequestBody @Validated BoatRouteCreateDTO dto,
@Parameter(description = "边界ID(可选)") @RequestParam(required = false) String boundaryId) {
RouteValidateResultVO result = boatRouteService.validateRoute(dto, boundaryId);
return Result.succeed(result);
}
@Operation(summary = "删除航线")
@DeleteMapping("/{routeId}")
public Result<Void> deleteRoute(
@Parameter(description = "航线ID") @PathVariable String routeId) {
boatRouteService.deleteRoute(routeId);
return Result.succeed(null, "删除成功");
}
@Operation(summary = "保存为模板")
@PostMapping("/{routeId}/template")
public Result<String> saveAsTemplate(
@Parameter(description = "航线ID") @PathVariable String routeId,
@Parameter(description = "模板名称") @RequestParam String templateName) {
String newRouteId = boatRouteService.saveAsTemplate(routeId, templateName);
return Result.succeed(newRouteId, "保存模板成功");
}
@Operation(summary = "获取模板列表")
@GetMapping("/templates")
public Result<List<BoatRouteListVO>> listTemplates() {
List<BoatRouteListVO> list = boatRouteService.listTemplates();
return Result.succeed(list);
}
@Operation(summary = "发布航线")
@PostMapping("/{routeId}/publish")
public Result<Void> publishRoute(
@Parameter(description = "航线ID") @PathVariable String routeId) {
boatRouteService.publishRoute(routeId);
return Result.succeed(null, "发布成功");
}
}
@@ -0,0 +1,57 @@
package com.central.device.controller;
import com.central.common.model.Result;
import com.central.device.model.vo.BoatRealtimeVO;
import com.central.device.model.vo.TaskTrackVO;
import com.central.device.model.vo.TrackPointVO;
import com.central.device.service.IBoatTrackService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;
/**
* 无人船轨迹Controller
*
* @author dzc
* @date 2026-01-05
*/
@Tag(name = "无人船轨迹")
@RestController
@RequestMapping("/device/boat/track")
@RequiredArgsConstructor
public class BoatTrackController {
private final IBoatTrackService boatTrackService;
@Operation(summary = "获取实时位置")
@GetMapping("/realtime/{deviceSn}")
public Result<BoatRealtimeVO> getRealtimePosition(
@Parameter(description = "设备SN") @PathVariable String deviceSn) {
BoatRealtimeVO realtime = boatTrackService.getRealtimePosition(deviceSn);
return Result.succeed(realtime);
}
@Operation(summary = "获取历史轨迹")
@GetMapping("/history/{deviceSn}")
public Result<List<TrackPointVO>> getHistoryTrack(
@Parameter(description = "设备SN") @PathVariable String deviceSn,
@Parameter(description = "开始时间") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
@Parameter(description = "结束时间") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
List<TrackPointVO> track = boatTrackService.getHistoryTrack(deviceSn, startTime, endTime);
return Result.succeed(track);
}
@Operation(summary = "获取任务执行轨迹")
@GetMapping("/task/{taskId}")
public Result<TaskTrackVO> getTaskTrack(
@Parameter(description = "任务ID") @PathVariable String taskId) {
TaskTrackVO taskTrack = boatTrackService.getTaskTrack(taskId);
return Result.succeed(taskTrack);
}
}
@@ -0,0 +1,110 @@
package com.central.device.controller;
import com.central.common.model.Result;
import com.central.device.model.dto.PointDTO;
import com.central.device.model.dto.WaterBoundaryCreateDTO;
import com.central.device.model.vo.BoundaryCheckResultVO;
import com.central.device.model.vo.WaterBoundaryVO;
import com.central.device.service.IWaterBoundaryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 水域边界管理Controller
*
* @author dzc
* @date 2026-01-05
*/
@Tag(name = "水域边界管理")
@RestController
@RequestMapping("/device/water/boundary")
@RequiredArgsConstructor
public class WaterBoundaryController {
private final IWaterBoundaryService waterBoundaryService;
@Operation(summary = "创建水域边界")
@PostMapping("/create")
public Result<String> createBoundary(@RequestBody @Validated WaterBoundaryCreateDTO dto) {
String boundaryId = waterBoundaryService.createBoundary(dto);
return Result.succeed(boundaryId, "边界创建成功");
}
@Operation(summary = "获取边界详情")
@GetMapping("/{boundaryId}")
public Result<WaterBoundaryVO> getBoundaryDetail(
@Parameter(description = "边界ID") @PathVariable String boundaryId) {
var boundary = waterBoundaryService.getByBoundaryId(boundaryId);
if (boundary == null) {
return Result.failed("边界不存在");
}
WaterBoundaryVO vo = new WaterBoundaryVO();
vo.setBoundaryId(boundary.getBoundaryId());
vo.setBoundaryName(boundary.getBoundaryName());
vo.setScenicId(boundary.getScenicId());
vo.setBoundaryType(boundary.getBoundaryType());
vo.setPolygonData(boundary.getPolygonData());
vo.setStatus(boundary.getStatus());
vo.setCreateTime(boundary.getCreateTime());
return Result.succeed(vo);
}
@Operation(summary = "获取景区边界列表")
@GetMapping("/list/{scenicId}")
public Result<List<WaterBoundaryVO>> listByScenicId(
@Parameter(description = "景区ID") @PathVariable Long scenicId) {
List<WaterBoundaryVO> list = waterBoundaryService.listByScenicId(scenicId);
return Result.succeed(list);
}
@Operation(summary = "检测点是否在边界内")
@GetMapping("/check/point")
public Result<Boolean> checkPoint(
@Parameter(description = "边界ID") @RequestParam String boundaryId,
@Parameter(description = "经度") @RequestParam Double longitude,
@Parameter(description = "纬度") @RequestParam Double latitude) {
boolean inBoundary = waterBoundaryService.isPointInBoundary(boundaryId, longitude, latitude);
return Result.succeed(inBoundary);
}
@Operation(summary = "检测航线是否在边界内")
@PostMapping("/check/route")
public Result<BoundaryCheckResultVO> checkRoute(
@Parameter(description = "边界ID") @RequestParam String boundaryId,
@RequestBody List<PointDTO> waypoints) {
BoundaryCheckResultVO result = waterBoundaryService.checkRouteInBoundary(boundaryId, waypoints);
return Result.succeed(result);
}
@Operation(summary = "从3D模型检测边界(异步)")
@PostMapping("/detect/model")
public Result<String> detectFromModel(
@Parameter(description = "模型ID") @RequestParam String modelId,
@Parameter(description = "景区ID") @RequestParam Long scenicId) {
String taskId = waterBoundaryService.detectFromModelAsync(modelId, scenicId);
return Result.succeed(taskId, "检测任务已启动");
}
@Operation(summary = "更新边界状态")
@PutMapping("/{boundaryId}/status")
public Result<Void> updateStatus(
@Parameter(description = "边界ID") @PathVariable String boundaryId,
@Parameter(description = "状态: 0-禁用 1-启用") @RequestParam Integer status) {
waterBoundaryService.updateStatus(boundaryId, status);
return Result.succeed(null, "状态更新成功");
}
@Operation(summary = "删除边界")
@DeleteMapping("/{boundaryId}")
public Result<Void> deleteBoundary(
@Parameter(description = "边界ID") @PathVariable String boundaryId) {
waterBoundaryService.deleteBoundary(boundaryId);
return Result.succeed(null, "删除成功");
}
}
@@ -0,0 +1,243 @@
package com.central.device.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 无人船航线实体
*
* @author dzc
* @date 2026-01-05
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("boat_route")
public class BoatRoute implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 航线唯一标识(UUID)
*/
@TableField("route_id")
private String routeId;
/**
* 航线名称
*/
@TableField("route_name")
private String routeName;
/**
* 绑定设备SN
*/
@TableField("device_sn")
private String deviceSn;
/**
* 设备名称
*/
@TableField("device_name")
private String deviceName;
/**
* 所属景区ID
*/
@TableField("scenic_id")
private Long scenicId;
/**
* 租户ID
*/
@TableField("tenant_id")
private String tenantId;
// ========== 航线统计信息 ==========
/**
* 航点数量
*/
@TableField("waypoint_count")
private Integer waypointCount;
/**
* 总航程(米)
*/
@TableField("total_distance")
private BigDecimal totalDistance;
/**
* 预计时长(秒)
*/
@TableField("total_duration")
private Integer totalDuration;
/**
* 巡航速度(m/s)
*/
@TableField("cruise_speed")
private BigDecimal cruiseSpeed;
// ========== 航线边界 ==========
/**
* 水域边界多边形(GeoJSON)
*/
@TableField("boundary_polygon")
private String boundaryPolygon;
/**
* 起点坐标(lng,lat)
*/
@TableField("start_point")
private String startPoint;
/**
* 终点坐标(lng,lat)
*/
@TableField("end_point")
private String endPoint;
// ========== 航线配置 ==========
/**
* 是否循环航行:0-否,1-是
*/
@TableField("loop_enabled")
private Boolean loopEnabled;
/**
* 循环次数(-1无限循环)
*/
@TableField("loop_count")
private Integer loopCount;
/**
* 结束动作:return_start-返回起点,stay-原地停留
*/
@TableField("return_mode")
private String returnMode;
/**
* 安全距离(米)
*/
@TableField("safe_distance")
private BigDecimal safeDistance;
// ========== 状态字段 ==========
/**
* 状态:0-草稿,1-已发布,2-执行中,3-已完成
*/
@TableField("status")
private Integer status;
/**
* 是否为模板:0-否,1-是
*/
@TableField("is_template")
private Boolean isTemplate;
/**
* 备注
*/
@TableField("remark")
private String remark;
/**
* 创建时间
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 创建人
*/
@TableField(value = "create_by", fill = FieldFill.INSERT)
private String createBy;
/**
* 删除标记
*/
@TableLogic
@TableField("deleted")
private Integer deleted;
// ========== 状态枚举 ==========
/**
* 航线状态枚举
*/
public enum RouteStatus {
DRAFT(0, "草稿"),
PUBLISHED(1, "已发布"),
EXECUTING(2, "执行中"),
COMPLETED(3, "已完成");
private final Integer code;
private final String desc;
RouteStatus(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
public Integer getCode() {
return code;
}
public String getDesc() {
return desc;
}
public static RouteStatus fromCode(Integer code) {
for (RouteStatus status : values()) {
if (status.getCode().equals(code)) {
return status;
}
}
return DRAFT;
}
}
/**
* 结束动作枚举
*/
public enum ReturnMode {
RETURN_START("return_start", "返回起点"),
STAY("stay", "原地停留");
private final String code;
private final String desc;
ReturnMode(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
}
@@ -0,0 +1,115 @@
package com.central.device.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 无人船轨迹实体
*
* @author dzc
* @date 2026-01-05
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("boat_track")
public class BoatTrack implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 设备SN
*/
@TableField("device_sn")
private String deviceSn;
/**
* 执行的航线ID
*/
@TableField("route_id")
private String routeId;
/**
* 任务ID(mission_code)
*/
@TableField("task_id")
private String taskId;
// ========== 位置信息 ==========
/**
* 经度
*/
@TableField("longitude")
private BigDecimal longitude;
/**
* 纬度
*/
@TableField("latitude")
private BigDecimal latitude;
// ========== 航行状态 ==========
/**
* 当前速度(m/s)
*/
@TableField("speed")
private BigDecimal speed;
/**
* 航向角(度)
*/
@TableField("heading")
private BigDecimal heading;
/**
* 电池电量(%)
*/
@TableField("battery_percent")
private Integer batteryPercent;
// ========== 偏离检测 ==========
/**
* 偏离航线距离(米)
*/
@TableField("deviation_distance")
private BigDecimal deviationDistance;
/**
* 是否偏离:0-否,1-是
*/
@TableField("is_deviation")
private Boolean isDeviation;
/**
* 最近航点序号
*/
@TableField("nearest_waypoint_index")
private Integer nearestWaypointIndex;
// ========== 时间戳 ==========
/**
* 设备上报时间
*/
@TableField("record_time")
private LocalDateTime recordTime;
/**
* 入库时间
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
}
@@ -0,0 +1,207 @@
package com.central.device.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
/**
* 无人船航点实体
*
* @author dzc
* @date 2026-01-05
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName(value = "boat_waypoint", autoResultMap = true)
public class BoatWaypoint implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 航点唯一标识
*/
@TableField("waypoint_id")
private String waypointId;
/**
* 关联航线ID
*/
@TableField("route_id")
private String routeId;
/**
* 航点序号(从0开始)
*/
@TableField("waypoint_index")
private Integer waypointIndex;
// ========== 位置信息 ==========
/**
* 经度
*/
@TableField("longitude")
private BigDecimal longitude;
/**
* 纬度
*/
@TableField("latitude")
private BigDecimal latitude;
// ========== 航行参数 ==========
/**
* 到达此点的速度(m/s),null使用航线默认
*/
@TableField("speed")
private BigDecimal speed;
/**
* 停留时长(秒)
*/
@TableField("stay_duration")
private Integer stayDuration;
/**
* 航向角(度,0-360,null自动计算)
*/
@TableField("heading_angle")
private BigDecimal headingAngle;
/**
* 转弯模式:smooth-平滑,sharp-急转
*/
@TableField("turn_mode")
private String turnMode;
// ========== 航点动作 ==========
/**
* 航点动作配置(JSON数组)
*/
@TableField(value = "actions", typeHandler = JacksonTypeHandler.class)
private List<WaypointAction> actions;
// ========== 标记 ==========
/**
* 是否关键点:0-否,1-是
*/
@TableField("is_key_point")
private Boolean isKeyPoint;
/**
* 航点名称
*/
@TableField("point_name")
private String pointName;
/**
* 备注
*/
@TableField("remark")
private String remark;
/**
* 创建时间
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
// ========== 内嵌类 ==========
/**
* 航点动作
*/
@Data
public static class WaypointAction implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 动作类型: photo/video_start/video_stop/horn/light
*/
private String actionType;
/**
* 动作持续时间(秒)
*/
private Integer duration;
/**
* 动作参数
*/
private Object params;
}
// ========== 枚举 ==========
/**
* 转弯模式枚举
*/
public enum TurnMode {
SMOOTH("smooth", "平滑转弯"),
SHARP("sharp", "急转弯");
private final String code;
private final String desc;
TurnMode(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
/**
* 动作类型枚举
*/
public enum ActionType {
PHOTO("photo", "拍照"),
VIDEO_START("video_start", "开始录像"),
VIDEO_STOP("video_stop", "停止录像"),
HORN("horn", "鸣笛"),
LIGHT("light", "灯光控制");
private final String code;
private final String desc;
ActionType(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
}
@@ -0,0 +1,181 @@
package com.central.device.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 水域边界实体
*
* @author dzc
* @date 2026-01-05
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("water_boundary")
public class WaterBoundary implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 边界唯一标识
*/
@TableField("boundary_id")
private String boundaryId;
/**
* 边界名称
*/
@TableField("boundary_name")
private String boundaryName;
/**
* 所属景区ID
*/
@TableField("scenic_id")
private Long scenicId;
/**
* 租户ID
*/
@TableField("tenant_id")
private String tenantId;
// ========== 边界数据 ==========
/**
* 边界类型:navigable-可航行,obstacle-障碍物,restricted-禁行区
*/
@TableField("boundary_type")
private String boundaryType;
/**
* 多边形坐标(GeoJSON)
*/
@TableField("polygon_data")
private String polygonData;
/**
* 中心点坐标
*/
@TableField("center_point")
private String centerPoint;
/**
* 面积(平方米)
*/
@TableField("area")
private BigDecimal area;
// ========== 来源 ==========
/**
* 来源:manual-手动绘制,model-模型识别,import-导入
*/
@TableField("source_type")
private String sourceType;
/**
* 关联3D模型ID
*/
@TableField("model_id")
private String modelId;
// ========== 状态 ==========
/**
* 状态:0-禁用,1-启用
*/
@TableField("status")
private Integer status;
/**
* 创建时间
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 删除标记
*/
@TableLogic
@TableField("deleted")
private Integer deleted;
// ========== 枚举 ==========
/**
* 边界类型枚举
*/
public enum BoundaryType {
NAVIGABLE("navigable", "可航行区域"),
OBSTACLE("obstacle", "障碍物"),
RESTRICTED("restricted", "禁行区");
private final String code;
private final String desc;
BoundaryType(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
public static BoundaryType fromCode(String code) {
for (BoundaryType type : values()) {
if (type.getCode().equals(code)) {
return type;
}
}
return NAVIGABLE;
}
}
/**
* 来源类型枚举
*/
public enum SourceType {
MANUAL("manual", "手动绘制"),
MODEL("model", "模型识别"),
IMPORT("import", "导入");
private final String code;
private final String desc;
SourceType(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
}
@@ -0,0 +1,104 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.BoatRoute;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.math.BigDecimal;
import java.util.List;
/**
* 无人船航线Mapper接口
*
* @author dzc
* @date 2026-01-05
*/
@Mapper
public interface BoatRouteMapper extends BaseMapper<BoatRoute> {
/**
* 根据航线ID查询
*
* @param routeId 航线ID
* @return 航线
*/
BoatRoute selectByRouteId(@Param("routeId") String routeId);
/**
* 根据设备SN查询绑定的航线列表
*
* @param deviceSn 设备SN
* @return 航线列表
*/
List<BoatRoute> selectByDeviceSn(@Param("deviceSn") String deviceSn);
/**
* 根据景区ID查询航线列表
*
* @param scenicId 景区ID
* @param tenantId 租户ID
* @return 航线列表
*/
List<BoatRoute> selectByScenicId(@Param("scenicId") Long scenicId, @Param("tenantId") String tenantId);
/**
* 查询模板列表
*
* @param tenantId 租户ID
* @return 模板列表
*/
List<BoatRoute> selectTemplates(@Param("tenantId") String tenantId);
/**
* 更新航线状态
*
* @param routeId 航线ID
* @param status 状态
* @return 影响行数
*/
int updateStatus(@Param("routeId") String routeId, @Param("status") Integer status);
/**
* 更新航线统计信息
*
* @param routeId 航线ID
* @param waypointCount 航点数量
* @param totalDistance 总航程
* @param totalDuration 总时长
* @return 影响行数
*/
int updateRouteStats(@Param("routeId") String routeId,
@Param("waypointCount") Integer waypointCount,
@Param("totalDistance") BigDecimal totalDistance,
@Param("totalDuration") Integer totalDuration);
/**
* 绑定航线到设备
*
* @param routeId 航线ID
* @param deviceSn 设备SN
* @param deviceName 设备名称
* @return 影响行数
*/
int bindToDevice(@Param("routeId") String routeId,
@Param("deviceSn") String deviceSn,
@Param("deviceName") String deviceName);
/**
* 解绑航线和设备
*
* @param routeId 航线ID
* @return 影响行数
*/
int unbindDevice(@Param("routeId") String routeId);
/**
* 设置为模板
*
* @param routeId 航线ID
* @param isTemplate 是否为模板
* @return 影响行数
*/
int setTemplate(@Param("routeId") String routeId, @Param("isTemplate") Boolean isTemplate);
}
@@ -0,0 +1,72 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.BoatTrack;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.time.LocalDateTime;
import java.util.List;
/**
* 无人船轨迹Mapper接口
*
* @author dzc
* @date 2026-01-05
*/
@Mapper
public interface BoatTrackMapper extends BaseMapper<BoatTrack> {
/**
* 查询设备最新位置
*
* @param deviceSn 设备SN
* @return 最新轨迹点
*/
BoatTrack selectLatestByDeviceSn(@Param("deviceSn") String deviceSn);
/**
* 查询设备历史轨迹
*
* @param deviceSn 设备SN
* @param startTime 开始时间
* @param endTime 结束时间
* @return 轨迹列表
*/
List<BoatTrack> selectHistoryTrack(@Param("deviceSn") String deviceSn,
@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime);
/**
* 查询任务轨迹
*
* @param taskId 任务ID
* @return 轨迹列表
*/
List<BoatTrack> selectByTaskId(@Param("taskId") String taskId);
/**
* 查询航线执行轨迹
*
* @param routeId 航线ID
* @param taskId 任务ID
* @return 轨迹列表
*/
List<BoatTrack> selectByRouteIdAndTaskId(@Param("routeId") String routeId, @Param("taskId") String taskId);
/**
* 批量插入轨迹点
*
* @param tracks 轨迹列表
* @return 影响行数
*/
int batchInsert(@Param("list") List<BoatTrack> tracks);
/**
* 删除指定时间之前的轨迹数据(用于历史数据归档)
*
* @param beforeTime 时间阈值
* @return 影响行数
*/
int deleteBeforeTime(@Param("beforeTime") LocalDateTime beforeTime);
}
@@ -0,0 +1,58 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.BoatWaypoint;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 无人船航点Mapper接口
*
* @author dzc
* @date 2026-01-05
*/
@Mapper
public interface BoatWaypointMapper extends BaseMapper<BoatWaypoint> {
/**
* 根据航线ID查询航点列表(按序号排序)
*
* @param routeId 航线ID
* @return 航点列表
*/
List<BoatWaypoint> selectByRouteIdOrderByIndex(@Param("routeId") String routeId);
/**
* 根据航线ID删除航点
*
* @param routeId 航线ID
* @return 影响行数
*/
int deleteByRouteId(@Param("routeId") String routeId);
/**
* 批量插入航点
*
* @param waypoints 航点列表
* @return 影响行数
*/
int batchInsert(@Param("list") List<BoatWaypoint> waypoints);
/**
* 根据航线ID统计航点数量
*
* @param routeId 航线ID
* @return 航点数量
*/
int countByRouteId(@Param("routeId") String routeId);
/**
* 根据航点ID查询
*
* @param waypointId 航点ID
* @return 航点
*/
BoatWaypoint selectByWaypointId(@Param("waypointId") String waypointId);
}
@@ -0,0 +1,64 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.WaterBoundary;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 水域边界Mapper接口
*
* @author dzc
* @date 2026-01-05
*/
@Mapper
public interface WaterBoundaryMapper extends BaseMapper<WaterBoundary> {
/**
* 根据边界ID查询
*
* @param boundaryId 边界ID
* @return 边界
*/
WaterBoundary selectByBoundaryId(@Param("boundaryId") String boundaryId);
/**
* 根据景区ID查询边界列表
*
* @param scenicId 景区ID
* @param tenantId 租户ID
* @return 边界列表
*/
List<WaterBoundary> selectByScenicId(@Param("scenicId") Long scenicId, @Param("tenantId") String tenantId);
/**
* 根据景区ID和边界类型查询
*
* @param scenicId 景区ID
* @param boundaryType 边界类型
* @param tenantId 租户ID
* @return 边界列表
*/
List<WaterBoundary> selectByScenicIdAndType(@Param("scenicId") Long scenicId,
@Param("boundaryType") String boundaryType,
@Param("tenantId") String tenantId);
/**
* 更新边界状态
*
* @param boundaryId 边界ID
* @param status 状态
* @return 影响行数
*/
int updateStatus(@Param("boundaryId") String boundaryId, @Param("status") Integer status);
/**
* 根据3D模型ID查询关联边界
*
* @param modelId 模型ID
* @return 边界列表
*/
List<WaterBoundary> selectByModelId(@Param("modelId") String modelId);
}
@@ -0,0 +1,27 @@
package com.central.device.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 无人船手动控制DTO
*
* @author dzc
* @date 2026-01-05
*/
@Data
@Schema(description = "无人船手动控制请求")
public class BoatManualControlDTO {
@Schema(description = "油门值(-100到100,正数前进,负数后退)")
private Integer throttle;
@Schema(description = "舵角值(-100到100,正数右转,负数左转)")
private Integer rudder;
@Schema(description = "目标航向角(0-360度)")
private Double targetHeading;
@Schema(description = "目标速度(m/s)")
private Double targetSpeed;
}
@@ -0,0 +1,55 @@
package com.central.device.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/**
* 无人船航线创建DTO
*
* @author dzc
* @date 2026-01-05
*/
@Data
@Schema(description = "无人船航线创建请求")
public class BoatRouteCreateDTO {
@Schema(description = "航线名称", required = true)
@NotBlank(message = "航线名称不能为空")
private String routeName;
@Schema(description = "绑定设备SN")
private String deviceSn;
@Schema(description = "所属景区ID")
private Long scenicId;
@Schema(description = "巡航速度(m/s)", example = "2.0")
private BigDecimal cruiseSpeed = BigDecimal.valueOf(2.0);
@Schema(description = "是否循环航行")
private Boolean loopEnabled = false;
@Schema(description = "循环次数(-1无限循环)")
private Integer loopCount = 1;
@Schema(description = "结束动作:return_start-返回起点,stay-原地停留")
private String returnMode = "return_start";
@Schema(description = "安全距离(米)")
private BigDecimal safeDistance = BigDecimal.valueOf(5.0);
@Schema(description = "水域边界ID(用于验证)")
private String boundaryId;
@Schema(description = "备注")
private String remark;
@Schema(description = "航点列表", required = true)
@NotEmpty(message = "航点不能为空")
private List<BoatWaypointDTO> waypoints;
}
@@ -0,0 +1,42 @@
package com.central.device.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/**
* 无人船航线更新DTO
*
* @author dzc
* @date 2026-01-05
*/
@Data
@Schema(description = "无人船航线更新请求")
public class BoatRouteUpdateDTO {
@Schema(description = "航线名称")
private String routeName;
@Schema(description = "巡航速度(m/s)")
private BigDecimal cruiseSpeed;
@Schema(description = "是否循环航行")
private Boolean loopEnabled;
@Schema(description = "循环次数(-1无限循环)")
private Integer loopCount;
@Schema(description = "结束动作:return_start-返回起点,stay-原地停留")
private String returnMode;
@Schema(description = "安全距离(米)")
private BigDecimal safeDistance;
@Schema(description = "备注")
private String remark;
@Schema(description = "航点列表(如果提供则更新所有航点)")
private List<BoatWaypointDTO> waypoints;
}
@@ -0,0 +1,48 @@
package com.central.device.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/**
* 无人船航点DTO
*
* @author dzc
* @date 2026-01-05
*/
@Data
@Schema(description = "无人船航点")
public class BoatWaypointDTO {
@Schema(description = "经度", required = true)
@NotNull(message = "经度不能为空")
private BigDecimal longitude;
@Schema(description = "纬度", required = true)
@NotNull(message = "纬度不能为空")
private BigDecimal latitude;
@Schema(description = "到达此点的速度(m/s),null使用航线默认")
private BigDecimal speed;
@Schema(description = "停留时长(秒)")
private Integer stayDuration = 0;
@Schema(description = "转弯模式:smooth-平滑,sharp-急转")
private String turnMode = "smooth";
@Schema(description = "航点名称")
private String pointName;
@Schema(description = "是否关键点")
private Boolean isKeyPoint = false;
@Schema(description = "航点动作列表")
private List<WaypointActionDTO> actions;
@Schema(description = "备注")
private String remark;
}
@@ -0,0 +1,25 @@
package com.central.device.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 坐标点DTO
*
* @author dzc
* @date 2026-01-05
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "坐标点")
public class PointDTO {
@Schema(description = "经度")
private Double longitude;
@Schema(description = "纬度")
private Double latitude;
}
@@ -0,0 +1,46 @@
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;
import java.math.BigDecimal;
/**
* 水域边界创建DTO
*
* @author dzc
* @date 2026-01-05
*/
@Data
@Schema(description = "水域边界创建请求")
public class WaterBoundaryCreateDTO {
@Schema(description = "边界名称", required = true)
@NotBlank(message = "边界名称不能为空")
private String boundaryName;
@Schema(description = "所属景区ID", required = true)
@NotNull(message = "景区ID不能为空")
private Long scenicId;
@Schema(description = "边界类型:navigable-可航行,obstacle-障碍物,restricted-禁行区")
private String boundaryType = "navigable";
@Schema(description = "多边形坐标(GeoJSON格式)", required = true)
@NotBlank(message = "多边形坐标不能为空")
private String polygonData;
@Schema(description = "中心点坐标")
private String centerPoint;
@Schema(description = "面积(平方米)")
private BigDecimal area;
@Schema(description = "来源:manual-手动绘制,model-模型识别,import-导入")
private String sourceType = "manual";
@Schema(description = "关联3D模型ID")
private String modelId;
}
@@ -0,0 +1,24 @@
package com.central.device.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 航点动作DTO
*
* @author dzc
* @date 2026-01-05
*/
@Data
@Schema(description = "航点动作")
public class WaypointActionDTO {
@Schema(description = "动作类型: photo/video_start/video_stop/horn/light")
private String actionType;
@Schema(description = "动作持续时间(秒)")
private Integer duration;
@Schema(description = "动作参数")
private Object params;
}
@@ -0,0 +1,60 @@
package com.central.device.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 无人船实时位置VO
*
* @author dzc
* @date 2026-01-05
*/
@Data
@Schema(description = "无人船实时位置")
public class BoatRealtimeVO {
@Schema(description = "设备SN")
private String deviceSn;
@Schema(description = "经度")
private BigDecimal longitude;
@Schema(description = "纬度")
private BigDecimal latitude;
@Schema(description = "当前速度(m/s)")
private BigDecimal speed;
@Schema(description = "航向角(度)")
private BigDecimal heading;
@Schema(description = "电池电量(%)")
private Integer batteryPercent;
@Schema(description = "当前执行的航线ID")
private String routeId;
@Schema(description = "当前任务ID")
private String taskId;
@Schema(description = "设备状态")
private String status;
@Schema(description = "偏离航线距离(米)")
private BigDecimal deviationDistance;
@Schema(description = "是否偏离航线")
private Boolean isDeviation;
@Schema(description = "最近航点序号")
private Integer nearestWaypointIndex;
@Schema(description = "数据时间")
private LocalDateTime recordTime;
@Schema(description = "是否在线")
private Boolean online;
}
@@ -0,0 +1,88 @@
package com.central.device.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
/**
* 无人船航线详情VO
*
* @author dzc
* @date 2026-01-05
*/
@Data
@Schema(description = "无人船航线详情")
public class BoatRouteDetailVO {
@Schema(description = "航线ID")
private String routeId;
@Schema(description = "航线名称")
private String routeName;
@Schema(description = "设备SN")
private String deviceSn;
@Schema(description = "设备名称")
private String deviceName;
@Schema(description = "所属景区ID")
private Long scenicId;
@Schema(description = "航点数量")
private Integer waypointCount;
@Schema(description = "总航程(米)")
private BigDecimal totalDistance;
@Schema(description = "预计时长(秒)")
private Integer totalDuration;
@Schema(description = "预计时长(格式化)")
private String totalDurationStr;
@Schema(description = "巡航速度(m/s)")
private BigDecimal cruiseSpeed;
@Schema(description = "是否循环航行")
private Boolean loopEnabled;
@Schema(description = "循环次数")
private Integer loopCount;
@Schema(description = "结束动作")
private String returnMode;
@Schema(description = "安全距离(米)")
private BigDecimal safeDistance;
@Schema(description = "起点坐标")
private String startPoint;
@Schema(description = "终点坐标")
private String endPoint;
@Schema(description = "状态:0-草稿,1-已发布,2-执行中,3-已完成")
private Integer status;
@Schema(description = "状态描述")
private String statusDesc;
@Schema(description = "是否为模板")
private Boolean isTemplate;
@Schema(description = "备注")
private String remark;
@Schema(description = "航点列表")
private List<BoatWaypointVO> waypoints;
@Schema(description = "创建时间")
private LocalDateTime createTime;
@Schema(description = "更新时间")
private LocalDateTime updateTime;
}
@@ -0,0 +1,54 @@
package com.central.device.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 无人船航线列表VO
*
* @author dzc
* @date 2026-01-05
*/
@Data
@Schema(description = "无人船航线列表项")
public class BoatRouteListVO {
@Schema(description = "航线ID")
private String routeId;
@Schema(description = "航线名称")
private String routeName;
@Schema(description = "设备SN")
private String deviceSn;
@Schema(description = "设备名称")
private String deviceName;
@Schema(description = "航点数量")
private Integer waypointCount;
@Schema(description = "总航程(米)")
private BigDecimal totalDistance;
@Schema(description = "预计时长(格式化)")
private String totalDurationStr;
@Schema(description = "巡航速度(m/s)")
private BigDecimal cruiseSpeed;
@Schema(description = "状态:0-草稿,1-已发布,2-执行中,3-已完成")
private Integer status;
@Schema(description = "状态描述")
private String statusDesc;
@Schema(description = "是否为模板")
private Boolean isTemplate;
@Schema(description = "创建时间")
private LocalDateTime createTime;
}
@@ -0,0 +1,55 @@
package com.central.device.model.vo;
import com.central.device.entity.BoatWaypoint;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/**
* 无人船航点VO
*
* @author dzc
* @date 2026-01-05
*/
@Data
@Schema(description = "无人船航点")
public class BoatWaypointVO {
@Schema(description = "航点ID")
private String waypointId;
@Schema(description = "航点序号")
private Integer waypointIndex;
@Schema(description = "经度")
private BigDecimal longitude;
@Schema(description = "纬度")
private BigDecimal latitude;
@Schema(description = "速度(m/s)")
private BigDecimal speed;
@Schema(description = "停留时长(秒)")
private Integer stayDuration;
@Schema(description = "航向角(度)")
private BigDecimal headingAngle;
@Schema(description = "转弯模式")
private String turnMode;
@Schema(description = "是否关键点")
private Boolean isKeyPoint;
@Schema(description = "航点名称")
private String pointName;
@Schema(description = "航点动作列表")
private List<BoatWaypoint.WaypointAction> actions;
@Schema(description = "备注")
private String remark;
}
@@ -0,0 +1,43 @@
package com.central.device.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 边界检测结果VO
*
* @author dzc
* @date 2026-01-05
*/
@Data
@Schema(description = "边界检测结果")
public class BoundaryCheckResultVO {
@Schema(description = "是否全部在边界内")
private Boolean allInBoundary = true;
@Schema(description = "超出边界的航段列表")
private List<String> outOfBoundarySegments = new ArrayList<>();
@Schema(description = "超出边界的航点索引列表")
private List<Integer> outOfBoundaryWaypointIndices = new ArrayList<>();
/**
* 添加超出边界的航段
*/
public void addOutOfBoundarySegment(String segment) {
this.allInBoundary = false;
this.outOfBoundarySegments.add(segment);
}
/**
* 添加超出边界的航点索引
*/
public void addOutOfBoundaryWaypointIndex(Integer index) {
this.allInBoundary = false;
this.outOfBoundaryWaypointIndices.add(index);
}
}
@@ -0,0 +1,48 @@
package com.central.device.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 航线验证结果VO
*
* @author dzc
* @date 2026-01-05
*/
@Data
@Schema(description = "航线验证结果")
public class RouteValidateResultVO {
@Schema(description = "是否验证通过")
private Boolean valid = true;
@Schema(description = "错误列表")
private List<String> errors = new ArrayList<>();
@Schema(description = "警告列表")
private List<String> warnings = new ArrayList<>();
@Schema(description = "总航程(米)")
private Double totalDistance;
@Schema(description = "预计时长(秒)")
private Integer estimatedDuration;
/**
* 添加错误
*/
public void addError(String error) {
this.valid = false;
this.errors.add(error);
}
/**
* 添加警告
*/
public void addWarning(String warning) {
this.warnings.add(warning);
}
}
@@ -0,0 +1,55 @@
package com.central.device.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
/**
* 任务轨迹VO
*
* @author dzc
* @date 2026-01-05
*/
@Data
@Schema(description = "任务轨迹")
public class TaskTrackVO {
@Schema(description = "任务ID")
private String taskId;
@Schema(description = "设备SN")
private String deviceSn;
@Schema(description = "航线ID")
private String routeId;
@Schema(description = "航线名称")
private String routeName;
@Schema(description = "轨迹点列表")
private List<TrackPointVO> trackPoints;
@Schema(description = "轨迹点数量")
private Integer trackPointCount;
@Schema(description = "实际航程(米)")
private BigDecimal actualDistance;
@Schema(description = "实际时长(秒)")
private Integer actualDuration;
@Schema(description = "开始时间")
private LocalDateTime startTime;
@Schema(description = "结束时间")
private LocalDateTime endTime;
@Schema(description = "最大偏离距离(米)")
private BigDecimal maxDeviationDistance;
@Schema(description = "平均速度(m/s)")
private BigDecimal avgSpeed;
}
@@ -0,0 +1,39 @@
package com.central.device.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 轨迹点VO
*
* @author dzc
* @date 2026-01-05
*/
@Data
@Schema(description = "轨迹点")
public class TrackPointVO {
@Schema(description = "经度")
private BigDecimal longitude;
@Schema(description = "纬度")
private BigDecimal latitude;
@Schema(description = "速度(m/s)")
private BigDecimal speed;
@Schema(description = "航向角(度)")
private BigDecimal heading;
@Schema(description = "电池电量(%)")
private Integer batteryPercent;
@Schema(description = "偏离距离(米)")
private BigDecimal deviationDistance;
@Schema(description = "记录时间")
private LocalDateTime recordTime;
}
@@ -0,0 +1,54 @@
package com.central.device.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 水域边界VO
*
* @author dzc
* @date 2026-01-05
*/
@Data
@Schema(description = "水域边界")
public class WaterBoundaryVO {
@Schema(description = "边界ID")
private String boundaryId;
@Schema(description = "边界名称")
private String boundaryName;
@Schema(description = "所属景区ID")
private Long scenicId;
@Schema(description = "边界类型:navigable-可航行,obstacle-障碍物,restricted-禁行区")
private String boundaryType;
@Schema(description = "边界类型描述")
private String boundaryTypeDesc;
@Schema(description = "多边形坐标(GeoJSON)")
private String polygonData;
@Schema(description = "中心点坐标")
private String centerPoint;
@Schema(description = "面积(平方米)")
private BigDecimal area;
@Schema(description = "来源类型")
private String sourceType;
@Schema(description = "状态:0-禁用,1-启用")
private Integer status;
@Schema(description = "状态描述")
private String statusDesc;
@Schema(description = "创建时间")
private LocalDateTime createTime;
}
@@ -0,0 +1,74 @@
package com.central.device.service;
import com.central.device.model.dto.BoatManualControlDTO;
/**
* 无人船控制服务接口
*
* @author dzc
* @date 2026-01-05
*/
public interface IBoatControlService {
/**
* 执行航线任务
*
* @param deviceSn 设备SN
* @param boatRouteId 航线ID
* @param missionCode 任务编码
* @return 任务ID
*/
String executeRoute(String deviceSn, String boatRouteId, String missionCode);
/**
* 暂停航行
*
* @param deviceSn 设备SN
*/
void pause(String deviceSn);
/**
* 恢复航行
*
* @param deviceSn 设备SN
*/
void resume(String deviceSn);
/**
* 返回起点
*
* @param deviceSn 设备SN
*/
void returnToStart(String deviceSn);
/**
* 紧急停止
*
* @param deviceSn 设备SN
*/
void emergencyStop(String deviceSn);
/**
* 手动控制(遥控)
*
* @param deviceSn 设备SN
* @param dto 控制参数
*/
void manualControl(String deviceSn, BoatManualControlDTO dto);
/**
* 检查设备是否在线
*
* @param deviceSn 设备SN
* @return 是否在线
*/
boolean isDeviceOnline(String deviceSn);
/**
* 获取设备当前状态
*
* @param deviceSn 设备SN
* @return 设备状态
*/
String getDeviceStatus(String deviceSn);
}
@@ -0,0 +1,133 @@
package com.central.device.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.device.entity.BoatRoute;
import com.central.device.model.dto.BoatRouteCreateDTO;
import com.central.device.model.dto.BoatRouteUpdateDTO;
import com.central.device.model.vo.BoatRouteDetailVO;
import com.central.device.model.vo.BoatRouteListVO;
import com.central.device.model.vo.RouteValidateResultVO;
import java.util.List;
/**
* 无人船航线服务接口
*
* @author dzc
* @date 2026-01-05
*/
public interface IBoatRouteService extends IService<BoatRoute> {
/**
* 创建航线
*
* @param dto 创建参数
* @return 航线ID
*/
String createRoute(BoatRouteCreateDTO dto);
/**
* 更新航线
*
* @param routeId 航线ID
* @param dto 更新参数
*/
void updateRoute(String routeId, BoatRouteUpdateDTO dto);
/**
* 获取航线详情(含航点)
*
* @param routeId 航线ID
* @return 航线详情
*/
BoatRouteDetailVO getRouteDetail(String routeId);
/**
* 根据航线ID查询实体
*
* @param routeId 航线ID
* @return 航线实体
*/
BoatRoute getByRouteId(String routeId);
/**
* 获取设备绑定的航线列表
*
* @param deviceSn 设备SN
* @return 航线列表
*/
List<BoatRouteListVO> listByDeviceSn(String deviceSn);
/**
* 获取景区航线列表(分页)
*
* @param scenicId 景区ID
* @param page 页码
* @param size 每页数量
* @return 航线分页列表
*/
Page<BoatRouteListVO> listByScenicId(Long scenicId, Integer page, Integer size);
/**
* 绑定航线到设备
*
* @param routeId 航线ID
* @param deviceSn 设备SN
*/
void bindToDevice(String routeId, String deviceSn);
/**
* 解绑航线和设备
*
* @param routeId 航线ID
*/
void unbindDevice(String routeId);
/**
* 校验航线(边界检测)
*
* @param dto 航线数据
* @param boundaryId 边界ID(可选)
* @return 验证结果
*/
RouteValidateResultVO validateRoute(BoatRouteCreateDTO dto, String boundaryId);
/**
* 删除航线
*
* @param routeId 航线ID
*/
void deleteRoute(String routeId);
/**
* 保存为模板
*
* @param routeId 航线ID
* @param templateName 模板名称
* @return 新模板ID
*/
String saveAsTemplate(String routeId, String templateName);
/**
* 获取模板列表
*
* @return 模板列表
*/
List<BoatRouteListVO> listTemplates();
/**
* 更新航线状态
*
* @param routeId 航线ID
* @param status 状态
*/
void updateStatus(String routeId, Integer status);
/**
* 发布航线
*
* @param routeId 航线ID
*/
void publishRoute(String routeId);
}
@@ -0,0 +1,85 @@
package com.central.device.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.device.entity.BoatTrack;
import com.central.device.model.vo.BoatRealtimeVO;
import com.central.device.model.vo.TaskTrackVO;
import com.central.device.model.vo.TrackPointVO;
import java.time.LocalDateTime;
import java.util.List;
import java.util.function.Consumer;
/**
* 无人船轨迹服务接口
*
* @author dzc
* @date 2026-01-05
*/
public interface IBoatTrackService extends IService<BoatTrack> {
/**
* 获取实时位置
*
* @param deviceSn 设备SN
* @return 实时位置
*/
BoatRealtimeVO getRealtimePosition(String deviceSn);
/**
* 获取历史轨迹
*
* @param deviceSn 设备SN
* @param startTime 开始时间
* @param endTime 结束时间
* @return 轨迹点列表
*/
List<TrackPointVO> getHistoryTrack(String deviceSn, LocalDateTime startTime, LocalDateTime endTime);
/**
* 获取任务执行轨迹
*
* @param taskId 任务ID
* @return 任务轨迹
*/
TaskTrackVO getTaskTrack(String taskId);
/**
* 保存轨迹点
*
* @param track 轨迹点
*/
void saveTrackPoint(BoatTrack track);
/**
* 批量保存轨迹点
*
* @param tracks 轨迹点列表
*/
void batchSaveTrackPoints(List<BoatTrack> tracks);
/**
* 注册遥测数据回调
*
* @param deviceSn 设备SN
* @param connectionId 连接ID
* @param callback 回调函数
*/
void registerTelemetryCallback(String deviceSn, String connectionId, Consumer<BoatRealtimeVO> callback);
/**
* 注销遥测数据回调
*
* @param deviceSn 设备SN
* @param connectionId 连接ID
*/
void unregisterTelemetryCallback(String deviceSn, String connectionId);
/**
* 推送遥测数据(供IoT消息处理器调用)
*
* @param deviceSn 设备SN
* @param data 遥测数据
*/
void pushTelemetryData(String deviceSn, BoatRealtimeVO data);
}
@@ -0,0 +1,86 @@
package com.central.device.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.device.entity.WaterBoundary;
import com.central.device.model.dto.PointDTO;
import com.central.device.model.dto.WaterBoundaryCreateDTO;
import com.central.device.model.vo.BoundaryCheckResultVO;
import com.central.device.model.vo.WaterBoundaryVO;
import java.util.List;
/**
* 水域边界服务接口
*
* @author dzc
* @date 2026-01-05
*/
public interface IWaterBoundaryService extends IService<WaterBoundary> {
/**
* 创建水域边界
*
* @param dto 创建参数
* @return 边界ID
*/
String createBoundary(WaterBoundaryCreateDTO dto);
/**
* 根据边界ID查询
*
* @param boundaryId 边界ID
* @return 边界实体
*/
WaterBoundary getByBoundaryId(String boundaryId);
/**
* 获取景区水域边界列表
*
* @param scenicId 景区ID
* @return 边界列表
*/
List<WaterBoundaryVO> listByScenicId(Long scenicId);
/**
* 检测点是否在水域内
*
* @param boundaryId 边界ID
* @param longitude 经度
* @param latitude 纬度
* @return 是否在边界内
*/
boolean isPointInBoundary(String boundaryId, Double longitude, Double latitude);
/**
* 检测航线是否在水域内
*
* @param boundaryId 边界ID
* @param waypoints 航点列表
* @return 检测结果
*/
BoundaryCheckResultVO checkRouteInBoundary(String boundaryId, List<PointDTO> waypoints);
/**
* 从3D模型识别水域边界(异步)
*
* @param modelId 模型ID
* @param scenicId 景区ID
* @return 任务ID
*/
String detectFromModelAsync(String modelId, Long scenicId);
/**
* 更新边界状态
*
* @param boundaryId 边界ID
* @param status 状态
*/
void updateStatus(String boundaryId, Integer status);
/**
* 删除边界
*
* @param boundaryId 边界ID
*/
void deleteBoundary(String boundaryId);
}
@@ -0,0 +1,265 @@
package com.central.device.service.impl;
import com.central.common.exception.BusinessException;
import com.central.device.entity.BoatRoute;
import com.central.device.model.dto.BoatManualControlDTO;
import com.central.device.service.IBoatControlService;
import com.central.device.service.IBoatRouteService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* 无人船控制服务实现
* 当前为Mock实现,待实际设备对接后替换
*
* @author dzc
* @date 2026-01-05
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class BoatControlServiceImpl implements IBoatControlService {
private final IBoatRouteService boatRouteService;
/**
* Mock设备状态存储
* key: deviceSn, value: status
*/
private final Map<String, DeviceState> deviceStates = new ConcurrentHashMap<>();
/**
* Mock设备状态
*/
private static class DeviceState {
String status = "idle"; // idle, executing, paused, returning, stopped
String currentTaskId;
String currentRouteId;
boolean online = true;
}
@Override
public String executeRoute(String deviceSn, String boatRouteId, String missionCode) {
log.info("[Mock] 执行航线任务: deviceSn={}, routeId={}, missionCode={}", deviceSn, boatRouteId, missionCode);
// 验证航线
BoatRoute route = boatRouteService.getByRouteId(boatRouteId);
if (route == null) {
throw new BusinessException("航线不存在");
}
// 检查设备状态
DeviceState state = getOrCreateDeviceState(deviceSn);
if (!state.online) {
throw new BusinessException("设备离线");
}
if ("executing".equals(state.status)) {
throw new BusinessException("设备正在执行其他任务");
}
// 生成任务ID
String taskId = UUID.randomUUID().toString().replace("-", "");
// 更新Mock状态
state.status = "executing";
state.currentTaskId = taskId;
state.currentRouteId = boatRouteId;
// 更新航线状态
boatRouteService.updateStatus(boatRouteId, BoatRoute.RouteStatus.EXECUTING.getCode());
// TODO: 实际设备对接时,通过MQTT/WebSocket发送控制指令
// 指令格式示例:
// {
// "cmd": "execute_route",
// "taskId": taskId,
// "routeId": boatRouteId,
// "waypoints": [...],
// "params": { "speed": ..., "loop": ... }
// }
log.info("[Mock] 航线任务已下发: taskId={}", taskId);
return taskId;
}
@Override
public void pause(String deviceSn) {
log.info("[Mock] 暂停航行: deviceSn={}", deviceSn);
DeviceState state = getOrCreateDeviceState(deviceSn);
if (!"executing".equals(state.status)) {
throw new BusinessException("设备当前未在执行任务");
}
state.status = "paused";
// TODO: 发送暂停指令到设备
// {
// "cmd": "pause",
// "deviceSn": deviceSn
// }
log.info("[Mock] 暂停指令已下发");
}
@Override
public void resume(String deviceSn) {
log.info("[Mock] 恢复航行: deviceSn={}", deviceSn);
DeviceState state = getOrCreateDeviceState(deviceSn);
if (!"paused".equals(state.status)) {
throw new BusinessException("设备当前未处于暂停状态");
}
state.status = "executing";
// TODO: 发送恢复指令到设备
// {
// "cmd": "resume",
// "deviceSn": deviceSn
// }
log.info("[Mock] 恢复指令已下发");
}
@Override
public void returnToStart(String deviceSn) {
log.info("[Mock] 返回起点: deviceSn={}", deviceSn);
DeviceState state = getOrCreateDeviceState(deviceSn);
if (!state.online) {
throw new BusinessException("设备离线");
}
String previousStatus = state.status;
state.status = "returning";
// 如果有正在执行的航线,更新状态
if (state.currentRouteId != null && "executing".equals(previousStatus)) {
boatRouteService.updateStatus(state.currentRouteId, BoatRoute.RouteStatus.PUBLISHED.getCode());
}
// TODO: 发送返航指令到设备
// {
// "cmd": "return_to_start",
// "deviceSn": deviceSn
// }
log.info("[Mock] 返航指令已下发");
}
@Override
public void emergencyStop(String deviceSn) {
log.warn("[Mock] 紧急停止: deviceSn={}", deviceSn);
DeviceState state = getOrCreateDeviceState(deviceSn);
String previousRouteId = state.currentRouteId;
state.status = "stopped";
state.currentTaskId = null;
state.currentRouteId = null;
// 更新航线状态
if (previousRouteId != null) {
boatRouteService.updateStatus(previousRouteId, BoatRoute.RouteStatus.PUBLISHED.getCode());
}
// TODO: 发送紧急停止指令到设备(最高优先级)
// {
// "cmd": "emergency_stop",
// "deviceSn": deviceSn,
// "priority": "highest"
// }
log.warn("[Mock] 紧急停止指令已下发");
}
@Override
public void manualControl(String deviceSn, BoatManualControlDTO dto) {
log.debug("[Mock] 手动控制: deviceSn={}, throttle={}, rudder={}",
deviceSn, dto.getThrottle(), dto.getRudder());
DeviceState state = getOrCreateDeviceState(deviceSn);
if (!state.online) {
throw new BusinessException("设备离线");
}
// 手动控制时暂停自动任务
if ("executing".equals(state.status)) {
state.status = "paused";
log.info("[Mock] 切换到手动控制模式,自动任务已暂停");
}
// TODO: 发送手动控制指令到设备
// 这类指令需要高频发送(如50ms间隔)
// {
// "cmd": "manual_control",
// "deviceSn": deviceSn,
// "throttle": dto.getThrottle(),
// "rudder": dto.getRudder(),
// "timestamp": System.currentTimeMillis()
// }
}
@Override
public boolean isDeviceOnline(String deviceSn) {
DeviceState state = deviceStates.get(deviceSn);
if (state == null) {
// Mock: 假设首次查询的设备都在线
return true;
}
return state.online;
}
@Override
public String getDeviceStatus(String deviceSn) {
DeviceState state = deviceStates.get(deviceSn);
if (state == null) {
return "idle";
}
return state.status;
}
// ========== Mock辅助方法 ==========
private DeviceState getOrCreateDeviceState(String deviceSn) {
return deviceStates.computeIfAbsent(deviceSn, k -> new DeviceState());
}
/**
* 模拟设备上线(供测试使用)
*/
public void mockDeviceOnline(String deviceSn) {
DeviceState state = getOrCreateDeviceState(deviceSn);
state.online = true;
log.info("[Mock] 设备上线: deviceSn={}", deviceSn);
}
/**
* 模拟设备离线(供测试使用)
*/
public void mockDeviceOffline(String deviceSn) {
DeviceState state = getOrCreateDeviceState(deviceSn);
state.online = false;
log.info("[Mock] 设备离线: deviceSn={}", deviceSn);
}
/**
* 模拟任务完成(供测试使用)
*/
public void mockTaskComplete(String deviceSn) {
DeviceState state = deviceStates.get(deviceSn);
if (state != null && state.currentRouteId != null) {
boatRouteService.updateStatus(state.currentRouteId, BoatRoute.RouteStatus.PUBLISHED.getCode());
state.status = "idle";
state.currentTaskId = null;
state.currentRouteId = null;
log.info("[Mock] 任务完成: deviceSn={}", deviceSn);
}
}
}
@@ -0,0 +1,501 @@
package com.central.device.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.exception.BusinessException;
import com.central.device.entity.BoatRoute;
import com.central.device.entity.BoatWaypoint;
import com.central.device.mapper.BoatRouteMapper;
import com.central.device.mapper.BoatWaypointMapper;
import com.central.device.model.dto.BoatRouteCreateDTO;
import com.central.device.model.dto.BoatRouteUpdateDTO;
import com.central.device.model.dto.BoatWaypointDTO;
import com.central.device.model.dto.PointDTO;
import com.central.device.model.vo.*;
import com.central.device.service.IBoatRouteService;
import com.central.device.service.IWaterBoundaryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* 无人船航线服务实现
*
* @author dzc
* @date 2026-01-05
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class BoatRouteServiceImpl extends ServiceImpl<BoatRouteMapper, BoatRoute> implements IBoatRouteService {
private final BoatWaypointMapper waypointMapper;
private final IWaterBoundaryService waterBoundaryService;
@Override
@Transactional(rollbackFor = Exception.class)
public String createRoute(BoatRouteCreateDTO dto) {
// 1. 创建航线主记录
BoatRoute route = new BoatRoute();
route.setRouteId(UUID.randomUUID().toString().replace("-", ""));
route.setRouteName(dto.getRouteName());
route.setDeviceSn(dto.getDeviceSn());
route.setScenicId(dto.getScenicId());
route.setCruiseSpeed(dto.getCruiseSpeed());
route.setLoopEnabled(dto.getLoopEnabled());
route.setLoopCount(dto.getLoopCount());
route.setReturnMode(dto.getReturnMode());
route.setSafeDistance(dto.getSafeDistance());
route.setRemark(dto.getRemark());
route.setTenantId(LoginUserContextHolder.getCurrentTenantId());
route.setStatus(BoatRoute.RouteStatus.DRAFT.getCode());
route.setIsTemplate(false);
// 2. 计算航线统计信息
List<BoatWaypointDTO> waypoints = dto.getWaypoints();
route.setWaypointCount(waypoints.size());
// 计算总距离
double totalDistance = calculateTotalDistance(waypoints);
route.setTotalDistance(BigDecimal.valueOf(totalDistance).setScale(2, RoundingMode.HALF_UP));
// 计算预计时长
int totalDuration = calculateDuration(totalDistance, dto.getCruiseSpeed().doubleValue(), waypoints);
route.setTotalDuration(totalDuration);
// 设置起止点
BoatWaypointDTO firstPoint = waypoints.get(0);
BoatWaypointDTO lastPoint = waypoints.get(waypoints.size() - 1);
route.setStartPoint(firstPoint.getLongitude() + "," + firstPoint.getLatitude());
route.setEndPoint(lastPoint.getLongitude() + "," + lastPoint.getLatitude());
this.save(route);
// 3. 保存航点
saveWaypoints(route.getRouteId(), waypoints, dto.getCruiseSpeed());
log.info("航线创建成功: routeId={}, name={}, waypointCount={}",
route.getRouteId(), route.getRouteName(), waypoints.size());
return route.getRouteId();
}
private void saveWaypoints(String routeId, List<BoatWaypointDTO> waypoints, BigDecimal defaultSpeed) {
List<BoatWaypoint> entities = new ArrayList<>();
for (int i = 0; i < waypoints.size(); i++) {
BoatWaypointDTO dto = waypoints.get(i);
BoatWaypoint entity = new BoatWaypoint();
entity.setWaypointId(UUID.randomUUID().toString().replace("-", ""));
entity.setRouteId(routeId);
entity.setWaypointIndex(i);
entity.setLongitude(dto.getLongitude());
entity.setLatitude(dto.getLatitude());
entity.setSpeed(dto.getSpeed() != null ? dto.getSpeed() : defaultSpeed);
entity.setStayDuration(dto.getStayDuration() != null ? dto.getStayDuration() : 0);
entity.setTurnMode(dto.getTurnMode() != null ? dto.getTurnMode() : "smooth");
entity.setPointName(dto.getPointName() != null ? dto.getPointName() : "航点" + (i + 1));
entity.setIsKeyPoint(dto.getIsKeyPoint() != null ? dto.getIsKeyPoint() : false);
entity.setRemark(dto.getRemark());
// 转换动作列表
if (dto.getActions() != null && !dto.getActions().isEmpty()) {
List<BoatWaypoint.WaypointAction> actions = dto.getActions().stream()
.map(a -> {
BoatWaypoint.WaypointAction action = new BoatWaypoint.WaypointAction();
action.setActionType(a.getActionType());
action.setDuration(a.getDuration());
action.setParams(a.getParams());
return action;
}).collect(Collectors.toList());
entity.setActions(actions);
}
// 自动计算航向角(指向下一个航点)
if (i < waypoints.size() - 1) {
BoatWaypointDTO nextPoint = waypoints.get(i + 1);
double heading = calculateHeading(
dto.getLongitude().doubleValue(), dto.getLatitude().doubleValue(),
nextPoint.getLongitude().doubleValue(), nextPoint.getLatitude().doubleValue()
);
entity.setHeadingAngle(BigDecimal.valueOf(heading).setScale(2, RoundingMode.HALF_UP));
}
entities.add(entity);
}
waypointMapper.batchInsert(entities);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateRoute(String routeId, BoatRouteUpdateDTO dto) {
BoatRoute route = getByRouteId(routeId);
if (route == null) {
throw new BusinessException("航线不存在");
}
// 更新基本信息
if (StrUtil.isNotBlank(dto.getRouteName())) {
route.setRouteName(dto.getRouteName());
}
if (dto.getCruiseSpeed() != null) {
route.setCruiseSpeed(dto.getCruiseSpeed());
}
if (dto.getLoopEnabled() != null) {
route.setLoopEnabled(dto.getLoopEnabled());
}
if (dto.getLoopCount() != null) {
route.setLoopCount(dto.getLoopCount());
}
if (StrUtil.isNotBlank(dto.getReturnMode())) {
route.setReturnMode(dto.getReturnMode());
}
if (dto.getSafeDistance() != null) {
route.setSafeDistance(dto.getSafeDistance());
}
if (dto.getRemark() != null) {
route.setRemark(dto.getRemark());
}
// 如果提供了航点则更新航点
if (dto.getWaypoints() != null && !dto.getWaypoints().isEmpty()) {
// 删除旧航点
waypointMapper.deleteByRouteId(routeId);
// 保存新航点
saveWaypoints(routeId, dto.getWaypoints(), route.getCruiseSpeed());
// 更新统计信息
route.setWaypointCount(dto.getWaypoints().size());
double totalDistance = calculateTotalDistance(dto.getWaypoints());
route.setTotalDistance(BigDecimal.valueOf(totalDistance).setScale(2, RoundingMode.HALF_UP));
int totalDuration = calculateDuration(totalDistance, route.getCruiseSpeed().doubleValue(), dto.getWaypoints());
route.setTotalDuration(totalDuration);
// 更新起止点
BoatWaypointDTO firstPoint = dto.getWaypoints().get(0);
BoatWaypointDTO lastPoint = dto.getWaypoints().get(dto.getWaypoints().size() - 1);
route.setStartPoint(firstPoint.getLongitude() + "," + firstPoint.getLatitude());
route.setEndPoint(lastPoint.getLongitude() + "," + lastPoint.getLatitude());
}
this.updateById(route);
log.info("航线更新成功: routeId={}", routeId);
}
@Override
public BoatRouteDetailVO getRouteDetail(String routeId) {
BoatRoute route = getByRouteId(routeId);
if (route == null) {
throw new BusinessException("航线不存在");
}
BoatRouteDetailVO vo = BeanUtil.copyProperties(route, BoatRouteDetailVO.class);
vo.setStatusDesc(BoatRoute.RouteStatus.fromCode(route.getStatus()).getDesc());
vo.setTotalDurationStr(formatDuration(route.getTotalDuration()));
// 获取航点
List<BoatWaypoint> waypoints = waypointMapper.selectByRouteIdOrderByIndex(routeId);
List<BoatWaypointVO> waypointVOs = waypoints.stream()
.map(wp -> {
BoatWaypointVO wpVo = BeanUtil.copyProperties(wp, BoatWaypointVO.class);
return wpVo;
}).collect(Collectors.toList());
vo.setWaypoints(waypointVOs);
return vo;
}
@Override
public BoatRoute getByRouteId(String routeId) {
return baseMapper.selectByRouteId(routeId);
}
@Override
public List<BoatRouteListVO> listByDeviceSn(String deviceSn) {
List<BoatRoute> routes = baseMapper.selectByDeviceSn(deviceSn);
return convertToListVO(routes);
}
@Override
public Page<BoatRouteListVO> listByScenicId(Long scenicId, Integer page, Integer size) {
String tenantId = LoginUserContextHolder.getCurrentTenantId();
Page<BoatRoute> pageParam = new Page<>(page, size);
LambdaQueryWrapper<BoatRoute> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(BoatRoute::getScenicId, scenicId)
.eq(BoatRoute::getTenantId, tenantId)
.eq(BoatRoute::getDeleted, 0)
.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
@Transactional(rollbackFor = Exception.class)
public void bindToDevice(String routeId, String deviceSn) {
BoatRoute route = getByRouteId(routeId);
if (route == null) {
throw new BusinessException("航线不存在");
}
// TODO: 获取设备名称
baseMapper.bindToDevice(routeId, deviceSn, null);
log.info("航线绑定设备成功: routeId={}, deviceSn={}", routeId, deviceSn);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void unbindDevice(String routeId) {
baseMapper.unbindDevice(routeId);
log.info("航线解绑设备成功: routeId={}", routeId);
}
@Override
public RouteValidateResultVO validateRoute(BoatRouteCreateDTO dto, String boundaryId) {
RouteValidateResultVO result = new RouteValidateResultVO();
List<BoatWaypointDTO> waypoints = dto.getWaypoints();
// 1. 检查航点是否在水域边界内
if (StrUtil.isNotBlank(boundaryId)) {
for (int i = 0; i < waypoints.size(); i++) {
BoatWaypointDTO wp = waypoints.get(i);
boolean inBoundary = waterBoundaryService.isPointInBoundary(
boundaryId, wp.getLongitude().doubleValue(), wp.getLatitude().doubleValue()
);
if (!inBoundary) {
result.addError(String.format("航点%d超出水域边界", i + 1));
}
}
// 2. 检查航线段是否穿过边界外区域
List<PointDTO> points = waypoints.stream()
.map(w -> new PointDTO(w.getLongitude().doubleValue(), w.getLatitude().doubleValue()))
.collect(Collectors.toList());
BoundaryCheckResultVO lineCheck = waterBoundaryService.checkRouteInBoundary(boundaryId, points);
if (!lineCheck.getAllInBoundary()) {
result.getErrors().addAll(lineCheck.getOutOfBoundarySegments());
result.setValid(false);
}
}
// 3. 检查航点间距
for (int i = 0; i < waypoints.size() - 1; i++) {
BoatWaypointDTO p1 = waypoints.get(i);
BoatWaypointDTO p2 = waypoints.get(i + 1);
double distance = calculateDistance(
p1.getLongitude().doubleValue(), p1.getLatitude().doubleValue(),
p2.getLongitude().doubleValue(), p2.getLatitude().doubleValue()
);
if (distance < 5) {
result.addWarning(String.format("航点%d和%d间距过近(%.1fm)", i + 1, i + 2, distance));
}
if (distance > 1000) {
result.addWarning(String.format("航点%d和%d间距过远(%.0fm),建议增加中间点", i + 1, i + 2, distance));
}
}
// 4. 计算总航程和预计时长
double totalDistance = calculateTotalDistance(waypoints);
result.setTotalDistance(totalDistance);
int estimatedDuration = calculateDuration(totalDistance, dto.getCruiseSpeed().doubleValue(), waypoints);
result.setEstimatedDuration(estimatedDuration);
// 5. 检查总航程
if (totalDistance > 10000) {
result.addWarning(String.format("总航程较长(%.0fm),请确认电量充足", totalDistance));
}
return result;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteRoute(String routeId) {
BoatRoute route = getByRouteId(routeId);
if (route == null) {
throw new BusinessException("航线不存在");
}
if (route.getStatus() == BoatRoute.RouteStatus.EXECUTING.getCode()) {
throw new BusinessException("执行中的航线不能删除");
}
// 逻辑删除航线
route.setDeleted(1);
this.updateById(route);
// 删除航点
waypointMapper.deleteByRouteId(routeId);
log.info("航线删除成功: routeId={}", routeId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public String saveAsTemplate(String routeId, String templateName) {
BoatRouteDetailVO detail = getRouteDetail(routeId);
// 创建新的模板航线
BoatRouteCreateDTO dto = new BoatRouteCreateDTO();
dto.setRouteName(templateName);
dto.setScenicId(detail.getScenicId());
dto.setCruiseSpeed(detail.getCruiseSpeed());
dto.setLoopEnabled(detail.getLoopEnabled());
dto.setLoopCount(detail.getLoopCount());
dto.setReturnMode(detail.getReturnMode());
dto.setSafeDistance(detail.getSafeDistance());
// 转换航点
List<BoatWaypointDTO> waypointDTOs = detail.getWaypoints().stream()
.map(wp -> {
BoatWaypointDTO wpDto = new BoatWaypointDTO();
wpDto.setLongitude(wp.getLongitude());
wpDto.setLatitude(wp.getLatitude());
wpDto.setSpeed(wp.getSpeed());
wpDto.setStayDuration(wp.getStayDuration());
wpDto.setTurnMode(wp.getTurnMode());
wpDto.setPointName(wp.getPointName());
wpDto.setIsKeyPoint(wp.getIsKeyPoint());
return wpDto;
}).collect(Collectors.toList());
dto.setWaypoints(waypointDTOs);
String newRouteId = createRoute(dto);
// 标记为模板
baseMapper.setTemplate(newRouteId, true);
log.info("航线保存为模板成功: sourceRouteId={}, newRouteId={}, templateName={}",
routeId, newRouteId, templateName);
return newRouteId;
}
@Override
public List<BoatRouteListVO> listTemplates() {
String tenantId = LoginUserContextHolder.getCurrentTenantId();
List<BoatRoute> templates = baseMapper.selectTemplates(tenantId);
return convertToListVO(templates);
}
@Override
public void updateStatus(String routeId, Integer status) {
baseMapper.updateStatus(routeId, status);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void publishRoute(String routeId) {
BoatRoute route = getByRouteId(routeId);
if (route == null) {
throw new BusinessException("航线不存在");
}
if (route.getStatus() != BoatRoute.RouteStatus.DRAFT.getCode()) {
throw new BusinessException("只有草稿状态的航线才能发布");
}
updateStatus(routeId, BoatRoute.RouteStatus.PUBLISHED.getCode());
log.info("航线发布成功: routeId={}", routeId);
}
// ========== 工具方法 ==========
private List<BoatRouteListVO> convertToListVO(List<BoatRoute> routes) {
return routes.stream().map(route -> {
BoatRouteListVO vo = BeanUtil.copyProperties(route, BoatRouteListVO.class);
vo.setStatusDesc(BoatRoute.RouteStatus.fromCode(route.getStatus()).getDesc());
vo.setTotalDurationStr(formatDuration(route.getTotalDuration()));
return vo;
}).collect(Collectors.toList());
}
private double calculateTotalDistance(List<BoatWaypointDTO> waypoints) {
double total = 0;
for (int i = 0; i < waypoints.size() - 1; i++) {
BoatWaypointDTO p1 = waypoints.get(i);
BoatWaypointDTO p2 = waypoints.get(i + 1);
total += calculateDistance(
p1.getLongitude().doubleValue(), p1.getLatitude().doubleValue(),
p2.getLongitude().doubleValue(), p2.getLatitude().doubleValue()
);
}
return total;
}
/**
* 计算两点间距离(Haversine公式)
*/
private double calculateDistance(double lon1, double lat1, double lon2, double lat2) {
final double R = 6371000; // 地球半径(米)
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
/**
* 计算航向角
*/
private double calculateHeading(double lon1, double lat1, double lon2, double lat2) {
double dLon = Math.toRadians(lon2 - lon1);
double y = Math.sin(dLon) * Math.cos(Math.toRadians(lat2));
double x = Math.cos(Math.toRadians(lat1)) * Math.sin(Math.toRadians(lat2)) -
Math.sin(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.cos(dLon);
double heading = Math.toDegrees(Math.atan2(y, x));
return (heading + 360) % 360; // 归一化到0-360
}
/**
* 计算预计时长(秒)
*/
private int calculateDuration(double totalDistance, double cruiseSpeed, List<BoatWaypointDTO> waypoints) {
// 航行时间
int travelTime = (int) (totalDistance / cruiseSpeed);
// 停留时间
int stayTime = waypoints.stream()
.mapToInt(wp -> wp.getStayDuration() != null ? wp.getStayDuration() : 0)
.sum();
return travelTime + stayTime;
}
/**
* 格式化时长
*/
private String formatDuration(Integer seconds) {
if (seconds == null || seconds <= 0) {
return "0秒";
}
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
int secs = seconds % 60;
StringBuilder sb = new StringBuilder();
if (hours > 0) {
sb.append(hours).append("小时");
}
if (minutes > 0) {
sb.append(minutes).append("分");
}
if (secs > 0 || sb.length() == 0) {
sb.append(secs).append("秒");
}
return sb.toString();
}
}
@@ -0,0 +1,241 @@
package com.central.device.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.common.exception.BusinessException;
import com.central.device.entity.BoatTrack;
import com.central.device.mapper.BoatTrackMapper;
import com.central.device.model.vo.BoatRealtimeVO;
import com.central.device.model.vo.TaskTrackVO;
import com.central.device.model.vo.TrackPointVO;
import com.central.device.service.IBoatTrackService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* 无人船轨迹服务实现
*
* @author dzc
* @date 2026-01-05
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class BoatTrackServiceImpl extends ServiceImpl<BoatTrackMapper, BoatTrack> implements IBoatTrackService {
/**
* 设备实时数据缓存
* key: deviceSn, value: 最新遥测数据
*/
private final Map<String, BoatRealtimeVO> realtimeCache = new ConcurrentHashMap<>();
/**
* 遥测数据回调注册表
* key: deviceSn, value: Map<connectionId, callback>
*/
private final Map<String, Map<String, Consumer<BoatRealtimeVO>>> telemetryCallbacks = new ConcurrentHashMap<>();
@Override
public BoatRealtimeVO getRealtimePosition(String deviceSn) {
// 先从缓存获取
BoatRealtimeVO cached = realtimeCache.get(deviceSn);
if (cached != null) {
return cached;
}
// 缓存没有则从数据库获取最新记录
BoatTrack latest = baseMapper.selectLatestByDeviceSn(deviceSn);
if (latest == null) {
return null;
}
BoatRealtimeVO vo = convertToRealtimeVO(latest);
realtimeCache.put(deviceSn, vo);
return vo;
}
@Override
public List<TrackPointVO> getHistoryTrack(String deviceSn, LocalDateTime startTime, LocalDateTime endTime) {
if (startTime == null || endTime == null) {
throw new BusinessException("开始时间和结束时间不能为空");
}
if (startTime.isAfter(endTime)) {
throw new BusinessException("开始时间不能晚于结束时间");
}
List<BoatTrack> tracks = baseMapper.selectHistoryTrack(deviceSn, startTime, endTime);
return tracks.stream()
.map(this::convertToTrackPointVO)
.collect(Collectors.toList());
}
@Override
public TaskTrackVO getTaskTrack(String taskId) {
List<BoatTrack> tracks = baseMapper.selectByTaskId(taskId);
if (tracks.isEmpty()) {
return null;
}
TaskTrackVO vo = new TaskTrackVO();
vo.setTaskId(taskId);
vo.setDeviceSn(tracks.get(0).getDeviceSn());
List<TrackPointVO> points = tracks.stream()
.map(this::convertToTrackPointVO)
.collect(Collectors.toList());
vo.setTrackPoints(points);
vo.setTrackPointCount(points.size());
// 计算统计信息
if (!tracks.isEmpty()) {
BoatTrack first = tracks.get(0);
BoatTrack last = tracks.get(tracks.size() - 1);
vo.setStartTime(first.getRecordTime());
vo.setEndTime(last.getRecordTime());
// 计算总里程
double totalDistance = 0;
for (int i = 1; i < tracks.size(); i++) {
BoatTrack p1 = tracks.get(i - 1);
BoatTrack p2 = tracks.get(i);
totalDistance += calculateDistance(
p1.getLongitude().doubleValue(), p1.getLatitude().doubleValue(),
p2.getLongitude().doubleValue(), p2.getLatitude().doubleValue()
);
}
vo.setActualDistance(java.math.BigDecimal.valueOf(totalDistance));
}
return vo;
}
@Override
public void saveTrackPoint(BoatTrack track) {
this.save(track);
// 更新实时缓存
BoatRealtimeVO realtimeVO = convertToRealtimeVO(track);
realtimeCache.put(track.getDeviceSn(), realtimeVO);
// 推送给订阅者
pushTelemetryData(track.getDeviceSn(), realtimeVO);
}
@Override
public void batchSaveTrackPoints(List<BoatTrack> tracks) {
if (tracks == null || tracks.isEmpty()) {
return;
}
baseMapper.batchInsert(tracks);
// 更新每个设备的实时缓存(取最新的)
Map<String, BoatTrack> latestByDevice = new ConcurrentHashMap<>();
for (BoatTrack track : tracks) {
BoatTrack existing = latestByDevice.get(track.getDeviceSn());
if (existing == null || track.getRecordTime().isAfter(existing.getRecordTime())) {
latestByDevice.put(track.getDeviceSn(), track);
}
}
for (Map.Entry<String, BoatTrack> entry : latestByDevice.entrySet()) {
BoatRealtimeVO realtimeVO = convertToRealtimeVO(entry.getValue());
realtimeCache.put(entry.getKey(), realtimeVO);
pushTelemetryData(entry.getKey(), realtimeVO);
}
}
@Override
public void registerTelemetryCallback(String deviceSn, String connectionId, Consumer<BoatRealtimeVO> callback) {
Map<String, Consumer<BoatRealtimeVO>> deviceCallbacks =
telemetryCallbacks.computeIfAbsent(deviceSn, k -> new ConcurrentHashMap<>());
deviceCallbacks.put(connectionId, callback);
log.info("注册遥测回调: deviceSn={}, connectionId={}", deviceSn, connectionId);
}
@Override
public void unregisterTelemetryCallback(String deviceSn, String connectionId) {
Map<String, Consumer<BoatRealtimeVO>> deviceCallbacks = telemetryCallbacks.get(deviceSn);
if (deviceCallbacks != null) {
deviceCallbacks.remove(connectionId);
if (deviceCallbacks.isEmpty()) {
telemetryCallbacks.remove(deviceSn);
}
log.info("注销遥测回调: deviceSn={}, connectionId={}", deviceSn, connectionId);
}
}
@Override
public void pushTelemetryData(String deviceSn, BoatRealtimeVO data) {
// 更新缓存
realtimeCache.put(deviceSn, data);
// 通知所有订阅者
Map<String, Consumer<BoatRealtimeVO>> deviceCallbacks = telemetryCallbacks.get(deviceSn);
if (deviceCallbacks != null && !deviceCallbacks.isEmpty()) {
for (Map.Entry<String, Consumer<BoatRealtimeVO>> entry : deviceCallbacks.entrySet()) {
try {
entry.getValue().accept(data);
} catch (Exception e) {
log.warn("遥测回调执行失败: deviceSn={}, connectionId={}, error={}",
deviceSn, entry.getKey(), e.getMessage());
// 移除失败的回调
deviceCallbacks.remove(entry.getKey());
}
}
}
}
// ========== 私有方法 ==========
private BoatRealtimeVO convertToRealtimeVO(BoatTrack track) {
BoatRealtimeVO vo = new BoatRealtimeVO();
vo.setDeviceSn(track.getDeviceSn());
vo.setLongitude(track.getLongitude());
vo.setLatitude(track.getLatitude());
vo.setHeading(track.getHeading());
vo.setSpeed(track.getSpeed());
vo.setBatteryPercent(track.getBatteryPercent());
vo.setRecordTime(track.getRecordTime());
vo.setTaskId(track.getTaskId());
vo.setRouteId(track.getRouteId());
vo.setNearestWaypointIndex(track.getNearestWaypointIndex());
vo.setDeviationDistance(track.getDeviationDistance());
vo.setIsDeviation(track.getIsDeviation());
return vo;
}
private TrackPointVO convertToTrackPointVO(BoatTrack track) {
TrackPointVO vo = new TrackPointVO();
vo.setLongitude(track.getLongitude());
vo.setLatitude(track.getLatitude());
vo.setHeading(track.getHeading());
vo.setSpeed(track.getSpeed());
vo.setBatteryPercent(track.getBatteryPercent());
vo.setRecordTime(track.getRecordTime());
vo.setDeviationDistance(track.getDeviationDistance());
return vo;
}
/**
* 计算两点间距离(Haversine公式)
*/
private double calculateDistance(double lon1, double lat1, double lon2, double lat2) {
final double R = 6371000; // 地球半径(米)
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
}
@@ -0,0 +1,281 @@
package com.central.device.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.exception.BusinessException;
import com.central.device.entity.WaterBoundary;
import com.central.device.mapper.WaterBoundaryMapper;
import com.central.device.model.dto.PointDTO;
import com.central.device.model.dto.WaterBoundaryCreateDTO;
import com.central.device.model.vo.BoundaryCheckResultVO;
import com.central.device.model.vo.WaterBoundaryVO;
import com.central.device.service.IWaterBoundaryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* 水域边界服务实现
* 使用射线法(Ray Casting)进行点在多边形内的检测
*
* @author dzc
* @date 2026-01-05
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class WaterBoundaryServiceImpl extends ServiceImpl<WaterBoundaryMapper, WaterBoundary> implements IWaterBoundaryService {
@Override
@Transactional(rollbackFor = Exception.class)
public String createBoundary(WaterBoundaryCreateDTO dto) {
WaterBoundary boundary = new WaterBoundary();
boundary.setBoundaryId(UUID.randomUUID().toString().replace("-", ""));
boundary.setBoundaryName(dto.getBoundaryName());
boundary.setScenicId(dto.getScenicId());
boundary.setBoundaryType(dto.getBoundaryType());
boundary.setPolygonData(dto.getPolygonData());
boundary.setCenterPoint(dto.getCenterPoint());
boundary.setArea(dto.getArea());
boundary.setSourceType(dto.getSourceType() != null ? dto.getSourceType() : WaterBoundary.SourceType.MANUAL.getCode());
boundary.setModelId(dto.getModelId());
boundary.setTenantId(LoginUserContextHolder.getCurrentTenantId());
boundary.setStatus(1); // 启用状态
this.save(boundary);
log.info("水域边界创建成功: boundaryId={}, name={}", boundary.getBoundaryId(), boundary.getBoundaryName());
return boundary.getBoundaryId();
}
@Override
public WaterBoundary getByBoundaryId(String boundaryId) {
return baseMapper.selectByBoundaryId(boundaryId);
}
@Override
public List<WaterBoundaryVO> listByScenicId(Long scenicId) {
String tenantId = LoginUserContextHolder.getCurrentTenantId();
List<WaterBoundary> boundaries = baseMapper.selectByScenicId(scenicId, tenantId);
return boundaries.stream()
.map(b -> {
WaterBoundaryVO vo = BeanUtil.copyProperties(b, WaterBoundaryVO.class);
vo.setStatusDesc(b.getStatus() == 1 ? "启用" : "禁用");
vo.setBoundaryTypeDesc(WaterBoundary.BoundaryType.fromCode(b.getBoundaryType()).getDesc());
return vo;
})
.collect(Collectors.toList());
}
@Override
public boolean isPointInBoundary(String boundaryId, Double longitude, Double latitude) {
WaterBoundary boundary = getByBoundaryId(boundaryId);
if (boundary == null) {
throw new BusinessException("边界不存在");
}
// 解析GeoJSON获取多边形顶点
List<double[]> polygon = parseGeoJsonPolygon(boundary.getPolygonData());
if (polygon.isEmpty()) {
return false;
}
// 射线法检测
return isPointInPolygon(longitude, latitude, polygon);
}
@Override
public BoundaryCheckResultVO checkRouteInBoundary(String boundaryId, List<PointDTO> waypoints) {
BoundaryCheckResultVO result = new BoundaryCheckResultVO();
result.setAllInBoundary(true);
result.setOutOfBoundarySegments(new ArrayList<>());
WaterBoundary boundary = getByBoundaryId(boundaryId);
if (boundary == null) {
result.setAllInBoundary(false);
result.addOutOfBoundarySegment("边界不存在");
return result;
}
List<double[]> polygon = parseGeoJsonPolygon(boundary.getPolygonData());
if (polygon.isEmpty()) {
result.setAllInBoundary(false);
result.addOutOfBoundarySegment("边界数据无效");
return result;
}
// 检查每个航点
List<Integer> outOfBoundaryPoints = new ArrayList<>();
for (int i = 0; i < waypoints.size(); i++) {
PointDTO point = waypoints.get(i);
if (!isPointInPolygon(point.getLongitude(), point.getLatitude(), polygon)) {
outOfBoundaryPoints.add(i + 1);
}
}
if (!outOfBoundaryPoints.isEmpty()) {
result.setAllInBoundary(false);
result.addOutOfBoundarySegment("航点" + outOfBoundaryPoints.toString() + "超出边界");
}
// 检查航线段是否穿过边界
for (int i = 0; i < waypoints.size() - 1; i++) {
PointDTO p1 = waypoints.get(i);
PointDTO p2 = waypoints.get(i + 1);
if (doesLineSegmentCrossBoundary(p1, p2, polygon)) {
result.setAllInBoundary(false);
result.addOutOfBoundarySegment(String.format("航线段%d-%d穿过边界", i + 1, i + 2));
}
}
return result;
}
@Override
@Async
public String detectFromModelAsync(String modelId, Long scenicId) {
// TODO: 实现从3D模型中自动检测水域边界
// 这是P2功能,暂时返回一个任务ID占位
String taskId = UUID.randomUUID().toString().replace("-", "");
log.info("启动水域边界自动检测任务: taskId={}, modelId={}, scenicId={}", taskId, modelId, scenicId);
return taskId;
}
@Override
public void updateStatus(String boundaryId, Integer status) {
baseMapper.updateStatus(boundaryId, status);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteBoundary(String boundaryId) {
WaterBoundary boundary = getByBoundaryId(boundaryId);
if (boundary == null) {
throw new BusinessException("边界不存在");
}
// 逻辑删除
boundary.setDeleted(1);
this.updateById(boundary);
log.info("水域边界删除成功: boundaryId={}", boundaryId);
}
// ========== 私有方法 ==========
/**
* 解析GeoJSON获取多边形坐标
* 支持Polygon类型的GeoJSON
*/
private List<double[]> parseGeoJsonPolygon(String geoJson) {
List<double[]> result = new ArrayList<>();
if (StrUtil.isBlank(geoJson)) {
return result;
}
try {
JSONObject json = JSON.parseObject(geoJson);
String type = json.getString("type");
if ("Polygon".equals(type)) {
JSONArray coordinates = json.getJSONArray("coordinates");
if (coordinates != null && !coordinates.isEmpty()) {
// Polygon的coordinates是一个二维数组,第一个是外环
JSONArray outerRing = coordinates.getJSONArray(0);
for (int i = 0; i < outerRing.size(); i++) {
JSONArray point = outerRing.getJSONArray(i);
result.add(new double[]{point.getDoubleValue(0), point.getDoubleValue(1)});
}
}
} else if ("Feature".equals(type)) {
JSONObject geometry = json.getJSONObject("geometry");
if (geometry != null && "Polygon".equals(geometry.getString("type"))) {
JSONArray coordinates = geometry.getJSONArray("coordinates");
if (coordinates != null && !coordinates.isEmpty()) {
JSONArray outerRing = coordinates.getJSONArray(0);
for (int i = 0; i < outerRing.size(); i++) {
JSONArray point = outerRing.getJSONArray(i);
result.add(new double[]{point.getDoubleValue(0), point.getDoubleValue(1)});
}
}
}
}
} catch (Exception e) {
log.error("解析GeoJSON失败: {}", e.getMessage());
}
return result;
}
/**
* 射线法(Ray Casting)判断点是否在多边形内
* 算法: 从该点向右发射一条射线,计算与多边形边界的交点数
* 交点为奇数则在内部,偶数则在外部
*/
private boolean isPointInPolygon(double x, double y, List<double[]> polygon) {
int n = polygon.size();
if (n < 3) {
return false;
}
int crossings = 0;
for (int i = 0; i < n; i++) {
double[] p1 = polygon.get(i);
double[] p2 = polygon.get((i + 1) % n);
double x1 = p1[0], y1 = p1[1];
double x2 = p2[0], y2 = p2[1];
// 检查边是否跨越射线所在的水平线
if ((y1 <= y && y < y2) || (y2 <= y && y < y1)) {
// 计算射线与边的交点x坐标
double intersectX = x1 + (y - y1) * (x2 - x1) / (y2 - y1);
if (x < intersectX) {
crossings++;
}
}
}
return (crossings % 2) == 1;
}
/**
* 检查线段是否穿过多边形边界
* 通过在线段上采样多个点来检测
*/
private boolean doesLineSegmentCrossBoundary(PointDTO p1, PointDTO p2, List<double[]> polygon) {
boolean p1Inside = isPointInPolygon(p1.getLongitude(), p1.getLatitude(), polygon);
boolean p2Inside = isPointInPolygon(p2.getLongitude(), p2.getLatitude(), polygon);
// 如果两端点状态不同,则一定穿过边界
if (p1Inside != p2Inside) {
return true;
}
// 如果两端点都在外部,还需要检查是否穿过边界又回来
// 通过采样中间点来检测
if (!p1Inside && !p2Inside) {
int sampleCount = 10;
for (int i = 1; i < sampleCount; i++) {
double t = (double) i / sampleCount;
double midLon = p1.getLongitude() + t * (p2.getLongitude() - p1.getLongitude());
double midLat = p1.getLatitude() + t * (p2.getLatitude() - p1.getLatitude());
if (isPointInPolygon(midLon, midLat, polygon)) {
return true;
}
}
}
return false;
}
}
@@ -0,0 +1,233 @@
package com.central.device.sse.controller;
import com.alibaba.fastjson.JSON;
import com.central.common.context.LoginUserContextHolder;
import com.central.device.model.vo.BoatRealtimeVO;
import com.central.device.service.IBoatTrackService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* 无人船遥测数据SSE控制器
* 提供SSE端点供前端订阅无人船实时位置数据
*
* @author dzc
* @date 2026-01-05
*/
@Slf4j
@RestController
@RequestMapping("/sse/boat")
@Tag(name = "无人船遥测数据SSE接口")
@RequiredArgsConstructor
public class BoatTelemetrySseController {
private final IBoatTrackService boatTrackService;
/**
* 存储SSE连接
* key: connectionId, value: SseEmitter
*/
private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();
/**
* 订阅无人船遥测数据SSE连接
* 前端建立SSE连接后,会实时推送无人船位置、速度、电量等数据
*
* @param deviceSn 设备SN
* @param clientSessionId 客户端会话ID(可选)
* @return SSE连接
*/
@Operation(summary = "订阅无人船遥测数据SSE连接")
@GetMapping(value = "/telemetry/{deviceSn}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public ResponseEntity<SseEmitter> subscribeBoatTelemetry(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn,
@Parameter(description = "客户端会话ID(可选)")
@RequestHeader(value = "X-Client-Session-Id", required = false) String clientSessionId) {
String tenantId = LoginUserContextHolder.getCurrentTenantId() != null
? LoginUserContextHolder.getCurrentTenantId() : "1";
String username = LoginUserContextHolder.getUser() != null
? LoginUserContextHolder.getUser().getUsername() : "anonymous";
// 生成connectionId
String connectionId;
if (clientSessionId != null && !clientSessionId.trim().isEmpty()) {
connectionId = "boat_" + clientSessionId + "_" + deviceSn;
log.info("客户端订阅无人船遥测SSE(复用会话): connectionId={}, deviceSn={}, tenant={}, user={}",
connectionId, deviceSn, tenantId, username);
} else {
connectionId = "boat_" + UUID.randomUUID().toString() + "_" + deviceSn;
log.info("客户端订阅无人船遥测SSE(新会话): connectionId={}, deviceSn={}, tenant={}, user={}",
connectionId, deviceSn, tenantId, username);
}
// 如果已存在相同连接,先移除
if (emitters.containsKey(connectionId)) {
removeConnection(connectionId, deviceSn);
}
// 创建SSE连接 (30分钟超时)
SseEmitter emitter = new SseEmitter(30 * 60 * 1000L);
// 配置回调
emitter.onCompletion(() -> {
log.info("无人船SSE连接完成: connectionId={}", connectionId);
removeConnection(connectionId, deviceSn);
});
emitter.onTimeout(() -> {
log.info("无人船SSE连接超时: connectionId={}", connectionId);
removeConnection(connectionId, deviceSn);
});
emitter.onError(e -> {
log.warn("无人船SSE连接错误: connectionId={}, error={}", connectionId, e.getMessage());
removeConnection(connectionId, deviceSn);
});
// 存储连接
emitters.put(connectionId, emitter);
// 注册遥测数据回调
boatTrackService.registerTelemetryCallback(deviceSn, connectionId, data -> {
sendTelemetryData(connectionId, data);
});
// 发送初始连接成功事件
try {
emitter.send(SseEmitter.event()
.name("connected")
.data("{\"status\":\"connected\",\"deviceSn\":\"" + deviceSn + "\"}"));
} catch (IOException e) {
log.error("发送初始连接事件失败: connectionId={}", connectionId, e);
}
// 发送当前实时位置(如果有)
BoatRealtimeVO realtime = boatTrackService.getRealtimePosition(deviceSn);
if (realtime != null) {
sendTelemetryData(connectionId, realtime);
}
return ResponseEntity.ok()
.header("Cache-Control", "no-cache, no-transform")
.header("Connection", "keep-alive")
.header("X-Accel-Buffering", "no")
.contentType(MediaType.TEXT_EVENT_STREAM)
.body(emitter);
}
/**
* 主动断开无人船遥测SSE连接
*
* @param deviceSn 设备SN
* @param clientSessionId 客户端会话ID
* @return 断开结果
*/
@Operation(summary = "主动断开无人船遥测SSE连接")
@DeleteMapping("/telemetry/{deviceSn}")
public ResponseEntity<String> disconnectBoatTelemetry(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn,
@Parameter(description = "客户端会话ID", required = true)
@RequestHeader(value = "X-Client-Session-Id") String clientSessionId) {
String connectionId = "boat_" + clientSessionId + "_" + deviceSn;
log.info("客户端主动断开无人船遥测SSE连接: connectionId={}, deviceSn={}", connectionId, deviceSn);
boolean success = removeConnection(connectionId, deviceSn);
if (success) {
return ResponseEntity.ok("连接已断开");
} else {
return ResponseEntity.ok("连接不存在或已断开");
}
}
/**
* Beacon方式断开无人船遥测SSE连接
* 用于浏览器刷新/关闭时
*
* @param deviceSn 设备SN
* @param body 包含sessionId的请求体
* @return 断开结果
*/
@Operation(summary = "Beacon方式断开无人船遥测SSE连接")
@PostMapping("/telemetry/{deviceSn}/disconnect")
public ResponseEntity<String> disconnectBoatTelemetryByBeacon(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn,
@RequestBody(required = false) Map<String, String> body) {
String clientSessionId = body != null ? body.get("sessionId") : null;
if (clientSessionId == null || clientSessionId.trim().isEmpty()) {
log.warn("Beacon断开无人船SSE请求缺少sessionId: deviceSn={}", deviceSn);
return ResponseEntity.badRequest().body("缺少sessionId");
}
String connectionId = "boat_" + clientSessionId + "_" + deviceSn;
log.info("Beacon方式断开无人船遥测SSE连接: connectionId={}, deviceSn={}", connectionId, deviceSn);
boolean success = removeConnection(connectionId, deviceSn);
if (success) {
return ResponseEntity.ok("连接已断开");
} else {
return ResponseEntity.ok("连接不存在或已断开");
}
}
// ========== 私有方法 ==========
/**
* 发送遥测数据到指定连接
*/
private void sendTelemetryData(String connectionId, BoatRealtimeVO data) {
SseEmitter emitter = emitters.get(connectionId);
if (emitter == null) {
return;
}
try {
emitter.send(SseEmitter.event()
.name("boat-telemetry")
.data(JSON.toJSONString(data)));
} catch (IOException e) {
log.warn("发送遥测数据失败: connectionId={}, error={}", connectionId, e.getMessage());
// 发送失败时移除连接
String deviceSn = data.getDeviceSn();
removeConnection(connectionId, deviceSn);
}
}
/**
* 移除连接并清理资源
*/
private boolean removeConnection(String connectionId, String deviceSn) {
SseEmitter emitter = emitters.remove(connectionId);
if (emitter != null) {
try {
emitter.complete();
} catch (Exception e) {
// 忽略
}
}
// 注销遥测回调
boatTrackService.unregisterTelemetryCallback(deviceSn, connectionId);
return emitter != null;
}
}
@@ -1,6 +1,11 @@
spring:
application:
name: device-center
servlet:
multipart:
enabled: true # 开启文件上传功能(默认开启,可省略)
max-file-size: 10MB # 单个文件的最大允许大小(可自定义,如50MB、1GB)
max-request-size: 50MB # 单次请求中所有文件的总最大允许大小(需大于等于max-file-size)
# cloud:
# nacos:
# discovery:
@@ -0,0 +1,813 @@
# 无人船航线规划和水域边界管理功能 - 实施方案
> **文档版本**: v1.0
> **创建时间**: 2026-01-06
> **最后更新**: 2026-01-06
> **状态**: ✅ 已完成
---
## 📊 实施进度总览
| Phase | 任务 | 状态 | 完成时间 |
|-------|------|------|---------|
| Phase 1.1 | 创建 useCesiumRouteRenderer Hook | ✅ 已完成 | 2026-01-06 |
| Phase 1.2 | 修改 RouteEditor/index.tsx 集成Hook | ✅ 已完成 | 2026-01-06 |
| Phase 2.1-2.6 | BoundaryEditor 组件完整实现 | ✅ 已完成 | 2026-01-06 |
| Phase 3.1-3.3 | LayerPanel 图层管理面板 | ✅ 已完成 | 2026-01-06 |
| Phase 4.1-4.2 | 实时轨迹显示功能 | ✅ 已完成 | 2026-01-06 |
**整体进度**: 100% (5/5 Phase 全部完成) 🎉
---
## 一、需求分析
### 用户提出的4个核心需求
1. ✅ 在3D模型上标绘水域边界并保存到后台
2. ✅ 在3D模型上规划航线,判断航线是否超出水域边界
3. ✅ 保存规划好的航线并能在模型上显示
4. ✅ **第一视角预览航线执行过程** (已实现完成)
### 用户确认的交互方式
- **航线显示**: 仅在RouteEditor编辑时显示(打开时在Cesium上渲染,关闭后隐藏)
- **边界标绘**: 独立的BoundaryEditor全屏弹窗组件
- **数据加载**: 按需手动加载(通过LayerPanel图层管理面板勾选)
- **实时轨迹**: 用户手动启用(添加"实时跟踪"按钮)
## 二、现状评估
### 已实现功能(约85%)
#### 后端完成度
- ✅ WaterBoundaryController - 完整CRUD + 射线法边界检测算法
- ✅ BoatRouteController - 完整CRUD + 航线校验 + 模板管理
- ✅ BoatTrackServiceImpl - 实时/历史/任务轨迹 + SSE回调机制
- ✅ BoatTelemetrySseController - SSE推送端点
- ⚠️ BoatControlServiceImpl - Mock实现(待对接实际设备)
#### 前端完成度
- ✅ RouteEditor组件 - 航线编辑逻辑完整(useRouteDrawing + useRouteValidation Hooks)
- ✅ **第一视角预览** - 已完整实现(`RouteEditor/index.tsx` 第77-209行)
- ✅ CesiumContainer - 3D地球渲染 + 设备标记 + 无人机实时位置示例
- ✅ useBoatSSE Hook - SSE订阅 + 自动重连 + 心跳检测
### 缺失功能(约15%)
#### 核心缺失项
1. ❌ **RouteEditor中的Cesium航线渲染** - 航点marker + polyline + 拖动交互
2. ❌ **BoundaryEditor组件** - 完全缺失,需从零创建
3. ❌ **LayerPanel图层管理面板** - 航线/边界列表 + 勾选显示/隐藏
4. ❌ **实时轨迹Cesium渲染** - 无人船marker + 轨迹polyline
## 三、技术选型
### Cesium渲染方案:Entity API
**选择理由**:
- 与现有设备marker渲染保持一致
- 内置拾取(pick)支持,易于实现拖动交互
- 航点数量 < 100,性能足够
- 代码简洁,易于维护
### 颜色编码规范
**航点颜色**:
- 正常航点: CYAN(青色,#00ffff)
- 选中航点: YELLOW(黄色,放大到18px)
- 起点: GREEN(绿色)
- 终点: RED(红色)
- 超出边界: ORANGE(橙色) + ⚠警告图标
**边界类型颜色**:
- navigable(可通行): 绿色 #00ff00 + 透明度0.2
- forbidden(禁行): 红色 #ff0000 + 透明度0.3
- warning(警告): 黄色 #ffff00 + 透明度0.2
## 四、详细实施步骤
---
### ✅ Phase 1: RouteEditor Cesium集成 ⭐ P0核心(已完成)
**状态**: ✅ 已完成
**完成时间**: 2026-01-06
**目标**: 让航线在3D地图上可见并支持交互式编辑
#### 1.1 创建 `useCesiumRouteRenderer` Hook ✅
**状态**: ✅ 已完成
**文件**: `zlt-web/yingyan/src/pages/map3d/components/RouteEditor/hooks/useCesiumRouteRenderer.ts`
**已实现功能**:
- ✅ Entity管理(使用Set记录所有Entity ID)
- ✅ 航点Marker渲染(带编号、颜色编码、可拖动)
- ✅ 航线Polyline渲染(发光效果、贴地)
- ✅ 拖动交互实现(requestAnimationFrame节流优化)
- ✅ 点击地图添加航点
- ✅ 边界检测预留接口
- ✅ 相机聚焦策略
- ✅ 内存泄漏防范(组件卸载清理)
#### 1.2 修改 `RouteEditor/index.tsx` 集成Hook ✅
**状态**: ✅ 已完成
**文件**: `zlt-web/yingyan/src/pages/map3d/components/RouteEditor/index.tsx`
**修改内容**:
- ✅ 导入useCesiumRouteRenderer Hook
- ✅ 在组件中调用Hook并传入所有必要参数
- ✅ 复用现有的handleMapClick、moveWaypoint、handleWaypointSelect回调
---
```typescript
interface UseCesiumRouteRendererOptions {
viewerRef: React.RefObject<any>;
waypoints: BoatWaypointDTO[];
selectedIndex: number | null;
mode: EditorMode; // 'view' | 'draw' | 'select' | 'edit'
boundaryGeoJson?: string; // 用于边界检测
onWaypointAdd: (point: { longitude: number; latitude: number }) => void;
onWaypointMove: (index: number, point: { longitude: number; latitude: number }) => void;
onWaypointSelect: (index: number) => void;
}
```
**实现要点**:
1. **Entity管理**:
- 用 `entityIdsRef: Set<string>` 记录所有创建的Entity ID
- 清理时遍历删除,避免内存泄漏
2. **航点Marker渲染**:
```typescript
viewer.entities.add({
id: `route-waypoint-${index}`,
position: Cesium.Cartesian3.fromDegrees(lon, lat, 0),
point: {
pixelSize: 14,
color: Cesium.Color.CYAN,
outlineColor: Cesium.Color.WHITE,
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
label: {
text: `${index + 1}`,
font: '12px sans-serif',
fillColor: Cesium.Color.WHITE,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -18),
},
properties: {
type: 'route-waypoint',
waypointIndex: index,
draggable: true,
}
});
```
3. **航线Polyline渲染**:
```typescript
viewer.entities.add({
id: 'route-path',
polyline: {
positions: waypointPositions, // Cartesian3[]
width: 4,
material: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.3,
color: Cesium.Color.CYAN,
}),
clampToGround: true,
}
});
```
4. **拖动交互实现**:
```typescript
const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
// LEFT_DOWN: 开始拖拽
handler.setInputAction((movement) => {
const pickedObject = viewer.scene.pick(movement.position);
if (pickedObject?.id?.properties?.draggable?.getValue()) {
viewer.scene.screenSpaceCameraController.enableRotate = false; // 禁用旋转
draggingEntity = pickedObject.id;
}
}, Cesium.ScreenSpaceEventType.LEFT_DOWN);
// MOUSE_MOVE: 拖拽中(使用requestAnimationFrame节流)
let rafId: number | null = null;
handler.setInputAction((movement) => {
if (draggingEntity && !rafId) {
rafId = requestAnimationFrame(() => {
const ray = viewer.camera.getPickRay(movement.endPosition);
const cartesian = viewer.scene.globe.pick(ray, viewer.scene);
if (cartesian) {
draggingEntity.position = cartesian;
const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
onWaypointMove(index, {
longitude: Cesium.Math.toDegrees(cartographic.longitude),
latitude: Cesium.Math.toDegrees(cartographic.latitude),
});
}
rafId = null;
});
}
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
// LEFT_UP: 结束拖拽
handler.setInputAction(() => {
if (draggingEntity) {
viewer.scene.screenSpaceCameraController.enableRotate = true;
draggingEntity = null;
}
}, Cesium.ScreenSpaceEventType.LEFT_UP);
```
5. **边界检测**(可选增强):
- 若传入 `boundaryGeoJson`,使用射线法检测航点是否在边界内
- 超出边界的航点标记为橙色
6. **相机聚焦策略**:
```typescript
// 组件挂载时飞到航线中心
useEffect(() => {
if (!viewerRef?.current || !waypoints.length) return;
const bounds = calculateBounds(waypoints);
viewerRef.current.camera.flyTo({
destination: Cesium.Rectangle.fromDegrees(
bounds.west, bounds.south, bounds.east, bounds.north
),
duration: 1.0,
});
}, []); // 只执行一次
```
#### 1.2 修改 `RouteEditor/index.tsx` 集成Hook ⏸️
**状态**: ⏸️ 待开始
**文件**: `zlt-web/yingyan/src/pages/map3d/components/RouteEditor/index.tsx`
**修改内容**(约15行):
```typescript
import { useCesiumRouteRenderer } from './hooks/useCesiumRouteRenderer';
const RouteEditor: React.FC<RouteEditorProps> = ({ viewerRef, ... }) => {
// ...现有逻辑...
// 集成Cesium渲染Hook
useCesiumRouteRenderer({
viewerRef,
waypoints,
selectedIndex: editorState.selectedWaypointIndex,
mode: editorState.mode,
boundaryGeoJson: boundaryData?.geoJson, // 可选
onWaypointAdd: handleMapClick,
onWaypointMove: moveWaypoint,
onWaypointSelect: handleWaypointSelect,
});
// UI保持不变
};
```
#### 1.3 处理事件冲突
**问题**: 绘制模式点击地图会触发旋转
**解决方案**:
```typescript
if (mode === 'draw') {
viewer.screenSpaceEventHandler.removeInputAction(LEFT_DOUBLE_CLICK);
viewer.scene.screenSpaceEventController.enableRotate = false;
} else {
viewer.scene.screenSpaceEventController.enableRotate = true;
}
```
---
### ✅ Phase 2: BoundaryEditor创建 ⭐ P0核心(已完成)
**状态**: ✅ 已完成
**完成时间**: 2026-01-06
**目标**: 实现水域边界的绘制、编辑、保存和显示
#### 2.1 文件结构
```
BoundaryEditor/
├── index.tsx # 主组件(全屏弹窗)
├── index.less # 样式(复用RouteEditor样式)
├── types.ts # 类型定义
├── BoundaryToolbar.tsx # 工具栏(绘制/保存/取消)
├── BoundaryPreview.tsx # 预览面板(顶点数量、面积等)
└── hooks/
├── useBoundaryDrawing.ts # 边界绘制逻辑
└── useCesiumBoundaryRenderer.ts # Cesium Polygon渲染
```
**位置**: `zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/`
#### 2.2 创建主组件 `BoundaryEditor/index.tsx` ✅
**状态**: ✅ 已完成
**参考**: `RouteEditor/index.tsx` 的结构
**核心状态**:
```typescript
const [vertices, setVertices] = useState<Array<{lon, lat}>>([]);
const [isDrawing, setIsDrawing] = useState(false);
const [boundaryType, setBoundaryType] = useState<'navigable' | 'obstacle' | 'restricted'>('navigable');
const [saveModalVisible, setSaveModalVisible] = useState(false);
```
**交互流程**:
1. 点击"开始绘制"按钮 → 进入绘制模式
2. 点击地图添加顶点 → 实时渲染多边形
3. 双击或按Enter → 结束绘制(自动闭合)
4. 填写边界信息(名称、类型)→ 保存到后台
#### 2.3 创建 `useBoundaryDrawing` Hook ✅
**状态**: ✅ 已完成
**文件**: `BoundaryEditor/hooks/useBoundaryDrawing.ts`
```typescript
export function useBoundaryDrawing() {
const [vertices, setVertices] = useState<Array<{lon, lat}>>([]);
const [isDrawing, setIsDrawing] = useState(false);
const startDrawing = () => {
setIsDrawing(true);
setVertices([]);
};
const finishDrawing = () => {
if (vertices.length >= 3) {
setIsDrawing(false);
} else {
message.warning('至少需要3个顶点才能形成边界');
}
};
const addVertex = (point: {longitude, latitude}) => {
setVertices(prev => [...prev, { lon: point.longitude, lat: point.latitude }]);
};
const updateVertex = (index: number, point: {lon, lat}) => { /*...*/ };
const deleteVertex = (index: number) => { /*...*/ };
const clearVertices = () => { setVertices([]); setIsDrawing(false); };
return { vertices, isDrawing, startDrawing, finishDrawing, addVertex, ... };
}
```
#### 2.4 创建 `useCesiumBoundaryRenderer` Hook ✅
**状态**: ✅ 已完成
**文件**: `BoundaryEditor/hooks/useCesiumBoundaryRenderer.ts`
**Polygon渲染**:
```typescript
viewer.entities.add({
id: `boundary-polygon`,
polygon: {
hierarchy: new Cesium.PolygonHierarchy(
vertices.map(v => Cesium.Cartesian3.fromDegrees(v.lon, v.lat, 0))
),
material: Cesium.Color.fromCssColorString(
boundaryType === 'navigable' ? '#00ff00' :
boundaryType === 'forbidden' ? '#ff0000' : '#ffff00'
).withAlpha(0.2),
outline: true,
outlineColor: Cesium.Color.LIME,
outlineWidth: 3,
classificationType: Cesium.ClassificationType.BOTH,
}
});
```
**顶点Marker**(可拖动):
```typescript
vertices.forEach((v, i) => {
viewer.entities.add({
id: `boundary-vertex-${i}`,
position: Cesium.Cartesian3.fromDegrees(v.lon, v.lat, 0),
point: {
pixelSize: 10,
color: Cesium.Color.WHITE,
outlineColor: Cesium.Color.BLACK,
outlineWidth: 2,
},
label: { text: `${i + 1}` },
properties: { type: 'boundary-vertex', vertexIndex: i, draggable: true },
});
});
```
#### 2.5 集成到 `CesiumContainer.tsx` ✅
**状态**: ✅ 已完成
**文件**: `zlt-web/yingyan/src/pages/map3d/components/MapContainer/CesiumContainer.tsx`
**修改内容**(约30行):
```typescript
// 新增状态
const [boundaryEditorVisible, setBoundaryEditorVisible] = useState(false);
// 在handleOpenRoutePlanning附近添加
const handleOpenBoundaryEditor = useCallback((device: any) => {
setBoundaryEditorVisible(true);
setRightPanelVisible(false);
}, []);
// 渲染(在RouteEditor之后)
{boundaryEditorVisible && (
<div style={{
position: 'fixed',
top: 0, left: 0, right: 0, bottom: 0,
zIndex: 1000,
background: 'rgba(0, 0, 0, 0.5)',
}}>
<BoundaryEditor
scenicId={selectedDevice?.scenicId || 1}
onSaveSuccess={(id) => setBoundaryEditorVisible(false)}
onCancel={() => setBoundaryEditorVisible(false)}
viewerRef={viewerRef}
/>
</div>
)}
```
---
### ✅ Phase 3: LayerPanel图层管理 ⭐ P1重要(已完成)
**状态**: ✅ 已完成
**完成时间**: 2026-01-06
**目标**: 按需加载和显示已保存的航线/边界
#### 3.1 创建 `LayerPanel.tsx` ✅
**状态**: ✅ 已完成
**文件**: `zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.tsx`
**UI设计**:
```
┌─────────────────────────┐
│ 图层管理 │
├─────────────────────────┤
│ 📍 航线图层 │
│ ☑ 航线A (已发布) │
│ □ 航线B (草稿) │
│ │
│ 🔲 边界图层 │
│ ☑ 可通行区域1 │
│ □ 禁行区域2 │
│ │
│ 📡 实时轨迹 │
│ ☑ 显示无人船轨迹 │
└─────────────────────────┘
```
**核心功能**:
```typescript
const [visibleRoutes, setVisibleRoutes] = useState<Set<string>>(new Set());
const [visibleBoundaries, setVisibleBoundaries] = useState<Set<string>>(new Set());
const routeEntitiesRef = useRef<Map<string, string[]>>(new Map()); // routeId -> entityIds[]
const renderRoute = async (routeId: string) => {
const detail = await getBoatRouteDetail(routeId);
const entityIds: string[] = [];
// 渲染航点
detail.waypoints.forEach((wp, i) => {
const entity = viewer.entities.add({
id: `layer-route-${routeId}-wp-${i}`,
position: Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0),
point: { pixelSize: 8, color: Cesium.Color.CYAN.withAlpha(0.7) },
label: { text: `${i + 1}`, font: '10px' },
});
entityIds.push(entity.id);
});
// 渲染polyline
const polyline = viewer.entities.add({
id: `layer-route-${routeId}-path`,
polyline: {
positions: detail.waypoints.map(wp =>
Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0)
),
width: 3,
material: Cesium.Color.CYAN.withAlpha(0.6),
}
});
entityIds.push(polyline.id);
routeEntitiesRef.current.set(routeId, entityIds);
};
const removeRoute = (routeId: string) => {
const entityIds = routeEntitiesRef.current.get(routeId);
entityIds?.forEach(id => viewer.entities.removeById(id));
routeEntitiesRef.current.delete(routeId);
};
```
**性能优化**:
- 同时显示的航线限制在5条
- 航点 > 50时仅显示Polyline不显示Marker
#### 3.2 集成到 `CesiumContainer.tsx` ✅
**状态**: ✅ 已完成
**修改内容**(约15行):
```typescript
const [layerPanelVisible, setLayerPanelVisible] = useState(false);
// 在BottomPanel区域渲染
<LayerPanel
visible={layerPanelVisible}
onClose={() => setLayerPanelVisible(false)}
viewer={viewerRef.current}
Cesium={Cesium}
scenicId={selectedDevice?.scenicId}
/>
```
---
### ✅ Phase 4: 实时轨迹显示 ⭐ P1重要(已完成)
**状态**: ✅ 已完成
**完成时间**: 2026-01-06
**目标**: 在3D地图上实时显示无人船位置和轨迹
#### 4.1 创建 `useCesiumBoatTrack` Hook ✅
**状态**: ✅ 已完成
**文件**: `zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useCesiumBoatTrack.ts`
**参考**: `CesiumContainer.tsx` 第458-569行无人机实时渲染逻辑
```typescript
export function useCesiumBoatTrack({ viewerRef, enabled, deviceSn }) {
const { boatData, connectBoatSSE, disconnectBoatSSE } = useBoatSSE();
const boatEntityRef = useRef<any>(null);
const trackEntityRef = useRef<any>(null);
const trackPositionsRef = useRef<any[]>([]);
// 订阅SSE
useEffect(() => {
if (enabled && deviceSn) {
connectBoatSSE(deviceSn);
} else {
disconnectBoatSSE();
clearTrack();
}
return () => disconnectBoatSSE();
}, [enabled, deviceSn]);
// 渲染实时位置
useEffect(() => {
if (!boatData || !viewerRef?.current) return;
const position = Cesium.Cartesian3.fromDegrees(
boatData.longitude, boatData.latitude, 0
);
// 更新船位置marker
if (boatEntityRef.current) {
boatEntityRef.current.position = position;
boatEntityRef.current.label.text =
`船 H:${boatData.heading}° S:${boatData.speed}m/s B:${boatData.batteryPercent}%`;
} else {
boatEntityRef.current = viewer.entities.add({
position,
point: { pixelSize: 16, color: Cesium.Color.BLUE },
label: { text: `船 H:${boatData.heading}°...` },
});
}
// 添加到轨迹
trackPositionsRef.current.push(position);
// 更新轨迹polyline
if (trackPositionsRef.current.length >= 2) {
if (trackEntityRef.current) {
trackEntityRef.current.polyline.positions = [...trackPositionsRef.current];
} else {
trackEntityRef.current = viewer.entities.add({
polyline: {
positions: [...trackPositionsRef.current],
width: 4,
material: Cesium.Color.BLUE,
}
});
}
}
}, [boatData]);
const clearTrack = () => {
if (boatEntityRef.current) viewer.entities.remove(boatEntityRef.current);
if (trackEntityRef.current) viewer.entities.remove(trackEntityRef.current);
boatEntityRef.current = null;
trackEntityRef.current = null;
trackPositionsRef.current = [];
};
return { clearTrack };
}
```
#### 4.2 集成到 `BoatRouteTab.tsx` ✅
**状态**: ✅ 已完成
**文件**: `zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/BoatRouteTab.tsx`
**修改内容**(约60行):
```typescript
const [trackingEnabled, setTrackingEnabled] = useState(false);
useCesiumBoatTrack({
viewerRef,
enabled: trackingEnabled,
deviceSn: selectedDevice?.deviceSn,
});
// UI添加开关
<Switch
checked={trackingEnabled}
onChange={setTrackingEnabled}
checkedChildren="实时跟踪"
unCheckedChildren="关闭跟踪"
/>
```
---
## 五、技术难点和解决方案
### 5.1 拖拽性能优化
**问题**: MOUSE_MOVE高频触发(60fps)导致卡顿
**解决方案**: 使用requestAnimationFrame节流
```typescript
let rafId: number | null = null;
handler.setInputAction((movement) => {
if (draggingEntity && !rafId) {
rafId = requestAnimationFrame(() => {
// 更新位置逻辑
rafId = null;
});
}
}, MOUSE_MOVE);
```
### 5.2 事件冲突处理
**问题**: 绘制模式点击地图会触发旋转
**解决方案**:
```typescript
if (mode === 'draw') {
viewer.scene.screenSpaceEventController.enableRotate = false;
} else {
viewer.scene.screenSpaceEventController.enableRotate = true;
}
```
### 5.3 内存泄漏防范
**解决方案**: 严格管理Entity生命周期
```typescript
const entityIdsRef = useRef<Set<string>>(new Set());
const cleanup = () => {
entityIdsRef.current.forEach(id => viewer.entities.removeById(id));
entityIdsRef.current.clear();
};
useEffect(() => {
return () => cleanup(); // 组件卸载时清理
}, []);
```
---
## 六、关键文件清单
### 需要创建的新文件(11个)
#### Phase 1
1. ⏳ `zlt-web/yingyan/src/pages/map3d/components/RouteEditor/hooks/useCesiumRouteRenderer.ts` - 航线渲染核心Hook (~400行)
#### Phase 2
2. ⏸️ `zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/index.tsx` - 边界编辑器主组件 (~300行)
3. ⏸️ `zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/index.less` - 样式 (~50行)
4. ⏸️ `zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/types.ts` - 类型定义 (~80行)
5. ⏸️ `zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/BoundaryToolbar.tsx` - 工具栏 (~150行)
6. ⏸️ `zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/BoundaryPreview.tsx` - 预览面板 (~100行)
7. ⏸️ `zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/hooks/useBoundaryDrawing.ts` - 绘制逻辑 (~200行)
8. ⏸️ `zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/hooks/useCesiumBoundaryRenderer.ts` - Cesium渲染 (~350行)
#### Phase 3
9. ⏸️ `zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.tsx` - 图层管理 (~400行)
10. ⏸️ `zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.less` - 样式 (~80行)
#### Phase 4
11. ⏸️ `zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useCesiumBoatTrack.ts` - 实时轨迹Hook (~250行)
### 需要修改的现有文件(3个)
1. ⏸️ **`RouteEditor/index.tsx`** - 集成useCesiumRouteRenderer (+15行)
2. ⏸️ **`CesiumContainer.tsx`** - 集成BoundaryEditor和LayerPanel (+55行)
3. ⏸️ **`BoatRouteTab.tsx`** - 添加实时跟踪开关 (+10行)
---
## 七、实施时间表
| Phase | 任务 | 预计时间 | 优先级 | 状态 |
|-------|------|---------|--------|------|
| Phase 1 | RouteEditor Cesium集成 | 2-3天 | ⭐ P0核心 | ⏳ 进行中 |
| Phase 2 | BoundaryEditor创建 | 2-3天 | ⭐ P0核心 | ⏸️ 待开始 |
| Phase 3 | LayerPanel图层管理 | 2天 | ⭐ P1重要 | ⏸️ 待开始 |
| Phase 4 | 实时轨迹显示 | 1天 | ⭐ P1重要 | ⏸️ 待开始 |
| **总计** | | **7-9天** | | |
### 里程碑
- **Day 3**: Phase 1完成,RouteEditor可在Cesium上绘制和编辑航线
- **Day 6**: Phase 2完成,BoundaryEditor可标绘水域边界
- **Day 8**: Phase 3完成,LayerPanel可管理图层显示
- **Day 9**: Phase 4完成,全部功能交付
---
## 八、验收标准
### Phase 1验收 ✅
- [x] 打开RouteEditor后,航线在Cesium上正确显示
- [x] 点击地图可添加航点,航点带编号
- [x] 拖动航点可更新位置,航线实时更新
- [ ] 航线超出边界时航点显示为橙色(边界检测接口已预留)
- [x] 关闭RouteEditor后航线从地图消失
### Phase 2验收 ✅
- [x] 打开BoundaryEditor后可点击地图绘制多边形
- [x] 双击或Enter结束绘制并自动闭合
- [x] 不同边界类型显示不同颜色
- [x] 保存边界成功后调用后端API并返回ID
- [x] 可拖动顶点调整边界形状
### Phase 3验收 ✅
- [x] LayerPanel显示已保存的航线和边界列表
- [x] 勾选航线后在地图上正确渲染
- [x] 取消勾选后从地图移除
- [x] 同时显示多条航线时性能正常(限制5条)
### Phase 4验收 ✅
- [x] 开启实时跟踪后订阅SSE并显示无人船位置
- [x] 实时更新船位置marker和轨迹polyline
- [x] 显示航向、速度、电量等信息
- [x] 关闭跟踪后断开SSE并清除图层
---
## 九、后续扩展(可选)
1. **航线智能优化** - 基于水流、风力等因素优化航线
2. **多无人船协同** - 多设备航线冲突检测
3. **3D模型自动识别水域边界** - AI算法识别(接口已预留)
4. **航线导入导出** - 支持KML/KMZ等标准格式
5. **障碍物智能规避** - 集成3D模型碰撞检测
---
## 📝 更新日志
| 日期 | 更新内容 | 更新人 |
|------|---------|-------|
| 2026-01-06 | 创建实施方案文档 | Claude |
| 2026-01-06 | ✅ Phase 1.1 完成 - 创建useCesiumRouteRenderer Hook (420行) | Claude |
| 2026-01-06 | ✅ Phase 1.2 完成 - RouteEditor集成Cesium渲染 | Claude |
| 2026-01-06 | ✅ Phase 1 完成 - RouteEditor Cesium集成功能完成 | Claude |
| 2026-01-06 | ✅ Phase 2.1 完成 - 创建types.ts类型定义 (90行) | Claude |
| 2026-01-06 | ✅ Phase 2.2 完成 - 创建useBoundaryDrawing Hook (270行) | Claude |
| 2026-01-06 | ✅ Phase 2.3 完成 - 创建useCesiumBoundaryRenderer Hook (390行) | Claude |
| 2026-01-06 | ✅ Phase 2.4 完成 - 创建BoundaryToolbar和BoundaryPreview组件 | Claude |
| 2026-01-06 | ✅ Phase 2.5 完成 - 创建BoundaryEditor主组件和样式 | Claude |
| 2026-01-06 | ✅ Phase 2.6 完成 - 集成BoundaryEditor到CesiumContainer | Claude |
| 2026-01-06 | ✅ Phase 2 完成 - 水域边界编辑功能全部实现 | Claude |
| 2026-01-06 | ✅ Phase 3.1 完成 - 创建LayerPanel主组件 (520行) | Claude |
| 2026-01-06 | ✅ Phase 3.2 完成 - 创建LayerPanel样式文件 (160行) | Claude |
| 2026-01-06 | ✅ Phase 3.3 完成 - 集成LayerPanel到CesiumContainer | Claude |
| 2026-01-06 | ✅ Phase 3 完成 - 图层管理功能全部实现 | Claude |
| 2026-01-06 | ✅ Phase 4.1 完成 - 创建useCesiumBoatTrack Hook (280行) | Claude |
| 2026-01-06 | ✅ Phase 4.2 完成 - 集成到BoatRouteTab,添加实时跟踪开关 | Claude |
| 2026-01-06 | ✅ Phase 4 完成 - 实时轨迹显示功能全部实现 | Claude |
| 2026-01-06 | 🎉 **项目完成** - 无人船航线规划和水域边界管理功能全部实现 | Claude |
@@ -0,0 +1,111 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.central.device.mapper.BoatRouteMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.central.device.entity.BoatRoute">
<id column="id" property="id" />
<result column="route_id" property="routeId" />
<result column="route_name" property="routeName" />
<result column="device_sn" property="deviceSn" />
<result column="device_name" property="deviceName" />
<result column="scenic_id" property="scenicId" />
<result column="tenant_id" property="tenantId" />
<result column="waypoint_count" property="waypointCount" />
<result column="total_distance" property="totalDistance" />
<result column="total_duration" property="totalDuration" />
<result column="cruise_speed" property="cruiseSpeed" />
<result column="boundary_polygon" property="boundaryPolygon" />
<result column="start_point" property="startPoint" />
<result column="end_point" property="endPoint" />
<result column="loop_enabled" property="loopEnabled" />
<result column="loop_count" property="loopCount" />
<result column="return_mode" property="returnMode" />
<result column="safe_distance" property="safeDistance" />
<result column="status" property="status" />
<result column="is_template" property="isTemplate" />
<result column="remark" property="remark" />
<result column="create_time" property="createTime" />
<result column="update_time" property="updateTime" />
<result column="create_by" property="createBy" />
<result column="deleted" property="deleted" />
</resultMap>
<!-- 根据航线ID查询 -->
<select id="selectByRouteId" resultMap="BaseResultMap">
SELECT * FROM boat_route
WHERE route_id = #{routeId}
AND deleted = 0
</select>
<!-- 根据设备SN查询绑定的航线列表 -->
<select id="selectByDeviceSn" resultMap="BaseResultMap">
SELECT * FROM boat_route
WHERE device_sn = #{deviceSn}
AND deleted = 0
ORDER BY create_time DESC
</select>
<!-- 根据景区ID查询航线列表 -->
<select id="selectByScenicId" resultMap="BaseResultMap">
SELECT * FROM boat_route
WHERE scenic_id = #{scenicId}
AND tenant_id = #{tenantId}
AND deleted = 0
ORDER BY create_time DESC
</select>
<!-- 查询模板列表 -->
<select id="selectTemplates" resultMap="BaseResultMap">
SELECT * FROM boat_route
WHERE is_template = 1
AND tenant_id = #{tenantId}
AND deleted = 0
ORDER BY create_time DESC
</select>
<!-- 更新航线状态 -->
<update id="updateStatus">
UPDATE boat_route
SET status = #{status},
update_time = NOW()
WHERE route_id = #{routeId}
</update>
<!-- 更新航线统计信息 -->
<update id="updateRouteStats">
UPDATE boat_route
SET waypoint_count = #{waypointCount},
total_distance = #{totalDistance},
total_duration = #{totalDuration},
update_time = NOW()
WHERE route_id = #{routeId}
</update>
<!-- 绑定航线到设备 -->
<update id="bindToDevice">
UPDATE boat_route
SET device_sn = #{deviceSn},
device_name = #{deviceName},
update_time = NOW()
WHERE route_id = #{routeId}
</update>
<!-- 解绑航线和设备 -->
<update id="unbindDevice">
UPDATE boat_route
SET device_sn = NULL,
device_name = NULL,
update_time = NOW()
WHERE route_id = #{routeId}
</update>
<!-- 设置为模板 -->
<update id="setTemplate">
UPDATE boat_route
SET is_template = #{isTemplate},
update_time = NOW()
WHERE route_id = #{routeId}
</update>
</mapper>
@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.central.device.mapper.BoatTrackMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.central.device.entity.BoatTrack">
<id column="id" property="id" />
<result column="device_sn" property="deviceSn" />
<result column="route_id" property="routeId" />
<result column="task_id" property="taskId" />
<result column="longitude" property="longitude" />
<result column="latitude" property="latitude" />
<result column="speed" property="speed" />
<result column="heading" property="heading" />
<result column="battery_percent" property="batteryPercent" />
<result column="deviation_distance" property="deviationDistance" />
<result column="is_deviation" property="isDeviation" />
<result column="nearest_waypoint_index" property="nearestWaypointIndex" />
<result column="record_time" property="recordTime" />
<result column="create_time" property="createTime" />
</resultMap>
<!-- 查询设备最新位置 -->
<select id="selectLatestByDeviceSn" resultMap="BaseResultMap">
SELECT * FROM boat_track
WHERE device_sn = #{deviceSn}
ORDER BY record_time DESC
LIMIT 1
</select>
<!-- 查询设备历史轨迹 -->
<select id="selectHistoryTrack" resultMap="BaseResultMap">
SELECT * FROM boat_track
WHERE device_sn = #{deviceSn}
AND record_time BETWEEN #{startTime} AND #{endTime}
ORDER BY record_time ASC
</select>
<!-- 查询任务轨迹 -->
<select id="selectByTaskId" resultMap="BaseResultMap">
SELECT * FROM boat_track
WHERE task_id = #{taskId}
ORDER BY record_time ASC
</select>
<!-- 查询航线执行轨迹 -->
<select id="selectByRouteIdAndTaskId" resultMap="BaseResultMap">
SELECT * FROM boat_track
WHERE route_id = #{routeId}
AND task_id = #{taskId}
ORDER BY record_time ASC
</select>
<!-- 批量插入轨迹点 -->
<insert id="batchInsert">
INSERT INTO boat_track (
device_sn, route_id, task_id,
longitude, latitude, speed, heading,
battery_percent, deviation_distance, is_deviation,
nearest_waypoint_index, record_time, create_time
) VALUES
<foreach collection="list" item="item" separator=",">
(
#{item.deviceSn}, #{item.routeId}, #{item.taskId},
#{item.longitude}, #{item.latitude}, #{item.speed}, #{item.heading},
#{item.batteryPercent}, #{item.deviationDistance}, #{item.isDeviation},
#{item.nearestWaypointIndex}, #{item.recordTime}, NOW()
)
</foreach>
</insert>
<!-- 删除指定时间之前的轨迹数据 -->
<delete id="deleteBeforeTime">
DELETE FROM boat_track
WHERE record_time &lt; #{beforeTime}
</delete>
</mapper>
@@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.central.device.mapper.BoatWaypointMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.central.device.entity.BoatWaypoint">
<id column="id" property="id" />
<result column="waypoint_id" property="waypointId" />
<result column="route_id" property="routeId" />
<result column="waypoint_index" property="waypointIndex" />
<result column="longitude" property="longitude" />
<result column="latitude" property="latitude" />
<result column="speed" property="speed" />
<result column="stay_duration" property="stayDuration" />
<result column="heading_angle" property="headingAngle" />
<result column="turn_mode" property="turnMode" />
<result column="actions" property="actions" typeHandler="com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler" />
<result column="is_key_point" property="isKeyPoint" />
<result column="point_name" property="pointName" />
<result column="remark" property="remark" />
<result column="create_time" property="createTime" />
<result column="update_time" property="updateTime" />
</resultMap>
<!-- 根据航线ID查询航点列表(按序号排序) -->
<select id="selectByRouteIdOrderByIndex" resultMap="BaseResultMap">
SELECT * FROM boat_waypoint
WHERE route_id = #{routeId}
ORDER BY waypoint_index ASC
</select>
<!-- 根据航线ID删除航点 -->
<delete id="deleteByRouteId">
DELETE FROM boat_waypoint
WHERE route_id = #{routeId}
</delete>
<!-- 批量插入航点 -->
<insert id="batchInsert">
INSERT INTO boat_waypoint (
waypoint_id, route_id, waypoint_index,
longitude, latitude, speed, stay_duration,
heading_angle, turn_mode, actions,
is_key_point, point_name, remark,
create_time, update_time
) VALUES
<foreach collection="list" item="item" separator=",">
(
#{item.waypointId}, #{item.routeId}, #{item.waypointIndex},
#{item.longitude}, #{item.latitude}, #{item.speed}, #{item.stayDuration},
#{item.headingAngle}, #{item.turnMode},
#{item.actions, typeHandler=com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler},
#{item.isKeyPoint}, #{item.pointName}, #{item.remark},
NOW(), NOW()
)
</foreach>
</insert>
<!-- 根据航线ID统计航点数量 -->
<select id="countByRouteId" resultType="int">
SELECT COUNT(*) FROM boat_waypoint
WHERE route_id = #{routeId}
</select>
<!-- 根据航点ID查询 -->
<select id="selectByWaypointId" resultMap="BaseResultMap">
SELECT * FROM boat_waypoint
WHERE waypoint_id = #{waypointId}
</select>
</mapper>
@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.central.device.mapper.WaterBoundaryMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.central.device.entity.WaterBoundary">
<id column="id" property="id" />
<result column="boundary_id" property="boundaryId" />
<result column="boundary_name" property="boundaryName" />
<result column="scenic_id" property="scenicId" />
<result column="tenant_id" property="tenantId" />
<result column="boundary_type" property="boundaryType" />
<result column="polygon_data" property="polygonData" />
<result column="center_point" property="centerPoint" />
<result column="area" property="area" />
<result column="source_type" property="sourceType" />
<result column="model_id" property="modelId" />
<result column="status" property="status" />
<result column="create_time" property="createTime" />
<result column="update_time" property="updateTime" />
<result column="deleted" property="deleted" />
</resultMap>
<!-- 根据边界ID查询 -->
<select id="selectByBoundaryId" resultMap="BaseResultMap">
SELECT * FROM water_boundary
WHERE boundary_id = #{boundaryId}
AND deleted = 0
</select>
<!-- 根据景区ID查询边界列表 -->
<select id="selectByScenicId" resultMap="BaseResultMap">
SELECT * FROM water_boundary
WHERE scenic_id = #{scenicId}
AND tenant_id = #{tenantId}
AND deleted = 0
AND status = 1
ORDER BY create_time DESC
</select>
<!-- 根据景区ID和边界类型查询 -->
<select id="selectByScenicIdAndType" resultMap="BaseResultMap">
SELECT * FROM water_boundary
WHERE scenic_id = #{scenicId}
AND boundary_type = #{boundaryType}
AND tenant_id = #{tenantId}
AND deleted = 0
AND status = 1
ORDER BY create_time DESC
</select>
<!-- 更新边界状态 -->
<update id="updateStatus">
UPDATE water_boundary
SET status = #{status},
update_time = NOW()
WHERE boundary_id = #{boundaryId}
</update>
<!-- 根据3D模型ID查询关联边界 -->
<select id="selectByModelId" resultMap="BaseResultMap">
SELECT * FROM water_boundary
WHERE model_id = #{modelId}
AND deleted = 0
ORDER BY create_time DESC
</select>
</mapper>
@@ -0,0 +1,153 @@
-- ====================================================================
-- 无人船航线规划相关数据表
-- 创建日期: 2026-01-05
-- 作者: dzc
-- ====================================================================
-- 1. 无人船航线表
CREATE TABLE IF NOT EXISTS `boat_route` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`route_id` varchar(64) NOT NULL COMMENT '航线唯一标识(UUID)',
`route_name` varchar(128) NOT NULL COMMENT '航线名称',
`device_sn` varchar(64) DEFAULT NULL COMMENT '绑定设备SN',
`device_name` varchar(128) DEFAULT NULL COMMENT '设备名称',
`scenic_id` bigint DEFAULT NULL COMMENT '所属景区ID',
`tenant_id` varchar(64) NOT NULL COMMENT '租户ID',
-- 航线统计信息
`waypoint_count` int DEFAULT 0 COMMENT '航点数量',
`total_distance` decimal(10,2) DEFAULT 0 COMMENT '总航程(米)',
`total_duration` int DEFAULT 0 COMMENT '预计时长(秒)',
`cruise_speed` decimal(5,2) DEFAULT 2.0 COMMENT '巡航速度(m/s)',
-- 航线边界
`boundary_polygon` text COMMENT '水域边界多边形(GeoJSON)',
`start_point` varchar(128) COMMENT '起点坐标(lng,lat)',
`end_point` varchar(128) COMMENT '终点坐标(lng,lat)',
-- 航线配置
`loop_enabled` tinyint DEFAULT 0 COMMENT '是否循环航行:0-否,1-是',
`loop_count` int DEFAULT 1 COMMENT '循环次数(-1无限循环)',
`return_mode` varchar(32) DEFAULT 'return_start' COMMENT '结束动作:return_start-返回起点,stay-原地停留',
`safe_distance` decimal(5,2) DEFAULT 5.0 COMMENT '安全距离(米)',
-- 状态字段
`status` tinyint DEFAULT 0 COMMENT '状态:0-草稿,1-已发布,2-执行中,3-已完成',
`is_template` tinyint DEFAULT 0 COMMENT '是否为模板:0-否,1-是',
`remark` varchar(512) DEFAULT NULL COMMENT '备注',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` varchar(64) DEFAULT NULL COMMENT '创建人',
`deleted` tinyint DEFAULT 0 COMMENT '删除标记',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_route_id` (`route_id`),
KEY `idx_device_sn` (`device_sn`),
KEY `idx_scenic_id` (`scenic_id`),
KEY `idx_tenant_id` (`tenant_id`),
KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='无人船航线表';
-- 2. 无人船航点表
CREATE TABLE IF NOT EXISTS `boat_waypoint` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`waypoint_id` varchar(64) NOT NULL COMMENT '航点唯一标识',
`route_id` varchar(64) NOT NULL COMMENT '关联航线ID',
`waypoint_index` int NOT NULL COMMENT '航点序号(从0开始)',
-- 位置信息
`longitude` decimal(12,8) NOT NULL COMMENT '经度',
`latitude` decimal(12,8) NOT NULL COMMENT '纬度',
-- 航行参数
`speed` decimal(5,2) DEFAULT NULL COMMENT '到达此点的速度(m/s),null使用航线默认',
`stay_duration` int DEFAULT 0 COMMENT '停留时长(秒)',
`heading_angle` decimal(5,2) DEFAULT NULL COMMENT '航向角(度,0-360,null自动计算)',
`turn_mode` varchar(32) DEFAULT 'smooth' COMMENT '转弯模式:smooth-平滑,sharp-急转',
-- 航点动作
`actions` json DEFAULT NULL COMMENT '航点动作配置(JSON数组)',
-- 标记
`is_key_point` tinyint DEFAULT 0 COMMENT '是否关键点:0-否,1-是',
`point_name` varchar(64) DEFAULT NULL COMMENT '航点名称',
`remark` varchar(256) DEFAULT NULL COMMENT '备注',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_waypoint_id` (`waypoint_id`),
KEY `idx_route_id` (`route_id`),
KEY `idx_route_index` (`route_id`, `waypoint_index`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='无人船航点表';
-- 3. 无人船轨迹表
CREATE TABLE IF NOT EXISTS `boat_track` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`device_sn` varchar(64) NOT NULL COMMENT '设备SN',
`route_id` varchar(64) DEFAULT NULL COMMENT '执行的航线ID',
`task_id` varchar(64) DEFAULT NULL COMMENT '任务ID(mission_code)',
-- 位置信息
`longitude` decimal(12,8) NOT NULL COMMENT '经度',
`latitude` decimal(12,8) NOT NULL COMMENT '纬度',
-- 航行状态
`speed` decimal(5,2) DEFAULT NULL COMMENT '当前速度(m/s)',
`heading` decimal(5,2) DEFAULT NULL COMMENT '航向角(度)',
`battery_percent` int DEFAULT NULL COMMENT '电池电量(%)',
-- 偏离检测
`deviation_distance` decimal(8,2) DEFAULT NULL COMMENT '偏离航线距离(米)',
`is_deviation` tinyint DEFAULT 0 COMMENT '是否偏离:0-否,1-是',
`nearest_waypoint_index` int DEFAULT NULL COMMENT '最近航点序号',
-- 时间戳
`record_time` datetime NOT NULL COMMENT '设备上报时间',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '入库时间',
PRIMARY KEY (`id`),
KEY `idx_device_sn` (`device_sn`),
KEY `idx_route_id` (`route_id`),
KEY `idx_task_id` (`task_id`),
KEY `idx_record_time` (`record_time`),
KEY `idx_device_time` (`device_sn`, `record_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='无人船轨迹表';
-- 4. 水域边界表
CREATE TABLE IF NOT EXISTS `water_boundary` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`boundary_id` varchar(64) NOT NULL COMMENT '边界唯一标识',
`boundary_name` varchar(128) NOT NULL COMMENT '边界名称',
`scenic_id` bigint NOT NULL COMMENT '所属景区ID',
`tenant_id` varchar(64) NOT NULL COMMENT '租户ID',
-- 边界数据
`boundary_type` varchar(32) DEFAULT 'navigable' COMMENT '边界类型:navigable-可航行,obstacle-障碍物,restricted-禁行区',
`polygon_data` text NOT NULL COMMENT '多边形坐标(GeoJSON)',
`center_point` varchar(128) COMMENT '中心点坐标',
`area` decimal(15,2) DEFAULT NULL COMMENT '面积(平方米)',
-- 来源
`source_type` varchar(32) DEFAULT 'manual' COMMENT '来源:manual-手动绘制,model-模型识别,import-导入',
`model_id` varchar(64) DEFAULT NULL COMMENT '关联3D模型ID',
`status` tinyint DEFAULT 1 COMMENT '状态:0-禁用,1-启用',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`deleted` tinyint DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_boundary_id` (`boundary_id`),
KEY `idx_scenic_id` (`scenic_id`),
KEY `idx_tenant_id` (`tenant_id`),
KEY `idx_boundary_type` (`boundary_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='水域边界表';
-- 5. 扩展missions表(order-center)
-- ALTER TABLE `missions`
-- ADD COLUMN `boat_route_id` varchar(64) DEFAULT NULL COMMENT '无人船航线ID' AFTER `wayline_name`,
-- ADD COLUMN `boat_route_name` varchar(128) DEFAULT NULL COMMENT '无人船航线名称' AFTER `boat_route_id`,
-- ADD INDEX `idx_boat_route_id` (`boat_route_id`);