diff --git a/.claude/settings.local.json b/.claude/settings.local.json index bda6201d..dc995866 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -66,7 +66,13 @@ "Bash(cmd /c move:*)", "Bash(set:*)", "Bash(copy \"F:\\\\project\\\\go-fly-platform-services\\\\zlt-web\\\\react-web-next\\\\src\\\\assets\\\\logo.png\" \"F:\\\\project\\\\go-fly-platform-services\\\\zlt-web\\\\yingyan\\\\src\\\\assets\\\\logo.png\")", - "Bash(cmd /c copy \"F:\\\\project\\\\go-fly-platform-services\\\\zlt-web\\\\react-web-next\\\\src\\\\assets\\\\logo.png\" \"F:\\\\project\\\\go-fly-platform-services\\\\zlt-web\\\\yingyan\\\\src\\\\assets\\\\logo.png\")" + "Bash(cmd /c copy \"F:\\\\project\\\\go-fly-platform-services\\\\zlt-web\\\\react-web-next\\\\src\\\\assets\\\\logo.png\" \"F:\\\\project\\\\go-fly-platform-services\\\\zlt-web\\\\yingyan\\\\src\\\\assets\\\\logo.png\")", + "Bash(xargs find)", + "Bash(for file in RouteToolbar.tsx RoutePreview.tsx WaypointEditor.tsx)", + "Bash(do if [ -f \"$file\" ])", + "Bash(else echo \"✗ $file NOT FOUND\")", + "Bash(fi)", + "Bash(done)" ], "deny": [], "ask": [] diff --git a/zlt-business/device-center/2.png b/zlt-business/device-center/2.png deleted file mode 100644 index 27da64dd..00000000 Binary files a/zlt-business/device-center/2.png and /dev/null differ diff --git a/zlt-business/device-center/3.png b/zlt-business/device-center/3.png deleted file mode 100644 index decb13ad..00000000 Binary files a/zlt-business/device-center/3.png and /dev/null differ diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/BoatCommandController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/BoatCommandController.java new file mode 100644 index 00000000..ffd8120a --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/BoatCommandController.java @@ -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 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 pause( + @Parameter(description = "设备SN") @RequestParam String deviceSn) { + boatControlService.pause(deviceSn); + return Result.succeed(null, "暂停指令已下发"); + } + + @Operation(summary = "恢复航行") + @PostMapping("/resume") + public Result resume( + @Parameter(description = "设备SN") @RequestParam String deviceSn) { + boatControlService.resume(deviceSn); + return Result.succeed(null, "恢复指令已下发"); + } + + @Operation(summary = "返回起点") + @PostMapping("/return") + public Result returnToStart( + @Parameter(description = "设备SN") @RequestParam String deviceSn) { + boatControlService.returnToStart(deviceSn); + return Result.succeed(null, "返航指令已下发"); + } + + @Operation(summary = "紧急停止") + @PostMapping("/emergency-stop") + public Result emergencyStop( + @Parameter(description = "设备SN") @RequestParam String deviceSn) { + boatControlService.emergencyStop(deviceSn); + return Result.succeed(null, "紧急停止指令已下发"); + } + + @Operation(summary = "手动控制") + @PostMapping("/manual") + public Result 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 isDeviceOnline( + @Parameter(description = "设备SN") @PathVariable String deviceSn) { + boolean online = boatControlService.isDeviceOnline(deviceSn); + return Result.succeed(online); + } + + @Operation(summary = "获取设备状态") + @GetMapping("/status/{deviceSn}") + public Result getDeviceStatus( + @Parameter(description = "设备SN") @PathVariable String deviceSn) { + String status = boatControlService.getDeviceStatus(deviceSn); + return Result.succeed(status); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/BoatRouteController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/BoatRouteController.java new file mode 100644 index 00000000..0faa381d --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/BoatRouteController.java @@ -0,0 +1,143 @@ +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.BoatRouteDisplayUpdateDTO; +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 createRoute(@RequestBody @Validated BoatRouteCreateDTO dto) { + String routeId = boatRouteService.createRoute(dto); + return Result.succeed(routeId, "航线创建成功"); + } + + @Operation(summary = "更新航线") + @PutMapping("/{routeId}") + public Result 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 getRouteDetail( + @Parameter(description = "航线ID") @PathVariable String routeId) { + BoatRouteDetailVO detail = boatRouteService.getRouteDetail(routeId); + return Result.succeed(detail); + } + + @Operation(summary = "获取设备绑定的航线列表") + @GetMapping("/list/device/{deviceSn}") + public Result> listByDeviceSn( + @Parameter(description = "设备SN") @PathVariable String deviceSn) { + List list = boatRouteService.listByDeviceSn(deviceSn); + return Result.succeed(list); + } + + @Operation(summary = "获取景区航线列表(分页)") + @GetMapping("/list/scenic/{scenicId}") + public Result> listByScenicId( + @Parameter(description = "景区ID") @PathVariable Long scenicId, + @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page, + @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer size) { + Page pageResult = boatRouteService.listByScenicId(scenicId, page, size); + return Result.succeed(pageResult); + } + + @Operation(summary = "绑定航线到设备") + @PostMapping("/{routeId}/bind") + public Result 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 unbindDevice( + @Parameter(description = "航线ID") @PathVariable String routeId) { + boatRouteService.unbindDevice(routeId); + return Result.succeed(null, "解绑成功"); + } + + @Operation(summary = "校验航线") + @PostMapping("/validate") + public Result 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 deleteRoute( + @Parameter(description = "航线ID") @PathVariable String routeId) { + boatRouteService.deleteRoute(routeId); + return Result.succeed(null, "删除成功"); + } + + @Operation(summary = "保存为模板") + @PostMapping("/{routeId}/template") + public Result 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> listTemplates() { + List list = boatRouteService.listTemplates(); + return Result.succeed(list); + } + + @Operation(summary = "发布航线") + @PostMapping("/{routeId}/publish") + public Result publishRoute( + @Parameter(description = "航线ID") @PathVariable String routeId) { + boatRouteService.publishRoute(routeId); + return Result.succeed(null, "发布成功"); + } + + @Operation(summary = "按设备批量更新航线模型显示状态") + @PutMapping("/display/device/{deviceSn}") + public Result updateShowInModelByDeviceSn( + @Parameter(description = "设备SN") @PathVariable String deviceSn, + @RequestBody @Validated BoatRouteDisplayUpdateDTO dto) { + boatRouteService.updateShowInModelByDeviceSn(deviceSn, dto.getRouteIds()); + return Result.succeed(null, "航线模型显示状态更新成功"); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/BoatTrackController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/BoatTrackController.java new file mode 100644 index 00000000..a1714755 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/BoatTrackController.java @@ -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 getRealtimePosition( + @Parameter(description = "设备SN") @PathVariable String deviceSn) { + BoatRealtimeVO realtime = boatTrackService.getRealtimePosition(deviceSn); + return Result.succeed(realtime); + } + + @Operation(summary = "获取历史轨迹") + @GetMapping("/history/{deviceSn}") + public Result> 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 track = boatTrackService.getHistoryTrack(deviceSn, startTime, endTime); + return Result.succeed(track); + } + + @Operation(summary = "获取任务执行轨迹") + @GetMapping("/task/{taskId}") + public Result getTaskTrack( + @Parameter(description = "任务ID") @PathVariable String taskId) { + TaskTrackVO taskTrack = boatTrackService.getTaskTrack(taskId); + return Result.succeed(taskTrack); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/WaterBoundaryController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/WaterBoundaryController.java new file mode 100644 index 00000000..1ba7e0f6 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/WaterBoundaryController.java @@ -0,0 +1,131 @@ +package com.central.device.controller; + +import com.central.common.model.Result; +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.dto.WaterBoundaryDisplayUpdateDTO; +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 createBoundary(@RequestBody @Validated WaterBoundaryCreateDTO dto) { + String boundaryId = waterBoundaryService.createBoundary(dto); + return Result.succeed(boundaryId, "边界创建成功"); + } + + @Operation(summary = "获取边界详情") + @GetMapping("/{boundaryId}") + public Result getBoundaryDetail( + @Parameter(description = "边界ID") @PathVariable String boundaryId) { + WaterBoundary boundary = waterBoundaryService.getByBoundaryId(boundaryId); + if (boundary == null) { + return Result.failed("边界不存在"); + } + WaterBoundaryVO vo = new WaterBoundaryVO(); + vo.setBoundaryId(boundary.getBoundaryId()); + vo.setBoundaryName(boundary.getBoundaryName()); + vo.setDeviceSn(boundary.getDeviceSn()); + vo.setScenicId(boundary.getScenicId()); + vo.setBoundaryType(boundary.getBoundaryType()); + vo.setPolygonData(boundary.getPolygonData()); + vo.setShowInModel(boundary.getShowInModel()); + vo.setStatus(boundary.getStatus()); + vo.setCreateTime(boundary.getCreateTime()); + return Result.succeed(vo); + } + + @Operation(summary = "获取景区边界列表") + @GetMapping("/list/{scenicId}") + public Result> listByScenicId( + @Parameter(description = "景区ID") @PathVariable Long scenicId) { + List list = waterBoundaryService.listByScenicId(scenicId); + return Result.succeed(list); + } + + @Operation(summary = "获取设备边界列表") + @GetMapping("/list/device/{deviceSn}") + public Result> listByDeviceSn( + @Parameter(description = "设备SN") @PathVariable String deviceSn) { + List list = waterBoundaryService.listByDeviceSn(deviceSn); + return Result.succeed(list); + } + + @Operation(summary = "检测点是否在边界内") + @GetMapping("/check/point") + public Result 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 checkRoute( + @Parameter(description = "边界ID") @RequestParam String boundaryId, + @RequestBody List waypoints) { + BoundaryCheckResultVO result = waterBoundaryService.checkRouteInBoundary(boundaryId, waypoints); + return Result.succeed(result); + } + + @Operation(summary = "从3D模型检测边界(异步)") + @PostMapping("/detect/model") + public Result 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 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 deleteBoundary( + @Parameter(description = "边界ID") @PathVariable String boundaryId) { + waterBoundaryService.deleteBoundary(boundaryId); + return Result.succeed(null, "删除成功"); + } + + @Operation(summary = "按设备批量更新标绘显示状态") + @PutMapping("/display/device/{deviceSn}") + public Result updateShowInModelByDeviceSn( + @Parameter(description = "设备SN") @PathVariable String deviceSn, + @RequestBody @Validated WaterBoundaryDisplayUpdateDTO dto) { + waterBoundaryService.updateShowInModelByDeviceSn(deviceSn, dto.getBoundaryIds()); + return Result.succeed(null, "标绘显示状态更新成功"); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/entity/BoatRoute.java b/zlt-business/device-center/src/main/java/com/central/device/entity/BoatRoute.java new file mode 100644 index 00000000..cb219632 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/entity/BoatRoute.java @@ -0,0 +1,255 @@ +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; + + /** + * 规划水域边界ID + */ + @TableField("boundary_id") + private String boundaryId; + + /** + * 起点坐标(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; + + /** + * 是否在模型中显示航线:0-否,1-是 + */ + @TableField("show_in_model") + private Integer showInModel; + + /** + * 备注 + */ + @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; + } + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/entity/BoatTrack.java b/zlt-business/device-center/src/main/java/com/central/device/entity/BoatTrack.java new file mode 100644 index 00000000..e02b9512 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/entity/BoatTrack.java @@ -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; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/entity/BoatWaypoint.java b/zlt-business/device-center/src/main/java/com/central/device/entity/BoatWaypoint.java new file mode 100644 index 00000000..b25e3d9b --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/entity/BoatWaypoint.java @@ -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 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; + } + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/entity/WaterBoundary.java b/zlt-business/device-center/src/main/java/com/central/device/entity/WaterBoundary.java new file mode 100644 index 00000000..8c9cc017 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/entity/WaterBoundary.java @@ -0,0 +1,193 @@ +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; + + /** + * 绑定设备SN + */ + @TableField("device_sn") + private String deviceSn; + + /** + * 所属景区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("show_in_model") + private Integer showInModel; + + // ========== 状态 ========== + + /** + * 状态: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; + } + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/BoatRouteMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/BoatRouteMapper.java new file mode 100644 index 00000000..0b9e5a23 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/BoatRouteMapper.java @@ -0,0 +1,125 @@ +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 { + + /** + * 根据航线ID查询 + * + * @param routeId 航线ID + * @return 航线 + */ + BoatRoute selectByRouteId(@Param("routeId") String routeId); + + /** + * 根据设备SN查询绑定的航线列表 + * + * @param deviceSn 设备SN + * @return 航线列表 + */ + List selectByDeviceSn(@Param("deviceSn") String deviceSn); + + /** + * 根据景区ID查询航线列表 + * + * @param scenicId 景区ID + * @param tenantId 租户ID + * @return 航线列表 + */ + List selectByScenicId(@Param("scenicId") Long scenicId, @Param("tenantId") String tenantId); + + /** + * 查询模板列表 + * + * @param tenantId 租户ID + * @return 模板列表 + */ + List 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); + + /** + * 根据设备SN重置“模型中显示航线”状态(全部不显示) + * + * @param deviceSn 设备SN + * @param tenantId 租户ID + * @return 影响行数 + */ + int resetShowInModelByDeviceSn(@Param("deviceSn") String deviceSn, @Param("tenantId") String tenantId); + + /** + * 根据设备SN批量设置“模型中显示航线”状态(指定ID集合显示) + * + * @param deviceSn 设备SN + * @param tenantId 租户ID + * @param routeIds 需要显示的航线ID列表 + * @return 影响行数 + */ + int setShowInModelByRouteIds(@Param("deviceSn") String deviceSn, + @Param("tenantId") String tenantId, + @Param("routeIds") List routeIds); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/BoatTrackMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/BoatTrackMapper.java new file mode 100644 index 00000000..3a49416c --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/BoatTrackMapper.java @@ -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 { + + /** + * 查询设备最新位置 + * + * @param deviceSn 设备SN + * @return 最新轨迹点 + */ + BoatTrack selectLatestByDeviceSn(@Param("deviceSn") String deviceSn); + + /** + * 查询设备历史轨迹 + * + * @param deviceSn 设备SN + * @param startTime 开始时间 + * @param endTime 结束时间 + * @return 轨迹列表 + */ + List selectHistoryTrack(@Param("deviceSn") String deviceSn, + @Param("startTime") LocalDateTime startTime, + @Param("endTime") LocalDateTime endTime); + + /** + * 查询任务轨迹 + * + * @param taskId 任务ID + * @return 轨迹列表 + */ + List selectByTaskId(@Param("taskId") String taskId); + + /** + * 查询航线执行轨迹 + * + * @param routeId 航线ID + * @param taskId 任务ID + * @return 轨迹列表 + */ + List selectByRouteIdAndTaskId(@Param("routeId") String routeId, @Param("taskId") String taskId); + + /** + * 批量插入轨迹点 + * + * @param tracks 轨迹列表 + * @return 影响行数 + */ + int batchInsert(@Param("list") List tracks); + + /** + * 删除指定时间之前的轨迹数据(用于历史数据归档) + * + * @param beforeTime 时间阈值 + * @return 影响行数 + */ + int deleteBeforeTime(@Param("beforeTime") LocalDateTime beforeTime); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/BoatWaypointMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/BoatWaypointMapper.java new file mode 100644 index 00000000..1cab26d3 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/BoatWaypointMapper.java @@ -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 { + + /** + * 根据航线ID查询航点列表(按序号排序) + * + * @param routeId 航线ID + * @return 航点列表 + */ + List selectByRouteIdOrderByIndex(@Param("routeId") String routeId); + + /** + * 根据航线ID删除航点 + * + * @param routeId 航线ID + * @return 影响行数 + */ + int deleteByRouteId(@Param("routeId") String routeId); + + /** + * 批量插入航点 + * + * @param waypoints 航点列表 + * @return 影响行数 + */ + int batchInsert(@Param("list") List waypoints); + + /** + * 根据航线ID统计航点数量 + * + * @param routeId 航线ID + * @return 航点数量 + */ + int countByRouteId(@Param("routeId") String routeId); + + /** + * 根据航点ID查询 + * + * @param waypointId 航点ID + * @return 航点 + */ + BoatWaypoint selectByWaypointId(@Param("waypointId") String waypointId); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/WaterBoundaryMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/WaterBoundaryMapper.java new file mode 100644 index 00000000..2c0db20e --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/WaterBoundaryMapper.java @@ -0,0 +1,94 @@ +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 { + + /** + * 根据边界ID查询 + * + * @param boundaryId 边界ID + * @return 边界 + */ + WaterBoundary selectByBoundaryId(@Param("boundaryId") String boundaryId); + + /** + * 根据设备SN查询边界列表 + * + * @param deviceSn 设备SN + * @param tenantId 租户ID + * @return 边界列表 + */ + List selectByDeviceSn(@Param("deviceSn") String deviceSn, @Param("tenantId") String tenantId); + + /** + * 根据景区ID查询边界列表 + * + * @param scenicId 景区ID + * @param tenantId 租户ID + * @return 边界列表 + */ + List selectByScenicId(@Param("scenicId") Long scenicId, @Param("tenantId") String tenantId); + + /** + * 根据景区ID和边界类型查询 + * + * @param scenicId 景区ID + * @param boundaryType 边界类型 + * @param tenantId 租户ID + * @return 边界列表 + */ + List 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); + + /** + * 根据设备SN重置显示标绘状态(全部不显示) + * + * @param deviceSn 设备SN + * @param tenantId 租户ID + * @return 影响行数 + */ + int resetShowInModelByDeviceSn(@Param("deviceSn") String deviceSn, @Param("tenantId") String tenantId); + + /** + * 根据设备SN批量设置显示标绘状态(指定ID集合显示) + * + * @param deviceSn 设备SN + * @param tenantId 租户ID + * @param boundaryIds 需要显示的边界ID列表 + * @return 影响行数 + */ + int setShowInModelByBoundaryIds(@Param("deviceSn") String deviceSn, + @Param("tenantId") String tenantId, + @Param("boundaryIds") List boundaryIds); + + /** + * 根据3D模型ID查询关联边界 + * + * @param modelId 模型ID + * @return 边界列表 + */ + List selectByModelId(@Param("modelId") String modelId); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatManualControlDTO.java b/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatManualControlDTO.java new file mode 100644 index 00000000..5503e6ce --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatManualControlDTO.java @@ -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; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteCreateDTO.java b/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteCreateDTO.java new file mode 100644 index 00000000..f51b1ee3 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteCreateDTO.java @@ -0,0 +1,58 @@ +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 = "是否在模型中显示航线:0-否,1-是(可选,默认0)", example = "0") + private Integer showInModel = 0; + + @Schema(description = "航点列表", required = true) + @NotEmpty(message = "航点不能为空") + private List waypoints; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteDisplayUpdateDTO.java b/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteDisplayUpdateDTO.java new file mode 100644 index 00000000..c75b2c5b --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteDisplayUpdateDTO.java @@ -0,0 +1,23 @@ +package com.central.device.model.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotNull; +import lombok.Data; + +import java.util.List; + +/** + * 无人船航线“模型中显示”状态更新DTO + * + * @author dzc + * @date 2026-01-08 + */ +@Data +@Schema(description = "无人船航线模型显示状态更新请求") +public class BoatRouteDisplayUpdateDTO { + + @Schema(description = "需要在模型中显示的航线ID列表(传空数组表示全隐)") + @NotNull(message = "routeIds不能为空(可传空数组)") + private List routeIds; +} + diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteUpdateDTO.java b/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteUpdateDTO.java new file mode 100644 index 00000000..6b8662b3 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteUpdateDTO.java @@ -0,0 +1,48 @@ +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 = "是否在模型中显示航线:0-否,1-是(可选)", example = "1") + private Integer showInModel; + + @Schema(description = "规划水域边界ID(可选,修改规划水域时传)") + private String boundaryId; + + @Schema(description = "航点列表(如果提供则更新所有航点)") + private List waypoints; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatWaypointDTO.java b/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatWaypointDTO.java new file mode 100644 index 00000000..72f3a32b --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatWaypointDTO.java @@ -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 actions; + + @Schema(description = "备注") + private String remark; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/dto/PointDTO.java b/zlt-business/device-center/src/main/java/com/central/device/model/dto/PointDTO.java new file mode 100644 index 00000000..7d477b86 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/dto/PointDTO.java @@ -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; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/dto/WaterBoundaryCreateDTO.java b/zlt-business/device-center/src/main/java/com/central/device/model/dto/WaterBoundaryCreateDTO.java new file mode 100644 index 00000000..e0b9d64b --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/dto/WaterBoundaryCreateDTO.java @@ -0,0 +1,51 @@ +package com.central.device.model.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +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 = "绑定设备SN", required = true) + @NotBlank(message = "设备SN不能为空") + private String deviceSn; + + @Schema(description = "所属景区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; + + @Schema(description = "是否在模型中显示标绘:0-否,1-是(可选,默认1)") + private Integer showInModel = 1; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/dto/WaterBoundaryDisplayUpdateDTO.java b/zlt-business/device-center/src/main/java/com/central/device/model/dto/WaterBoundaryDisplayUpdateDTO.java new file mode 100644 index 00000000..f0a53a6f --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/dto/WaterBoundaryDisplayUpdateDTO.java @@ -0,0 +1,23 @@ +package com.central.device.model.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotNull; +import lombok.Data; + +import java.util.List; + +/** + * 水域边界标绘显示状态更新DTO + * + * @author dzc + * @date 2026-01-07 + */ +@Data +@Schema(description = "水域边界标绘显示状态更新请求") +public class WaterBoundaryDisplayUpdateDTO { + + @Schema(description = "需要在模型中显示的边界ID列表(传空数组表示全隐)") + @NotNull(message = "boundaryIds不能为空(可传空数组)") + private List boundaryIds; +} + diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/dto/WaypointActionDTO.java b/zlt-business/device-center/src/main/java/com/central/device/model/dto/WaypointActionDTO.java new file mode 100644 index 00000000..5aeab9ba --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/dto/WaypointActionDTO.java @@ -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; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatRealtimeVO.java b/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatRealtimeVO.java new file mode 100644 index 00000000..bd52004a --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatRealtimeVO.java @@ -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; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatRouteDetailVO.java b/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatRouteDetailVO.java new file mode 100644 index 00000000..175575ae --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatRouteDetailVO.java @@ -0,0 +1,94 @@ +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 = "是否在模型中显示航线:0-否,1-是") + private Integer showInModel; + + @Schema(description = "规划水域边界ID") + private String boundaryId; + + @Schema(description = "备注") + private String remark; + + @Schema(description = "航点列表") + private List waypoints; + + @Schema(description = "创建时间") + private LocalDateTime createTime; + + @Schema(description = "更新时间") + private LocalDateTime updateTime; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatRouteListVO.java b/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatRouteListVO.java new file mode 100644 index 00000000..9896be5f --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatRouteListVO.java @@ -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 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 = "是否在模型中显示航线:0-否,1-是") + private Integer showInModel; + + @Schema(description = "规划水域边界ID") + private String boundaryId; + + @Schema(description = "创建时间") + private LocalDateTime createTime; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatWaypointVO.java b/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatWaypointVO.java new file mode 100644 index 00000000..24be8de8 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatWaypointVO.java @@ -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 actions; + + @Schema(description = "备注") + private String remark; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoundaryCheckResultVO.java b/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoundaryCheckResultVO.java new file mode 100644 index 00000000..f3e1ac57 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoundaryCheckResultVO.java @@ -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 outOfBoundarySegments = new ArrayList<>(); + + @Schema(description = "超出边界的航点索引列表") + private List 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); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/vo/RouteValidateResultVO.java b/zlt-business/device-center/src/main/java/com/central/device/model/vo/RouteValidateResultVO.java new file mode 100644 index 00000000..622f7263 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/vo/RouteValidateResultVO.java @@ -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 errors = new ArrayList<>(); + + @Schema(description = "警告列表") + private List 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); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/vo/TaskTrackVO.java b/zlt-business/device-center/src/main/java/com/central/device/model/vo/TaskTrackVO.java new file mode 100644 index 00000000..ab6e8d75 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/vo/TaskTrackVO.java @@ -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 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; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/vo/TrackPointVO.java b/zlt-business/device-center/src/main/java/com/central/device/model/vo/TrackPointVO.java new file mode 100644 index 00000000..51fcf6d3 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/vo/TrackPointVO.java @@ -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; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/vo/WaterBoundaryVO.java b/zlt-business/device-center/src/main/java/com/central/device/model/vo/WaterBoundaryVO.java new file mode 100644 index 00000000..44c037bb --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/vo/WaterBoundaryVO.java @@ -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 WaterBoundaryVO { + + @Schema(description = "边界ID") + private String boundaryId; + + @Schema(description = "边界名称") + private String boundaryName; + + @Schema(description = "绑定设备SN") + private String deviceSn; + + @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 showInModel; + + @Schema(description = "状态:0-禁用,1-启用") + private Integer status; + + @Schema(description = "状态描述") + private String statusDesc; + + @Schema(description = "创建时间") + private LocalDateTime createTime; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/IBoatControlService.java b/zlt-business/device-center/src/main/java/com/central/device/service/IBoatControlService.java new file mode 100644 index 00000000..c027e4a9 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/IBoatControlService.java @@ -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); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/IBoatRouteService.java b/zlt-business/device-center/src/main/java/com/central/device/service/IBoatRouteService.java new file mode 100644 index 00000000..1f1bb21c --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/IBoatRouteService.java @@ -0,0 +1,141 @@ +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 { + + /** + * 创建航线 + * + * @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 listByDeviceSn(String deviceSn); + + /** + * 获取景区航线列表(分页) + * + * @param scenicId 景区ID + * @param page 页码 + * @param size 每页数量 + * @return 航线分页列表 + */ + Page 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 listTemplates(); + + /** + * 更新航线状态 + * + * @param routeId 航线ID + * @param status 状态 + */ + void updateStatus(String routeId, Integer status); + + /** + * 发布航线 + * + * @param routeId 航线ID + */ + void publishRoute(String routeId); + + /** + * 按设备批量更新“模型中显示航线”状态(未包含的航线会被置为不显示) + * + * @param deviceSn 设备SN + * @param routeIds 需要显示的航线ID列表 + */ + void updateShowInModelByDeviceSn(String deviceSn, List routeIds); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/IBoatTrackService.java b/zlt-business/device-center/src/main/java/com/central/device/service/IBoatTrackService.java new file mode 100644 index 00000000..fa21f3bf --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/IBoatTrackService.java @@ -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 { + + /** + * 获取实时位置 + * + * @param deviceSn 设备SN + * @return 实时位置 + */ + BoatRealtimeVO getRealtimePosition(String deviceSn); + + /** + * 获取历史轨迹 + * + * @param deviceSn 设备SN + * @param startTime 开始时间 + * @param endTime 结束时间 + * @return 轨迹点列表 + */ + List 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 tracks); + + /** + * 注册遥测数据回调 + * + * @param deviceSn 设备SN + * @param connectionId 连接ID + * @param callback 回调函数 + */ + void registerTelemetryCallback(String deviceSn, String connectionId, Consumer 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); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/IWaterBoundaryService.java b/zlt-business/device-center/src/main/java/com/central/device/service/IWaterBoundaryService.java new file mode 100644 index 00000000..b863ee7d --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/IWaterBoundaryService.java @@ -0,0 +1,102 @@ +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 { + + /** + * 创建水域边界 + * + * @param dto 创建参数 + * @return 边界ID + */ + String createBoundary(WaterBoundaryCreateDTO dto); + + /** + * 根据边界ID查询 + * + * @param boundaryId 边界ID + * @return 边界实体 + */ + WaterBoundary getByBoundaryId(String boundaryId); + + /** + * 获取设备水域边界列表 + * + * @param deviceSn 设备SN + * @return 边界列表 + */ + List listByDeviceSn(String deviceSn); + + /** + * 获取景区水域边界列表 + * + * @param scenicId 景区ID + * @return 边界列表 + */ + List 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 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); + + /** + * 按设备维度批量更新“模型中显示标绘”状态:未包含的边界会被置为不显示 + * + * @param deviceSn 设备SN + * @param boundaryIds 需要显示的边界ID列表(空列表表示全隐) + */ + void updateShowInModelByDeviceSn(String deviceSn, List boundaryIds); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/BoatControlServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/BoatControlServiceImpl.java new file mode 100644 index 00000000..4906876f --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/BoatControlServiceImpl.java @@ -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 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); + } + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/BoatRouteServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/BoatRouteServiceImpl.java new file mode 100644 index 00000000..58ac5920 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/BoatRouteServiceImpl.java @@ -0,0 +1,535 @@ +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.Collections; +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 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.setBoundaryId(dto.getBoundaryId()); + route.setRemark(dto.getRemark()); + route.setTenantId(LoginUserContextHolder.getCurrentTenantId()); + route.setStatus(BoatRoute.RouteStatus.DRAFT.getCode()); + route.setIsTemplate(false); + route.setShowInModel(dto.getShowInModel() != null ? dto.getShowInModel() : 0); + + // 2. 计算航线统计信息 + List 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 waypoints, BigDecimal defaultSpeed) { + List 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 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.getShowInModel() != null) { + route.setShowInModel(dto.getShowInModel()); + } + if (StrUtil.isNotBlank(dto.getBoundaryId())) { + route.setBoundaryId(StrUtil.trim(dto.getBoundaryId())); + } + + // 如果提供了航点则更新航点 + 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 + @Transactional(rollbackFor = Exception.class) + public void updateShowInModelByDeviceSn(String deviceSn, List routeIds) { + String sn = StrUtil.trimToEmpty(deviceSn); + if (StrUtil.isBlank(sn)) { + throw new BusinessException("设备SN不能为空"); + } + + String tenantId = LoginUserContextHolder.getCurrentTenantId(); + List ids = routeIds == null ? Collections.emptyList() : routeIds.stream() + .filter(StrUtil::isNotBlank) + .map(StrUtil::trim) + .distinct() + .collect(Collectors.toList()); + + baseMapper.resetShowInModelByDeviceSn(sn, tenantId); + if (!ids.isEmpty()) { + baseMapper.setShowInModelByRouteIds(sn, tenantId, ids); + } + + log.info("更新无人船航线模型显示状态成功: deviceSn={}, showCount={}", sn, ids.size()); + } + + @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 waypoints = waypointMapper.selectByRouteIdOrderByIndex(routeId); + List 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 listByDeviceSn(String deviceSn) { + List routes = baseMapper.selectByDeviceSn(deviceSn); + return convertToListVO(routes); + } + + @Override + public Page listByScenicId(Long scenicId, Integer page, Integer size) { + String tenantId = LoginUserContextHolder.getCurrentTenantId(); + Page pageParam = new Page<>(page, size); + + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(BoatRoute::getScenicId, scenicId) + .eq(BoatRoute::getTenantId, tenantId) + .eq(BoatRoute::getDeleted, 0) + .orderByDesc(BoatRoute::getCreateTime); + + Page routePage = this.page(pageParam, wrapper); + + Page resultPage = new Page<>(page, size, routePage.getTotal()); + resultPage.setRecords(convertToListVO(routePage.getRecords())); + return resultPage; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void bindToDevice(String routeId, String deviceSn) { + 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 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 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("执行中的航线不能删除"); + } + + // 逻辑删除航线:使用 MyBatis-Plus @TableLogic,避免手动更新字段在拦截器/策略下不生效 + boolean removed = this.removeById(route.getId()); + if (!removed) { + throw new BusinessException("删除失败(未找到可删除的航线记录)"); + } + + // 删除航点 + 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 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 listTemplates() { + String tenantId = LoginUserContextHolder.getCurrentTenantId(); + List 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 convertToListVO(List 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 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 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(); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/BoatTrackServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/BoatTrackServiceImpl.java new file mode 100644 index 00000000..caeef603 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/BoatTrackServiceImpl.java @@ -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 implements IBoatTrackService { + + /** + * 设备实时数据缓存 + * key: deviceSn, value: 最新遥测数据 + */ + private final Map realtimeCache = new ConcurrentHashMap<>(); + + /** + * 遥测数据回调注册表 + * key: deviceSn, value: Map + */ + private final Map>> 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 getHistoryTrack(String deviceSn, LocalDateTime startTime, LocalDateTime endTime) { + if (startTime == null || endTime == null) { + throw new BusinessException("开始时间和结束时间不能为空"); + } + if (startTime.isAfter(endTime)) { + throw new BusinessException("开始时间不能晚于结束时间"); + } + + List tracks = baseMapper.selectHistoryTrack(deviceSn, startTime, endTime); + return tracks.stream() + .map(this::convertToTrackPointVO) + .collect(Collectors.toList()); + } + + @Override + public TaskTrackVO getTaskTrack(String taskId) { + List tracks = baseMapper.selectByTaskId(taskId); + if (tracks.isEmpty()) { + return null; + } + + TaskTrackVO vo = new TaskTrackVO(); + vo.setTaskId(taskId); + vo.setDeviceSn(tracks.get(0).getDeviceSn()); + + List 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 tracks) { + if (tracks == null || tracks.isEmpty()) { + return; + } + baseMapper.batchInsert(tracks); + + // 更新每个设备的实时缓存(取最新的) + Map 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 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 callback) { + Map> 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> 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> deviceCallbacks = telemetryCallbacks.get(deviceSn); + if (deviceCallbacks != null && !deviceCallbacks.isEmpty()) { + for (Map.Entry> 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; + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/WaterBoundaryServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/WaterBoundaryServiceImpl.java new file mode 100644 index 00000000..71ef0968 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/WaterBoundaryServiceImpl.java @@ -0,0 +1,322 @@ +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.Collections; +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 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.setDeviceSn(dto.getDeviceSn()); + 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.setShowInModel(dto.getShowInModel() != null ? dto.getShowInModel() : 1); + 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 listByDeviceSn(String deviceSn) { + String tenantId = LoginUserContextHolder.getCurrentTenantId(); + List boundaries = baseMapper.selectByDeviceSn(deviceSn, 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 List listByScenicId(Long scenicId) { + String tenantId = LoginUserContextHolder.getCurrentTenantId(); + List 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 polygon = parseGeoJsonPolygon(boundary.getPolygonData()); + if (polygon.isEmpty()) { + return false; + } + + // 射线法检测 + return isPointInPolygon(longitude, latitude, polygon); + } + + @Override + public BoundaryCheckResultVO checkRouteInBoundary(String boundaryId, List 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 polygon = parseGeoJsonPolygon(boundary.getPolygonData()); + if (polygon.isEmpty()) { + result.setAllInBoundary(false); + result.addOutOfBoundarySegment("边界数据无效"); + return result; + } + + // 检查每个航点 + List 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); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void updateShowInModelByDeviceSn(String deviceSn, List boundaryIds) { + String sn = StrUtil.trimToEmpty(deviceSn); + if (StrUtil.isBlank(sn)) { + throw new BusinessException("设备SN不能为空"); + } + + String tenantId = LoginUserContextHolder.getCurrentTenantId(); + List ids = boundaryIds == null ? Collections.emptyList() : boundaryIds.stream() + .filter(StrUtil::isNotBlank) + .map(StrUtil::trim) + .distinct() + .collect(Collectors.toList()); + + // 先全量重置为不显示,再批量置为显示(保证“选择几个就保存几个”) + baseMapper.resetShowInModelByDeviceSn(sn, tenantId); + if (!ids.isEmpty()) { + baseMapper.setShowInModelByBoundaryIds(sn, tenantId, ids); + } + + log.info("更新水域边界标绘显示状态成功: deviceSn={}, showCount={}", sn, ids.size()); + } + + // ========== 私有方法 ========== + + /** + * 解析GeoJSON获取多边形坐标 + * 支持Polygon类型的GeoJSON + */ + private List parseGeoJsonPolygon(String geoJson) { + List 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 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 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; + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/sse/controller/BoatTelemetrySseController.java b/zlt-business/device-center/src/main/java/com/central/device/sse/controller/BoatTelemetrySseController.java new file mode 100644 index 00000000..6d103caf --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/sse/controller/BoatTelemetrySseController.java @@ -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 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 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 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 disconnectBoatTelemetryByBeacon( + @Parameter(description = "设备SN", required = true) + @PathVariable String deviceSn, + @RequestBody(required = false) Map 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; + } +} diff --git a/zlt-business/device-center/src/main/resources/bootstrap.yml b/zlt-business/device-center/src/main/resources/bootstrap.yml index 698e082a..a10b30be 100644 --- a/zlt-business/device-center/src/main/resources/bootstrap.yml +++ b/zlt-business/device-center/src/main/resources/bootstrap.yml @@ -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: diff --git a/zlt-business/device-center/src/main/resources/doc/无人船航线规划和水域边界管理功能实施方案.md b/zlt-business/device-center/src/main/resources/doc/无人船航线规划和水域边界管理功能实施方案.md new file mode 100644 index 00000000..cae5080f --- /dev/null +++ b/zlt-business/device-center/src/main/resources/doc/无人船航线规划和水域边界管理功能实施方案.md @@ -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; + 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` 记录所有创建的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 = ({ 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>([]); +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>([]); + 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 && ( +
+ setBoundaryEditorVisible(false)} + onCancel={() => setBoundaryEditorVisible(false)} + viewerRef={viewerRef} + /> +
+)} +``` + +--- + +### ✅ 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>(new Set()); +const [visibleBoundaries, setVisibleBoundaries] = useState>(new Set()); +const routeEntitiesRef = useRef>(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区域渲染 + 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(null); + const trackEntityRef = useRef(null); + const trackPositionsRef = useRef([]); + + // 订阅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添加开关 + +``` + +--- + +## 五、技术难点和解决方案 + +### 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>(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 | + diff --git a/zlt-business/device-center/src/main/resources/doc/无人船航线规划技术方案.md b/zlt-business/device-center/src/main/resources/doc/无人船航线规划技术方案.md new file mode 100644 index 00000000..3a5158b0 --- /dev/null +++ b/zlt-business/device-center/src/main/resources/doc/无人船航线规划技术方案.md @@ -0,0 +1,2508 @@ +# 无人船航线规划技术方案 + +## 1. 需求概述 + +### 1.1 业务背景 +在旅游景区管理场景中,无人船作为水域巡检、游客观光、环境监测的重要设备,需要实现基于3D模型的智能航线规划功能。通过结合倾斜摄影模型,实现水域边界识别、航线自动生成、航线手动编辑等核心功能。 + +### 1.2 功能目标 +| 功能模块 | 描述 | 优先级 | +|---------|------|--------| +| 水域边界识别 | 基于3D模型自动识别可航行水域范围 | P0 | +| 航线规划编辑器 | 支持在3D地图上手动绘制/编辑航线 | P0 | +| 航点配置 | 配置航点停留时间、速度、动作 | P0 | +| 航线任务执行 | 将规划航线下发到无人船执行 | P0 | +| 实时轨迹显示 | 显示无人船实时位置和历史轨迹 | P1 | +| 障碍物规避 | 基于模型检测航线是否穿过障碍物 | P1 | +| 航线模板 | 保存常用航线为模板复用 | P2 | + +### 1.3 与现有系统的关系 + +**核心原则:无人船任务下发与无人机保持完全一致,复用现有Mission任务管理机制。** + +``` +现有系统已实现(完全复用): +├─ 任务管理框架 (order-center) +│ ├─ Mission实体 - 统一任务模型 +│ ├─ MissionController - 任务创建/执行/取消/完成 +│ ├─ MissionServiceImpl - 任务下发到设备 +│ ├─ MissionType枚举 - 任务类型定义 +│ └─ MissionStatus枚举 - 任务状态流转 +│ +├─ 设备控制框架 (device-center) +│ ├─ DeviceCommandController - 设备命令控制 +│ ├─ DeviceCommandManager - WebSocket命令管理 +│ └─ DeviceSubscriptionManager - 设备订阅管理 +│ +├─ 无人机航线管理 (device-center) +│ ├─ WaylineRoute/WaylineWaypoint/WaylineAction +│ └─ KmzFileParser - 航线文件解析 +│ +├─ 实时通信 (device-center) +│ ├─ WebSocket实时通信 +│ └─ SSE遥测订阅 +│ +└─ 前端展示 (yingyan) + ├─ 3D模型加载展示 (useTilesetLoader) + ├─ 航线可视化渲染 (TaskPanel) + └─ 任务面板组件 + +需要新增/扩展: +├─ MissionType枚举 - 新增 BOAT_ROUTE(3, "无人船航线任务") +├─ Mission实体 - 扩展boatRouteId字段 +├─ MissionServiceImpl - 新增无人船任务下发逻辑 +├─ DeviceCenterService(Feign) - 新增executeBoatRoute接口 +├─ BoatRouteController - 无人船航线CRUD +├─ BoatControlService - 无人船控制服务 +├─ 水域边界检测服务 (WaterBoundaryService) +└─ 前端航线编辑器组件 (RouteEditor) +``` + +### 1.4 任务系统对比 + +| 对比项 | 无人机任务 | 无人船任务 | +|-------|-----------|-----------| +| 任务类型 | WAYLINE(1), TAKEOFF(2) | BOAT_ROUTE(3) | +| 航线实体 | WaylineRoute | BoatRoute | +| 任务创建 | MissionController.saveMission | MissionController.saveMission (复用) | +| 任务执行 | MissionController.executeMission | MissionController.executeMission (复用) | +| 设备下发 | DeviceCenterService.executeWayline | DeviceCenterService.executeBoatRoute (新增) | +| 状态流转 | MissionStatus枚举 | MissionStatus枚举 (复用) | +| 任务取消 | MissionController.cancelMission | MissionController.cancelMission (复用) | + +--- + +## 2. 系统架构设计 + +### 2.1 整体架构 + +``` +┌─────────────────────────────────────────────────────────────────────────────┐ +│ 鹰眼可视化大屏 (yingyan) │ +├─────────────────────────────────────────────────────────────────────────────┤ +│ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ │ +│ │ CesiumContainer │ │ RouteEditor │ │ TaskPanel │ │ +│ │ 3D地图渲染 │ │ 航线编辑器 │ │ 任务管理 │ │ +│ └───────┬────────┘ └───────┬────────┘ └───────┬────────┘ │ +│ │ │ │ │ +│ ┌───────┴───────────────────┴───────────────────┴────────┐ │ +│ │ 航线规划服务层 │ │ +│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ +│ │ │RouteDrawer │ │BoundaryCheck│ │MissionAPI │ │ │ +│ │ │航线绘制 │ │边界检测 │ │任务管理(复用)│ │ │ +│ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │ +│ └────────────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────────────────────┘ + │ + │ HTTP/SSE + ▼ +┌─────────────────────────────────────────────────────────────────────────────┐ +│ 订单中心 (order-center) │ +├─────────────────────────────────────────────────────────────────────────────┤ +│ ┌────────────────────────────────────────────────────────────────────────┐ │ +│ │ Mission 任务管理 (统一入口) │ │ +│ │ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ │ │ +│ │ │MissionController│ │MissionService │ │DeviceCenter │ │ │ +│ │ │任务创建/执行 │ │Impl │ │Service(Feign) │ │ │ +│ │ │/取消/完成 │ │任务状态管理 │ │设备中心调用 │ │ │ +│ │ └────────────────┘ └────────────────┘ └────────────────┘ │ │ +│ │ │ │ +│ │ 任务类型: WAYLINE(1)=无人机航线 | TAKEOFF(2)=一键起飞 | BOAT_ROUTE(3)=无人船航线 │ +│ │ 状态流转: PENDING(1) → DOING(4) → UPLOADING(5) → UPLOADED(6) → COMPLETE(3) │ +│ └────────────────────────────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────────────────────┘ + │ + │ Feign RPC + ▼ +┌─────────────────────────────────────────────────────────────────────────────┐ +│ 设备中心 (device-center) │ +├─────────────────────────────────────────────────────────────────────────────┤ +│ ┌────────────────────────────────────────────────────────────────────────┐ │ +│ │ Controller 层 │ │ +│ │ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ │ │ +│ │ │BoatRouteController│ │DeviceCommand │ │BoatTrack │ │ │ +│ │ │无人船航线CRUD │ │Controller │ │Controller │ │ │ +│ │ │ │ │设备命令控制 │ │轨迹查询 │ │ │ +│ │ └────────────────┘ └────────────────┘ └────────────────┘ │ │ +│ └────────────────────────────────────────────────────────────────────────┘ │ +│ ┌────────────────────────────────────────────────────────────────────────┐ │ +│ │ Service 层 │ │ +│ │ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ │ │ +│ │ │BoatRouteService │ │WaterBoundary │ │BoatControl │ │ │ +│ │ │航线CRUD服务 │ │Service │ │Service │ │ │ +│ │ │ │ │水域边界服务 │ │无人船控制服务 │ │ │ +│ │ └────────────────┘ └────────────────┘ └────────────────┘ │ │ +│ └────────────────────────────────────────────────────────────────────────┘ │ +│ ┌────────────────────────────────────────────────────────────────────────┐ │ +│ │ WebSocket 层 │ │ +│ │ ┌────────────────────────────────────────────────────────┐ │ │ +│ │ │ DeviceSubscriptionManager (复用) + BoatTelemetryHandler │ │ │ +│ │ │ 无人船遥测数据订阅与处理 │ │ │ +│ │ └────────────────────────────────────────────────────────┘ │ │ +│ └────────────────────────────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────────────────────┘ + │ + │ MySQL / Redis / IoT + ▼ +┌─────────────────────────────────────────────────────────────────────────────┐ +│ 数据存储层 │ +│ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ │ +│ │ MySQL │ │ Redis │ │ IoT平台 │ │ +│ │ 航线+任务数据 │ │ 实时位置缓存 │ │ 设备通信 │ │ +│ └────────────────┘ └────────────────┘ └────────────────┘ │ +└─────────────────────────────────────────────────────────────────────────────┘ +``` + +### 2.2 技术选型 + +| 层级 | 技术选型 | 说明 | +|------|---------|------| +| 前端框架 | React 18 + TypeScript | 与现有yingyan项目保持一致 | +| 3D引擎 | Cesium.js | 复用现有3D地图组件 | +| 航线编辑 | Cesium DrawHelper + 自定义 | 点线绘制交互 | +| 后端框架 | Spring Boot 3.1.6 | 与现有device-center保持一致 | +| ORM框架 | MyBatis Plus 3.5.4 | 复用现有数据访问层 | +| 实时通信 | SSE + WebSocket | 复用现有通信架构 | +| 数据库 | MySQL 8.0 | 与现有系统共用 | +| 缓存 | Redis 7.0 | 实时位置缓存 | + +--- + +## 3. 数据模型设计 + +### 3.1 数据库表结构 + +#### 3.1.1 无人船航线表 (boat_route) +```sql +CREATE TABLE `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`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='无人船航线表'; +``` + +#### 3.1.2 无人船航点表 (boat_waypoint) +```sql +CREATE TABLE `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.1.3 无人船轨迹表 (boat_track) +```sql +CREATE TABLE `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', + + -- 位置信息 + `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_record_time` (`record_time`), + KEY `idx_device_time` (`device_sn`, `record_time`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='无人船轨迹表'; +``` + +#### 3.1.4 水域边界表 (water_boundary) +```sql +CREATE TABLE `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`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='水域边界表'; +``` + +### 3.2 实体类设计 + +#### 3.2.1 BoatRoute.java +```java +package com.central.device.entity; + +import com.baomidou.mybatisplus.annotation.*; +import lombok.Data; +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +@TableName("boat_route") +public class BoatRoute { + @TableId(type = IdType.AUTO) + private Long id; + + private String routeId; + private String routeName; + private String deviceSn; + private String deviceName; + private Long scenicId; + private String tenantId; + + // 航线统计 + private Integer waypointCount; + private BigDecimal totalDistance; + private Integer totalDuration; + private BigDecimal cruiseSpeed; + + // 航线边界 + private String boundaryPolygon; + private String startPoint; + private String endPoint; + + // 航线配置 + private Boolean loopEnabled; + private Integer loopCount; + private String returnMode; + private BigDecimal safeDistance; + + // 状态 + private Integer status; + private Boolean isTemplate; + private String remark; + + @TableField(fill = FieldFill.INSERT) + private LocalDateTime createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private LocalDateTime updateTime; + private String createBy; + + @TableLogic + private Integer deleted; +} +``` + +#### 3.2.2 BoatWaypoint.java +```java +package com.central.device.entity; + +import com.baomidou.mybatisplus.annotation.*; +import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler; +import lombok.Data; +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +@Data +@TableName(value = "boat_waypoint", autoResultMap = true) +public class BoatWaypoint { + @TableId(type = IdType.AUTO) + private Long id; + + private String waypointId; + private String routeId; + private Integer waypointIndex; + + // 位置 + private BigDecimal longitude; + private BigDecimal latitude; + + // 航行参数 + private BigDecimal speed; + private Integer stayDuration; + private BigDecimal headingAngle; + private String turnMode; + + // 动作配置 + @TableField(typeHandler = JacksonTypeHandler.class) + private List actions; + + // 标记 + private Boolean isKeyPoint; + private String pointName; + private String remark; + + @TableField(fill = FieldFill.INSERT) + private LocalDateTime createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private LocalDateTime updateTime; +} + +// 航点动作内嵌类 +@Data +class WaypointAction { + private String actionType; // photo/video_start/video_stop/horn/light + private Integer duration; // 动作持续时间(秒) + private Object params; // 动作参数 +} +``` + +### 3.3 VO/DTO设计 + +```java +// 航线创建请求 +@Data +public class BoatRouteCreateDTO { + @NotBlank(message = "航线名称不能为空") + private String routeName; + private String deviceSn; + private Long scenicId; + private BigDecimal cruiseSpeed = BigDecimal.valueOf(2.0); + private Boolean loopEnabled = false; + private Integer loopCount = 1; + private String returnMode = "return_start"; + private String remark; + + @NotEmpty(message = "航点不能为空") + private List waypoints; +} + +// 航点DTO +@Data +public class BoatWaypointDTO { + @NotNull + private BigDecimal longitude; + @NotNull + private BigDecimal latitude; + private BigDecimal speed; + private Integer stayDuration = 0; + private String turnMode = "smooth"; + private List actions; + private String pointName; +} + +// 航线详情VO +@Data +public class BoatRouteDetailVO { + private String routeId; + private String routeName; + private String deviceSn; + private String deviceName; + private Integer waypointCount; + private BigDecimal totalDistance; + private String totalDurationStr; // 格式化后的时长 + private BigDecimal cruiseSpeed; + private String status; + private List waypoints; + private LocalDateTime createTime; +} +``` + +--- + +## 4. 后端接口设计 + +### 4.1 Controller层 + +#### 4.1.1 BoatRouteController.java +```java +package com.central.device.controller; + +@RestController +@RequestMapping("/device/boat/route") +@RequiredArgsConstructor +@Slf4j +public class BoatRouteController { + + private final IBoatRouteService boatRouteService; + private final IWaterBoundaryService waterBoundaryService; + + /** + * 创建航线 + */ + @PostMapping("/create") + public Result createRoute(@RequestBody @Valid BoatRouteCreateDTO dto) { + String routeId = boatRouteService.createRoute(dto); + return Result.succeed(routeId, "航线创建成功"); + } + + /** + * 更新航线 + */ + @PutMapping("/update/{routeId}") + public Result updateRoute( + @PathVariable String routeId, + @RequestBody @Valid BoatRouteUpdateDTO dto) { + boatRouteService.updateRoute(routeId, dto); + return Result.succeed("航线更新成功"); + } + + /** + * 获取航线详情(含航点) + */ + @GetMapping("/detail/{routeId}") + public Result getRouteDetail(@PathVariable String routeId) { + return Result.succeed(boatRouteService.getRouteDetail(routeId)); + } + + /** + * 获取设备绑定的航线列表 + */ + @GetMapping("/list/device/{deviceSn}") + public Result> getRoutesByDevice(@PathVariable String deviceSn) { + return Result.succeed(boatRouteService.listByDeviceSn(deviceSn)); + } + + /** + * 获取景区航线列表(分页) + */ + @GetMapping("/list/scenic/{scenicId}") + public Result> getRoutesByScenic( + @PathVariable Long scenicId, + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "20") Integer size) { + return Result.succeed(boatRouteService.listByScenicId(scenicId, page, size)); + } + + /** + * 绑定航线到设备 + */ + @PostMapping("/bind") + public Result bindRouteToDevice( + @RequestParam String routeId, + @RequestParam String deviceSn) { + boatRouteService.bindToDevice(routeId, deviceSn); + return Result.succeed("绑定成功"); + } + + /** + * 校验航线(边界检测) + */ + @PostMapping("/validate") + public Result validateRoute( + @RequestBody BoatRouteCreateDTO dto, + @RequestParam(required = false) String boundaryId) { + return Result.succeed(boatRouteService.validateRoute(dto, boundaryId)); + } + + /** + * 删除航线 + */ + @DeleteMapping("/{routeId}") + public Result deleteRoute(@PathVariable String routeId) { + boatRouteService.deleteRoute(routeId); + return Result.succeed("删除成功"); + } + + /** + * 保存为模板 + */ + @PostMapping("/template/{routeId}") + public Result saveAsTemplate( + @PathVariable String routeId, + @RequestParam String templateName) { + return Result.succeed(boatRouteService.saveAsTemplate(routeId, templateName)); + } + + /** + * 获取模板列表 + */ + @GetMapping("/templates") + public Result> getTemplates() { + return Result.succeed(boatRouteService.listTemplates()); + } +} +``` + +#### 4.1.2 order-center 任务系统扩展(核心集成点) + +**重要:无人船任务通过现有Mission系统统一管理,保持与无人机任务下发流程一致。** + +##### 4.1.2.1 MissionType枚举扩展 +```java +// 文件路径: order-center/src/main/java/com/central/order/mission/enums/MissionType.java +package com.central.order.mission.enums; + +@Getter +public enum MissionType implements ZltEnum { + WAYLINE(1, "航线任务"), + TAKEOFF(2, "一键起飞任务"), + BOAT_ROUTE(3, "无人船航线任务"); // 新增 + + // ... 现有代码 ... + + /** + * 判断是否为无人船航线任务 + */ + public static boolean isBoatRouteTask(Integer type) { + return type != null && type.equals(BOAT_ROUTE.getId()); + } +} +``` + +##### 4.1.2.2 Mission实体扩展 +```java +// 文件路径: order-center/src/main/java/com/central/order/mission/model/Mission.java +// 在现有字段基础上新增 + +@Schema(description = "无人船航线ID(无人船任务必填)") +private String boatRouteId; + +@Schema(description = "无人船航线名称") +private String boatRouteName; +``` + +##### 4.1.2.3 missions表扩展 +```sql +-- 在missions表新增字段 +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`; + +-- 添加索引 +ALTER TABLE `missions` ADD INDEX `idx_boat_route_id` (`boat_route_id`); +``` + +##### 4.1.2.4 MissionController扩展(无需修改) +```java +// 文件路径: order-center/src/main/java/com/central/order/mission/controller/MissionController.java +// 现有saveMission接口已支持,只需在参数校验中增加BOAT_ROUTE类型判断 + +@PostMapping("/saveMission") +public Result saveMission(@RequestBody Mission mission) { + // ... 现有代码 ... + + // 根据任务类型校验必填参数(新增无人船航线判断) + if (MissionType.isWaylineTask(missionType)) { + if (!StringUtils.hasText(mission.getWaylineId())) { + return Result.failed("航线ID不能为空"); + } + } else if (MissionType.isTakeoffTask(missionType)) { + // ... 现有代码 ... + } else if (MissionType.isBoatRouteTask(missionType)) { // 新增 + if (!StringUtils.hasText(mission.getBoatRouteId())) { + return Result.failed("无人船航线ID不能为空"); + } + } else { + return Result.failed("无效的任务类型"); + } + + // ... 后续流程与现有逻辑一致 ... +} +``` + +##### 4.1.2.5 MissionServiceImpl扩展(核心下发逻辑) +```java +// 文件路径: order-center/src/main/java/com/central/order/mission/service/impl/MissionServiceImpl.java +// 在dispatchMissionToDevice方法中新增无人船任务下发逻辑 + +@Override +public boolean dispatchMissionToDevice(Mission mission) { + try { + Integer missionType = mission.getMissionType(); + + if (MissionType.isWaylineTask(missionType)) { + // 无人机航线任务(现有逻辑) + log.info("下发航线任务到设备: missionCode={}, deviceSn={}, waylineId={}", + mission.getMissionCode(), mission.getDeviceSn(), mission.getWaylineId()); + Result result = deviceCenterService.executeWayline( + mission.getDeviceSn(), + mission.getWaylineId(), + mission.getMissionCode() + ); + if (result != null && result.getResp_code() == 0) { + updateMissionStatus(mission.getMissionCode(), MissionStatus.DOING.getId()); + log.info("航线任务下发成功: missionCode={}", mission.getMissionCode()); + return true; + } else { + String errorMsg = result != null ? result.getResp_msg() : "设备中心服务调用失败"; + log.error("航线任务下发失败: missionCode={}, error={}", mission.getMissionCode(), errorMsg); + return false; + } + + } else if (MissionType.isTakeoffTask(missionType)) { + // 一键起飞任务(现有逻辑) + // ... 现有代码 ... + + } else if (MissionType.isBoatRouteTask(missionType)) { + // ============ 无人船航线任务(新增) ============ + log.info("下发无人船航线任务到设备: missionCode={}, deviceSn={}, boatRouteId={}", + mission.getMissionCode(), mission.getDeviceSn(), mission.getBoatRouteId()); + + Result result = deviceCenterService.executeBoatRoute( + mission.getDeviceSn(), + mission.getBoatRouteId(), + mission.getMissionCode() + ); + + if (result != null && result.getResp_code() == 0) { + updateMissionStatus(mission.getMissionCode(), MissionStatus.DOING.getId()); + log.info("无人船航线任务下发成功: missionCode={}", mission.getMissionCode()); + return true; + } else { + String errorMsg = result != null ? result.getResp_msg() : "设备中心服务调用失败"; + log.error("无人船航线任务下发失败: missionCode={}, error={}", mission.getMissionCode(), errorMsg); + return false; + } + // ============================================ + + } else { + log.error("未知的任务类型: {}", missionType); + return false; + } + return false; + } catch (Exception e) { + log.error("下发任务到设备失败: missionCode={}", mission.getMissionCode(), e); + return false; + } +} +``` + +##### 4.1.2.6 DeviceCenterService Feign接口扩展 +```java +// 文件路径: order-center/src/main/java/com/central/order/feign/DeviceCenterService.java +// 新增无人船航线执行接口 + +/** + * 执行无人船航线任务 + * @param deviceSn 设备序列号 + * @param boatRouteId 无人船航线ID + * @param missionCode 任务编码 + * @return 执行结果 + */ +@PostMapping("/device/boat/command/route/execute") +Result executeBoatRoute( + @RequestParam("deviceSn") String deviceSn, + @RequestParam("boatRouteId") String boatRouteId, + @RequestParam("missionCode") String missionCode +); + +/** + * 暂停无人船航行 + */ +@PostMapping("/device/boat/command/pause") +Result pauseBoatNavigation(@RequestParam("deviceSn") String deviceSn); + +/** + * 恢复无人船航行 + */ +@PostMapping("/device/boat/command/resume") +Result resumeBoatNavigation(@RequestParam("deviceSn") String deviceSn); + +/** + * 无人船返回起点 + */ +@PostMapping("/device/boat/command/return") +Result returnBoatToStart(@RequestParam("deviceSn") String deviceSn); + +/** + * 无人船紧急停止 + */ +@PostMapping("/device/boat/command/emergency-stop") +Result emergencyStopBoat(@RequestParam("deviceSn") String deviceSn); +``` + +##### 4.1.2.7 DeviceCenterServiceFallbackFactory扩展 +```java +// 文件路径: order-center/src/main/java/com/central/order/feign/fallback/DeviceCenterServiceFallbackFactory.java +// 在fallback实现中新增对应方法 + +@Override +public Result executeBoatRoute(String deviceSn, String boatRouteId, String missionCode) { + log.error("executeBoatRoute fallback: deviceSn={}, boatRouteId={}, missionCode={}", + deviceSn, boatRouteId, missionCode); + return Result.failed("设备中心服务不可用"); +} + +@Override +public Result pauseBoatNavigation(String deviceSn) { + log.error("pauseBoatNavigation fallback: deviceSn={}", deviceSn); + return Result.failed("设备中心服务不可用"); +} + +// ... 其他fallback方法 ... +``` + +--- + +#### 4.1.3 BoatCommandController.java (device-center,接收Feign调用) +```java +package com.central.device.controller; + +@RestController +@RequestMapping("/device/boat/command") +@RequiredArgsConstructor +@Slf4j +public class BoatCommandController { + + private final IBoatControlService boatControlService; + private final IBoatRouteService boatRouteService; + + /** + * 执行航线任务(供order-center Feign调用) + * @param deviceSn 设备序列号 + * @param boatRouteId 无人船航线ID + * @param missionCode 任务编码(来自Mission系统) + */ + @PostMapping("/route/execute") + public Result executeRoute( + @RequestParam String deviceSn, + @RequestParam String boatRouteId, + @RequestParam String missionCode) { + try { + log.info("接收无人船航线执行请求: deviceSn={}, boatRouteId={}, missionCode={}", + deviceSn, boatRouteId, missionCode); + + // 1. 获取航线详情 + BoatRoute route = boatRouteService.getByRouteId(boatRouteId); + if (route == null) { + return Result.failed("航线不存在: " + boatRouteId); + } + + // 2. 校验设备是否绑定了该航线 + if (!deviceSn.equals(route.getDeviceSn())) { + return Result.failed("航线未绑定到该设备"); + } + + // 3. 执行航线任务 + String taskId = boatControlService.executeRoute(deviceSn, boatRouteId, missionCode); + + log.info("无人船航线任务执行成功: missionCode={}, taskId={}", missionCode, taskId); + return Result.succeed(taskId, "航线任务已下发"); + + } catch (Exception e) { + log.error("无人船航线任务执行失败: missionCode={}", missionCode, e); + return Result.failed("航线任务执行失败: " + e.getMessage()); + } + } + + /** + * 暂停航行 + */ + @PostMapping("/pause") + public Result pauseNavigation(@RequestParam String deviceSn) { + boatControlService.pause(deviceSn); + return Result.succeed("暂停成功"); + } + + /** + * 恢复航行 + */ + @PostMapping("/resume") + public Result resumeNavigation(@RequestParam String deviceSn) { + boatControlService.resume(deviceSn); + return Result.succeed("恢复成功"); + } + + /** + * 返回起点 + */ + @PostMapping("/return") + public Result returnToStart(@RequestParam String deviceSn) { + boatControlService.returnToStart(deviceSn); + return Result.succeed("返航指令已下发"); + } + + /** + * 紧急停止 + */ + @PostMapping("/emergency-stop") + public Result emergencyStop(@RequestParam String deviceSn) { + boatControlService.emergencyStop(deviceSn); + return Result.succeed("紧急停止成功"); + } + + /** + * 手动控制(遥控) + */ + @PostMapping("/manual") + public Result manualControl( + @RequestParam String deviceSn, + @RequestBody BoatManualControlDTO dto) { + boatControlService.manualControl(deviceSn, dto); + return Result.succeed(); + } +} +``` + +#### 4.1.3 WaterBoundaryController.java +```java +package com.central.device.controller; + +@RestController +@RequestMapping("/device/water/boundary") +@RequiredArgsConstructor +public class WaterBoundaryController { + + private final IWaterBoundaryService waterBoundaryService; + + /** + * 创建水域边界 + */ + @PostMapping("/create") + public Result createBoundary(@RequestBody @Valid WaterBoundaryCreateDTO dto) { + return Result.succeed(waterBoundaryService.createBoundary(dto)); + } + + /** + * 获取景区水域边界列表 + */ + @GetMapping("/list/{scenicId}") + public Result> getBoundaries(@PathVariable Long scenicId) { + return Result.succeed(waterBoundaryService.listByScenicId(scenicId)); + } + + /** + * 检测点是否在水域内 + */ + @PostMapping("/check/point") + public Result checkPointInWater( + @RequestParam String boundaryId, + @RequestParam Double longitude, + @RequestParam Double latitude) { + return Result.succeed(waterBoundaryService.isPointInBoundary(boundaryId, longitude, latitude)); + } + + /** + * 检测航线是否在水域内 + */ + @PostMapping("/check/route") + public Result checkRouteInWater( + @RequestParam String boundaryId, + @RequestBody List waypoints) { + return Result.succeed(waterBoundaryService.checkRouteInBoundary(boundaryId, waypoints)); + } + + /** + * 从3D模型识别水域边界(异步) + */ + @PostMapping("/detect/model/{modelId}") + public Result detectFromModel( + @PathVariable String modelId, + @RequestParam Long scenicId) { + String taskId = waterBoundaryService.detectFromModelAsync(modelId, scenicId); + return Result.succeed(taskId, "边界识别任务已提交"); + } +} +``` + +#### 4.1.4 BoatTrackController.java +```java +package com.central.device.controller; + +@RestController +@RequestMapping("/device/boat/track") +@RequiredArgsConstructor +public class BoatTrackController { + + private final IBoatTrackService boatTrackService; + + /** + * 获取实时位置 + */ + @GetMapping("/realtime/{deviceSn}") + public Result getRealtimePosition(@PathVariable String deviceSn) { + return Result.succeed(boatTrackService.getRealtimePosition(deviceSn)); + } + + /** + * 获取历史轨迹 + */ + @GetMapping("/history/{deviceSn}") + public Result> getHistoryTrack( + @PathVariable String deviceSn, + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime, + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) { + return Result.succeed(boatTrackService.getHistoryTrack(deviceSn, startTime, endTime)); + } + + /** + * 获取任务执行轨迹 + */ + @GetMapping("/task/{taskId}") + public Result getTaskTrack(@PathVariable String taskId) { + return Result.succeed(boatTrackService.getTaskTrack(taskId)); + } +} +``` + +### 4.2 Service层核心实现 + +#### 4.2.1 BoatRouteServiceImpl.java (核心逻辑) +```java +@Service +@RequiredArgsConstructor +@Slf4j +public class BoatRouteServiceImpl extends ServiceImpl + implements IBoatRouteService { + + private final BoatWaypointMapper waypointMapper; + private final IWaterBoundaryService boundaryService; + + @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.setCruiseSpeed(dto.getCruiseSpeed()); + route.setLoopEnabled(dto.getLoopEnabled()); + route.setLoopCount(dto.getLoopCount()); + route.setReturnMode(dto.getReturnMode()); + route.setTenantId(LoginUserContextHolder.getTenantId()); + route.setStatus(0); // 草稿状态 + + // 2. 计算航线统计信息 + List waypoints = dto.getWaypoints(); + route.setWaypointCount(waypoints.size()); + + // 计算总距离 + double totalDistance = calculateTotalDistance(waypoints); + route.setTotalDistance(BigDecimal.valueOf(totalDistance)); + + // 计算预计时长 + 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); + + log.info("航线创建成功: routeId={}, name={}, waypointCount={}", + route.getRouteId(), route.getRouteName(), waypoints.size()); + + return route.getRouteId(); + } + + private void saveWaypoints(String routeId, List waypoints) { + List 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()); + entity.setStayDuration(dto.getStayDuration()); + entity.setTurnMode(dto.getTurnMode()); + entity.setPointName(dto.getPointName()); + + // 自动计算航向角(指向下一个航点) + 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)); + } + + entities.add(entity); + } + waypointMapper.insertBatch(entities); + } + + /** + * 计算两点间距离(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 + } + + @Override + public RouteValidateResultVO validateRoute(BoatRouteCreateDTO dto, String boundaryId) { + RouteValidateResultVO result = new RouteValidateResultVO(); + result.setValid(true); + result.setWarnings(new ArrayList<>()); + result.setErrors(new ArrayList<>()); + + List waypoints = dto.getWaypoints(); + + // 1. 检查航点是否在水域边界内 + if (StringUtils.hasText(boundaryId)) { + for (int i = 0; i < waypoints.size(); i++) { + BoatWaypointDTO wp = waypoints.get(i); + boolean inBoundary = boundaryService.isPointInBoundary( + boundaryId, wp.getLongitude().doubleValue(), wp.getLatitude().doubleValue() + ); + if (!inBoundary) { + result.setValid(false); + result.getErrors().add(String.format("航点%d超出水域边界", i + 1)); + } + } + + // 2. 检查航线段是否穿过边界外区域 + BoundaryCheckResultVO lineCheck = boundaryService.checkRouteInBoundary( + boundaryId, + waypoints.stream() + .map(w -> new PointDTO(w.getLongitude().doubleValue(), w.getLatitude().doubleValue())) + .collect(Collectors.toList()) + ); + if (!lineCheck.getAllInBoundary()) { + result.setValid(false); + result.getErrors().addAll(lineCheck.getOutOfBoundarySegments()); + } + } + + // 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.getWarnings().add(String.format("航点%d和%d间距过近(%.1fm)", i + 1, i + 2, distance)); + } + if (distance > 1000) { + result.getWarnings().add(String.format("航点%d和%d间距过远(%.0fm),建议增加中间点", i + 1, i + 2, distance)); + } + } + + // 4. 检查总航程 + double totalDistance = calculateTotalDistance(waypoints); + if (totalDistance > 10000) { + result.getWarnings().add(String.format("总航程较长(%.0fm),请确认电量充足", totalDistance)); + } + + return result; + } +} +``` + +#### 4.2.2 WaterBoundaryServiceImpl.java (边界检测) +```java +@Service +@RequiredArgsConstructor +@Slf4j +public class WaterBoundaryServiceImpl extends ServiceImpl + implements IWaterBoundaryService { + + /** + * 检测点是否在多边形边界内 + * 使用射线法(Ray Casting Algorithm) + */ + @Override + public boolean isPointInBoundary(String boundaryId, Double longitude, Double latitude) { + WaterBoundary boundary = this.getById(boundaryId); + if (boundary == null) { + throw new BusinessException("边界不存在"); + } + + // 解析GeoJSON多边形 + List polygon = parseGeoJsonPolygon(boundary.getPolygonData()); + + return isPointInPolygon(longitude, latitude, polygon); + } + + /** + * 射线法判断点是否在多边形内 + */ + private boolean isPointInPolygon(double x, double y, List polygon) { + int n = polygon.size(); + boolean inside = false; + + for (int i = 0, j = n - 1; i < n; j = i++) { + double xi = polygon.get(i)[0], yi = polygon.get(i)[1]; + double xj = polygon.get(j)[0], yj = polygon.get(j)[1]; + + if (((yi > y) != (yj > y)) && + (x < (xj - xi) * (y - yi) / (yj - yi) + xi)) { + inside = !inside; + } + } + + return inside; + } + + /** + * 检测航线是否完全在边界内 + */ + @Override + public BoundaryCheckResultVO checkRouteInBoundary(String boundaryId, List waypoints) { + BoundaryCheckResultVO result = new BoundaryCheckResultVO(); + result.setAllInBoundary(true); + result.setOutOfBoundarySegments(new ArrayList<>()); + + WaterBoundary boundary = this.getById(boundaryId); + List polygon = parseGeoJsonPolygon(boundary.getPolygonData()); + + // 检查每个航点 + for (int i = 0; i < waypoints.size(); i++) { + PointDTO point = waypoints.get(i); + if (!isPointInPolygon(point.getLongitude(), point.getLatitude(), polygon)) { + result.setAllInBoundary(false); + result.getOutOfBoundarySegments().add(String.format("航点%d超出边界", i + 1)); + } + } + + // 检查航线段是否穿过边界 + for (int i = 0; i < waypoints.size() - 1; i++) { + PointDTO p1 = waypoints.get(i); + PointDTO p2 = waypoints.get(i + 1); + + // 对航线段进行插值检测 + int interpolateCount = 10; + for (int j = 1; j < interpolateCount; j++) { + double ratio = (double) j / interpolateCount; + double lng = p1.getLongitude() + (p2.getLongitude() - p1.getLongitude()) * ratio; + double lat = p1.getLatitude() + (p2.getLatitude() - p1.getLatitude()) * ratio; + + if (!isPointInPolygon(lng, lat, polygon)) { + result.setAllInBoundary(false); + result.getOutOfBoundarySegments().add( + String.format("航线段%d-%d穿过边界外区域", i + 1, i + 2) + ); + break; + } + } + } + + return result; + } + + private List parseGeoJsonPolygon(String geoJson) { + // 解析GeoJSON格式的多边形坐标 + JSONObject json = JSON.parseObject(geoJson); + JSONArray coordinates = json.getJSONArray("coordinates").getJSONArray(0); + + List polygon = new ArrayList<>(); + for (int i = 0; i < coordinates.size(); i++) { + JSONArray point = coordinates.getJSONArray(i); + polygon.add(new double[]{point.getDoubleValue(0), point.getDoubleValue(1)}); + } + return polygon; + } +} +``` + +### 4.3 SSE实时推送 + +#### 4.3.1 BoatTelemetrySSEController.java +```java +@RestController +@RequestMapping("/sse/boat") +@RequiredArgsConstructor +@Slf4j +public class BoatTelemetrySSEController { + + private final DeviceSubscriptionManager subscriptionManager; + private final IBoatTrackService trackService; + + /** + * 订阅无人船遥测数据 + */ + @GetMapping(value = "/telemetry/{deviceSn}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public SseEmitter subscribeTelemetry(@PathVariable String deviceSn) { + SseEmitter emitter = new SseEmitter(30 * 60 * 1000L); // 30分钟超时 + + // 注册SSE连接 + String connectionId = UUID.randomUUID().toString(); + + // 订阅设备消息 + subscriptionManager.subscribeDevice(deviceSn, LoginUserContextHolder.getTenantId()); + + // 注册消息回调 + trackService.registerTelemetryCallback(deviceSn, connectionId, data -> { + try { + emitter.send(SseEmitter.event() + .name("boat-telemetry") + .data(data)); + } catch (IOException e) { + emitter.completeWithError(e); + } + }); + + // 清理回调 + emitter.onCompletion(() -> { + trackService.unregisterTelemetryCallback(deviceSn, connectionId); + log.info("SSE连接关闭: deviceSn={}", deviceSn); + }); + + emitter.onTimeout(() -> { + trackService.unregisterTelemetryCallback(deviceSn, connectionId); + log.info("SSE连接超时: deviceSn={}", deviceSn); + }); + + return emitter; + } +} +``` + +--- + +## 5. 前端实现设计 + +### 5.1 航线编辑器组件 + +#### 5.1.1 RouteEditor组件结构 +``` +zlt-web/yingyan/src/pages/map3d/components/ +└── RouteEditor/ + ├── index.tsx # 主入口 + ├── RouteDrawer.tsx # 航线绘制器 + ├── WaypointEditor.tsx # 航点编辑器 + ├── RouteToolbar.tsx # 工具栏 + ├── RoutePreview.tsx # 航线预览 + ├── hooks/ + │ ├── useRouteDrawing.ts # 绘制逻辑Hook + │ └── useRouteValidation.ts # 验证逻辑Hook + └── types.ts # 类型定义 +``` + +#### 5.1.2 RouteEditor/index.tsx +```tsx +import React, { useState, useCallback, useEffect } from 'react'; +import { Card, Button, Space, message, Modal } from 'antd'; +import { + EditOutlined, + CheckOutlined, + CloseOutlined, + SaveOutlined, + PlayCircleOutlined +} from '@ant-design/icons'; +import RouteDrawer from './RouteDrawer'; +import WaypointEditor from './WaypointEditor'; +import RouteToolbar from './RouteToolbar'; +import { useRouteDrawing } from './hooks/useRouteDrawing'; +import { useRouteValidation } from './hooks/useRouteValidation'; +import { boatRouteApi } from '@/services/boatRoute'; +import type { BoatWaypoint, BoatRouteCreateDTO } from './types'; + +interface RouteEditorProps { + viewer: Cesium.Viewer; + deviceSn: string; + scenicId: number; + boundaryId?: string; + onSave?: (routeId: string) => void; + onCancel?: () => void; +} + +const RouteEditor: React.FC = ({ + viewer, + deviceSn, + scenicId, + boundaryId, + onSave, + onCancel +}) => { + const [isEditing, setIsEditing] = useState(false); + const [waypoints, setWaypoints] = useState([]); + const [selectedWaypointIndex, setSelectedWaypointIndex] = useState(null); + const [routeConfig, setRouteConfig] = useState({ + routeName: '', + cruiseSpeed: 2.0, + loopEnabled: false, + loopCount: 1, + returnMode: 'return_start' + }); + + // 绘制逻辑 + const { + startDrawing, + stopDrawing, + addWaypoint, + updateWaypoint, + removeWaypoint, + clearWaypoints, + routeEntities + } = useRouteDrawing(viewer, waypoints, setWaypoints); + + // 验证逻辑 + const { + validateRoute, + validationResult, + isValidating + } = useRouteValidation(boundaryId); + + // 开始编辑 + const handleStartEdit = useCallback(() => { + setIsEditing(true); + startDrawing(); + }, [startDrawing]); + + // 取消编辑 + const handleCancelEdit = useCallback(() => { + Modal.confirm({ + title: '确认取消', + content: '取消后已绘制的航线将丢失,确定取消吗?', + onOk: () => { + setIsEditing(false); + stopDrawing(); + clearWaypoints(); + onCancel?.(); + } + }); + }, [stopDrawing, clearWaypoints, onCancel]); + + // 保存航线 + const handleSave = useCallback(async () => { + if (waypoints.length < 2) { + message.error('航线至少需要2个航点'); + return; + } + + if (!routeConfig.routeName) { + message.error('请输入航线名称'); + return; + } + + // 验证航线 + const validation = await validateRoute(waypoints); + if (!validation.valid) { + Modal.error({ + title: '航线验证失败', + content: ( +
+ {validation.errors.map((err, i) => ( +
{err}
+ ))} +
+ ) + }); + return; + } + + // 提交保存 + try { + const dto: BoatRouteCreateDTO = { + routeName: routeConfig.routeName, + deviceSn, + scenicId, + cruiseSpeed: routeConfig.cruiseSpeed, + loopEnabled: routeConfig.loopEnabled, + loopCount: routeConfig.loopCount, + returnMode: routeConfig.returnMode, + waypoints: waypoints.map((wp, index) => ({ + longitude: wp.longitude, + latitude: wp.latitude, + speed: wp.speed, + stayDuration: wp.stayDuration || 0, + turnMode: wp.turnMode || 'smooth', + pointName: wp.pointName || `航点${index + 1}`, + actions: wp.actions + })) + }; + + const routeId = await boatRouteApi.createRoute(dto); + message.success('航线保存成功'); + setIsEditing(false); + stopDrawing(); + onSave?.(routeId); + } catch (error) { + message.error('保存失败: ' + error.message); + } + }, [waypoints, routeConfig, deviceSn, scenicId, validateRoute, stopDrawing, onSave]); + + return ( + + + + + ) : ( + + ) + } + > + {isEditing && ( + <> + + + + + {validationResult && !validationResult.valid && ( +
+ {validationResult.errors.map((err, i) => ( +
{err}
+ ))} +
+ )} + + {validationResult?.warnings?.length > 0 && ( +
+ {validationResult.warnings.map((warn, i) => ( +
{warn}
+ ))} +
+ )} + + )} +
+ ); +}; + +export default RouteEditor; +``` + +#### 5.1.3 hooks/useRouteDrawing.ts +```tsx +import { useCallback, useRef, useEffect } from 'react'; +import * as Cesium from 'cesium'; +import type { BoatWaypoint } from '../types'; + +export function useRouteDrawing( + viewer: Cesium.Viewer, + waypoints: BoatWaypoint[], + setWaypoints: React.Dispatch> +) { + const isDrawingRef = useRef(false); + const routeEntityRef = useRef(null); + const waypointEntitiesRef = useRef([]); + const handlerRef = useRef(null); + + // 更新航线渲染 + const updateRouteVisualization = useCallback(() => { + if (!viewer) return; + + // 清除旧的航线实体 + if (routeEntityRef.current) { + viewer.entities.remove(routeEntityRef.current); + } + waypointEntitiesRef.current.forEach(entity => { + viewer.entities.remove(entity); + }); + waypointEntitiesRef.current = []; + + if (waypoints.length === 0) return; + + // 绘制航线(折线) + const positions = waypoints.map(wp => + Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0) + ); + + routeEntityRef.current = viewer.entities.add({ + polyline: { + positions, + width: 4, + material: new Cesium.PolylineGlowMaterialProperty({ + glowPower: 0.3, + color: Cesium.Color.CYAN + }), + clampToGround: true + } + }); + + // 绘制航点标记 + waypoints.forEach((wp, index) => { + const entity = viewer.entities.add({ + position: Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0), + point: { + pixelSize: index === 0 ? 14 : (index === waypoints.length - 1 ? 14 : 10), + color: index === 0 + ? Cesium.Color.LIME + : (index === waypoints.length - 1 ? Cesium.Color.RED : Cesium.Color.CYAN), + outlineColor: Cesium.Color.WHITE, + outlineWidth: 2, + heightReference: Cesium.HeightReference.CLAMP_TO_GROUND + }, + label: { + text: `${index + 1}`, + font: '12px sans-serif', + fillColor: Cesium.Color.WHITE, + outlineColor: Cesium.Color.BLACK, + outlineWidth: 2, + style: Cesium.LabelStyle.FILL_AND_OUTLINE, + verticalOrigin: Cesium.VerticalOrigin.BOTTOM, + pixelOffset: new Cesium.Cartesian2(0, -15), + heightReference: Cesium.HeightReference.CLAMP_TO_GROUND + } + }); + waypointEntitiesRef.current.push(entity); + }); + }, [viewer, waypoints]); + + // 监听航点变化更新渲染 + useEffect(() => { + updateRouteVisualization(); + }, [updateRouteVisualization]); + + // 开始绘制 + const startDrawing = useCallback(() => { + if (!viewer) return; + + isDrawingRef.current = true; + viewer.canvas.style.cursor = 'crosshair'; + + // 创建点击事件处理器 + handlerRef.current = new Cesium.ScreenSpaceEventHandler(viewer.canvas); + + // 左键点击添加航点 + handlerRef.current.setInputAction((event: { position: Cesium.Cartesian2 }) => { + if (!isDrawingRef.current) return; + + const cartesian = viewer.camera.pickEllipsoid(event.position, viewer.scene.globe.ellipsoid); + if (!cartesian) return; + + const cartographic = Cesium.Cartographic.fromCartesian(cartesian); + const longitude = Cesium.Math.toDegrees(cartographic.longitude); + const latitude = Cesium.Math.toDegrees(cartographic.latitude); + + const newWaypoint: BoatWaypoint = { + longitude, + latitude, + speed: null, + stayDuration: 0, + turnMode: 'smooth', + actions: [] + }; + + setWaypoints(prev => [...prev, newWaypoint]); + }, Cesium.ScreenSpaceEventType.LEFT_CLICK); + + // 右键撤销上一个航点 + handlerRef.current.setInputAction(() => { + setWaypoints(prev => prev.slice(0, -1)); + }, Cesium.ScreenSpaceEventType.RIGHT_CLICK); + + }, [viewer, setWaypoints]); + + // 停止绘制 + const stopDrawing = useCallback(() => { + isDrawingRef.current = false; + if (viewer) { + viewer.canvas.style.cursor = 'default'; + } + if (handlerRef.current) { + handlerRef.current.destroy(); + handlerRef.current = null; + } + }, [viewer]); + + // 添加航点 + const addWaypoint = useCallback((waypoint: BoatWaypoint) => { + setWaypoints(prev => [...prev, waypoint]); + }, [setWaypoints]); + + // 更新航点 + const updateWaypoint = useCallback((index: number, updates: Partial) => { + setWaypoints(prev => prev.map((wp, i) => + i === index ? { ...wp, ...updates } : wp + )); + }, [setWaypoints]); + + // 删除航点 + const removeWaypoint = useCallback((index: number) => { + setWaypoints(prev => prev.filter((_, i) => i !== index)); + }, [setWaypoints]); + + // 清空航点 + const clearWaypoints = useCallback(() => { + setWaypoints([]); + // 清除可视化 + if (routeEntityRef.current) { + viewer?.entities.remove(routeEntityRef.current); + routeEntityRef.current = null; + } + waypointEntitiesRef.current.forEach(entity => { + viewer?.entities.remove(entity); + }); + waypointEntitiesRef.current = []; + }, [viewer, setWaypoints]); + + // 清理 + useEffect(() => { + return () => { + stopDrawing(); + clearWaypoints(); + }; + }, []); + + return { + startDrawing, + stopDrawing, + addWaypoint, + updateWaypoint, + removeWaypoint, + clearWaypoints, + isDrawing: isDrawingRef.current, + routeEntities: waypointEntitiesRef.current + }; +} +``` + +### 5.2 API服务 + +#### 5.2.1 services/boatRoute.ts (航线CRUD) +```tsx +import request from '@/utils/request'; +import type { + BoatRouteCreateDTO, + BoatRouteDetailVO, + BoatRouteListVO, + RouteValidateResultVO +} from '@/types/boatRoute'; + +const BASE_URL = '/api-device/device/boat/route'; + +export const boatRouteApi = { + // 创建航线 + createRoute: (data: BoatRouteCreateDTO): Promise => { + return request.post(`${BASE_URL}/create`, data); + }, + + // 更新航线 + updateRoute: (routeId: string, data: Partial): Promise => { + return request.put(`${BASE_URL}/update/${routeId}`, data); + }, + + // 获取航线详情 + getRouteDetail: (routeId: string): Promise => { + return request.get(`${BASE_URL}/detail/${routeId}`); + }, + + // 获取设备航线列表 + getRoutesByDevice: (deviceSn: string): Promise => { + return request.get(`${BASE_URL}/list/device/${deviceSn}`); + }, + + // 绑定航线到设备 + bindToDevice: (routeId: string, deviceSn: string): Promise => { + return request.post(`${BASE_URL}/bind`, null, { params: { routeId, deviceSn } }); + }, + + // 验证航线 + validateRoute: (data: BoatRouteCreateDTO, boundaryId?: string): Promise => { + return request.post(`${BASE_URL}/validate`, data, { params: { boundaryId } }); + }, + + // 删除航线 + deleteRoute: (routeId: string): Promise => { + return request.delete(`${BASE_URL}/${routeId}`); + }, + + // 保存为模板 + saveAsTemplate: (routeId: string, templateName: string): Promise => { + return request.post(`${BASE_URL}/template/${routeId}`, null, { params: { templateName } }); + }, + + // 获取模板列表 + getTemplates: (): Promise => { + return request.get(`${BASE_URL}/templates`); + } +}; +``` + +#### 5.2.2 services/mission.ts (复用现有任务API) +```tsx +/** + * 任务管理API - 复用现有missionApi + * 无人船任务使用missionType=3 (BOAT_ROUTE) + */ +import request from '@/utils/request'; +import type { Mission, MissionListVO } from '@/types/mission'; + +const BASE_URL = '/api-order/mission'; + +// 任务类型枚举 +export const MissionType = { + WAYLINE: 1, // 无人机航线任务 + TAKEOFF: 2, // 一键起飞任务 + BOAT_ROUTE: 3, // 无人船航线任务(新增) +} as const; + +// 任务状态枚举 +export const MissionStatus = { + PENDING: 1, // 待执行 + CANCELED: 2, // 已取消 + COMPLETE: 3, // 执行完成 + DOING: 4, // 执行中 + UPLOADING: 5, // 图片上传中 + UPLOADED: 6, // 图片上传完成 +} as const; + +export const missionApi = { + /** + * 创建无人船航线任务 + * @param params 任务参数 + */ + createBoatRouteMission: (params: { + deviceSn: string; + boatRouteId: string; + boatRouteName: string; + missionName?: string; + tourismId?: number; + remark?: string; + }): Promise => { + return request.post(`${BASE_URL}/saveMission`, { + ...params, + missionType: MissionType.BOAT_ROUTE, + }); + }, + + /** + * 执行任务(适用于所有任务类型) + * @param missionCode 任务编码 + */ + executeMission: (missionCode: string): Promise => { + return request.post(`${BASE_URL}/executeMission`, { missionCode }); + }, + + /** + * 取消任务 + * @param missionCode 任务编码 + */ + cancelMission: (missionCode: string): Promise => { + return request.post(`${BASE_URL}/cancelMission`, { missionCode }); + }, + + /** + * 获取任务详情 + * @param missionCode 任务编码 + */ + getMission: (missionCode: string): Promise => { + return request.post(`${BASE_URL}/getMission`, { missionCode }); + }, + + /** + * 查询任务列表 + * @param params 查询参数 + */ + listMissions: (params: { + deviceSn?: string; + missionType?: number; + missionStatus?: number; + page?: number; + limit?: number; + }): Promise<{ data: MissionListVO[]; count: number }> => { + return request.post(`${BASE_URL}/listMission`, params); + }, + + /** + * 完成任务 + * @param missionCode 任务编码 + */ + completeMission: (missionCode: string): Promise => { + return request.post(`${BASE_URL}/completeMission`, { missionCode }); + }, + + /** + * 删除任务 + * @param missionCode 任务编码 + */ + deleteMission: (missionCode: string): Promise => { + return request.post(`${BASE_URL}/deleteMission`, { missionCode }); + }, +}; +``` + +#### 5.2.3 services/boatControl.ts (无人船控制指令) +```tsx +/** + * 无人船控制API - 直接调用device-center + * 用于暂停/恢复/返航/紧急停止等实时控制 + */ +import request from '@/utils/request'; + +const BASE_URL = '/api-device/device/boat/command'; + +export const boatControlApi = { + // 暂停航行 + pause: (deviceSn: string): Promise => { + return request.post(`${BASE_URL}/pause`, null, { params: { deviceSn } }); + }, + + // 恢复航行 + resume: (deviceSn: string): Promise => { + return request.post(`${BASE_URL}/resume`, null, { params: { deviceSn } }); + }, + + // 返回起点 + returnToStart: (deviceSn: string): Promise => { + return request.post(`${BASE_URL}/return`, null, { params: { deviceSn } }); + }, + + // 紧急停止 + emergencyStop: (deviceSn: string): Promise => { + return request.post(`${BASE_URL}/emergency-stop`, null, { params: { deviceSn } }); + }, + + // 手动控制 + manualControl: (deviceSn: string, params: { + throttle?: number; // 油门 (前进/后退) + rudder?: number; // 舵角 (左转/右转) + }): Promise => { + return request.post(`${BASE_URL}/manual`, params, { params: { deviceSn } }); + }, +}; +``` + +### 5.3 SSE遥测订阅Hook + +#### 5.3.1 hooks/useBoatSSE.ts +```tsx +import { useEffect, useRef, useCallback, useState } from 'react'; +import type { BoatTelemetryData } from '@/types/boatRoute'; + +interface UseBoatSSEOptions { + deviceSn: string; + enabled?: boolean; + onData?: (data: BoatTelemetryData) => void; +} + +export function useBoatSSE({ deviceSn, enabled = true, onData }: UseBoatSSEOptions) { + const [telemetry, setTelemetry] = useState(null); + const [connected, setConnected] = useState(false); + const [error, setError] = useState(null); + const eventSourceRef = useRef(null); + const reconnectTimeoutRef = useRef(null); + const reconnectAttempts = useRef(0); + + const connect = useCallback(() => { + if (!deviceSn || !enabled) return; + + const url = `/api-device/sse/boat/telemetry/${deviceSn}`; + const eventSource = new EventSource(url); + eventSourceRef.current = eventSource; + + eventSource.onopen = () => { + setConnected(true); + setError(null); + reconnectAttempts.current = 0; + console.log(`[BoatSSE] 连接成功: ${deviceSn}`); + }; + + eventSource.addEventListener('boat-telemetry', (event) => { + try { + const data: BoatTelemetryData = JSON.parse(event.data); + setTelemetry(data); + onData?.(data); + } catch (e) { + console.error('[BoatSSE] 解析数据失败:', e); + } + }); + + eventSource.addEventListener('heartbeat', () => { + // 心跳,静默处理 + }); + + eventSource.onerror = (e) => { + console.error('[BoatSSE] 连接错误:', e); + setConnected(false); + eventSource.close(); + + // 重连逻辑 + if (reconnectAttempts.current < 10) { + const delay = Math.min(2000 * Math.pow(1.5, reconnectAttempts.current), 30000); + reconnectTimeoutRef.current = setTimeout(() => { + reconnectAttempts.current++; + connect(); + }, delay); + } else { + setError('连接失败,已达最大重试次数'); + } + }; + }, [deviceSn, enabled, onData]); + + const disconnect = useCallback(() => { + if (eventSourceRef.current) { + eventSourceRef.current.close(); + eventSourceRef.current = null; + } + if (reconnectTimeoutRef.current) { + clearTimeout(reconnectTimeoutRef.current); + reconnectTimeoutRef.current = null; + } + setConnected(false); + }, []); + + useEffect(() => { + if (enabled && deviceSn) { + connect(); + } + return () => { + disconnect(); + }; + }, [deviceSn, enabled, connect, disconnect]); + + return { + telemetry, + connected, + error, + reconnect: connect, + disconnect + }; +} +``` + +--- + +## 6. 交互流程设计 + +### 6.1 航线规划流程 + +``` +┌─────────────────────────────────────────────────────────────────────────────┐ +│ 航线规划交互流程 │ +└─────────────────────────────────────────────────────────────────────────────┘ + +用户 前端(yingyan) 后端(device-center) + │ │ │ + │ 1. 点击"开始规划" │ │ + │─────────────────────────────>│ │ + │ │ │ + │ │ 2. 进入绘制模式 │ + │ │ - 切换鼠标为十字光标 │ + │ │ - 加载水域边界(可选) │ + │ │ │ + │ 3. 点击地图添加航点 │ │ + │─────────────────────────────>│ │ + │ │ │ + │ │ 4. 实时渲染航点和航线 │ + │<─────────────────────────────│ │ + │ │ │ + │ 5. 右键撤销/调整航点 │ │ + │─────────────────────────────>│ │ + │ │ │ + │ 6. 点击航点编辑参数 │ │ + │─────────────────────────────>│ │ + │ │ │ + │ │ 7. 弹出航点配置面板 │ + │ │ - 速度、停留时间、动作 │ + │<─────────────────────────────│ │ + │ │ │ + │ 8. 配置航线参数 │ │ + │ (名称、循环、巡航速度) │ │ + │─────────────────────────────>│ │ + │ │ │ + │ 9. 点击"保存" │ │ + │─────────────────────────────>│ │ + │ │ │ + │ │ 10. 调用验证接口 │ + │ │─────────────────────────────────>│ + │ │ │ + │ │ 11. 返回验证结果 │ + │ │<─────────────────────────────────│ + │ │ │ + │ │ 12. 验证通过则调用创建接口 │ + │ │─────────────────────────────────>│ + │ │ │ + │ │ 13. 返回航线ID │ + │ │<─────────────────────────────────│ + │ │ │ + │ 14. 提示保存成功 │ │ + │<─────────────────────────────│ │ + │ │ │ +``` + +### 6.2 航线任务执行流程(与无人机一致) + +**核心流程:前端 → order-center(Mission) → device-center → IoT平台 → 设备** + +``` +┌─────────────────────────────────────────────────────────────────────────────┐ +│ 航线任务执行流程(复用Mission系统) │ +└─────────────────────────────────────────────────────────────────────────────┘ + +用户 前端(yingyan) order-center device-center + │ │ │ │ + │ 1. 选择航线 │ │ │ + │ 点击"创建任务" │ │ │ + │───────────────────────>│ │ │ + │ │ │ │ + │ │ 2. 调用saveMission │ │ + │ │ missionType=3 │ │ + │ │ (BOAT_ROUTE) │ │ + │ │──────────────────────>│ │ + │ │ │ │ + │ │ │ 3. 创建Mission记录 │ + │ │ │ 状态=PENDING(1) │ + │ │ │ │ + │ │ 4. 返回Mission对象 │ │ + │ │ 含missionCode │ │ + │ │<──────────────────────│ │ + │ │ │ │ + │ 5. 显示任务创建成功 │ │ │ + │ "请确认执行" │ │ │ + │<───────────────────────│ │ │ + │ │ │ │ + │ 6. 点击"执行任务" │ │ │ + │───────────────────────>│ │ │ + │ │ │ │ + │ │ 7. 调用executeMission │ │ + │ │──────────────────────>│ │ + │ │ │ │ + │ │ │ 8. dispatchMissionToDevice + │ │ │ 判断missionType=3 │ + │ │ │ │ + │ │ │ 9. Feign调用 │ + │ │ │ executeBoatRoute │ + │ │ │─────────────────────>│ + │ │ │ │ + │ │ │ │ 10. 获取航线详情 + │ │ │ │ 构建控制命令 + │ │ │ │ + │ │ │ │ 11. WebSocket + │ │ │ │ 下发到IoT平台 + │ │ │ │ ───────────> + │ │ │ │ + │ │ │ 12. 返回执行结果 │ + │ │ │<─────────────────────│ + │ │ │ │ + │ │ │ 13. 更新Mission状态 │ + │ │ │ DOING(4) │ + │ │ │ │ + │ │ 14. 返回"任务已下发" │ │ + │ │<──────────────────────│ │ + │ │ │ │ + │ 15. 显示执行中状态 │ │ │ + │<───────────────────────│ │ │ + │ │ │ │ + │ │ 16. 建立SSE连接 │ │ + │ │ 订阅遥测数据 │ │ + │ │─────────────────────────────────────────────>│ + │ │ │ │ + │ 17. 实时显示船只位置 │ <───── SSE推送 ─────────────────────────────│ + │<───────────────────────│ │ │ + │ │ │ │ +``` + +### 6.3 任务状态流转 + +``` +┌─────────────────────────────────────────────────────────────────────────────┐ +│ Mission任务状态流转图 │ +└─────────────────────────────────────────────────────────────────────────────┘ + + ┌─────────────┐ + │ 创建任务 │ + │ saveMission │ + └──────┬──────┘ + │ + ▼ + ┌─────────────┐ + │ PENDING(1) │ ◄──────────────────┐ + │ 待执行 │ │ + └──────┬──────┘ │ + │ │ + ┌────────────────┼────────────────┐ │ + │ │ │ │ + ▼ ▼ │ │ + ┌─────────────┐ ┌─────────────┐ │ │ + │ CANCELED(2) │ │executeMission│ │ │ + │ 已取消 │ │ 执行任务 │ │ │ + └─────────────┘ └──────┬──────┘ │ │ + │ │ │ + ▼ │ │ + ┌─────────────┐ │ │ + │ DOING(4) │ │ │ + │ 执行中 │────────┘ │ + └──────┬──────┘ (执行失败可重试) │ + │ │ + ▼ │ + ┌─────────────┐ │ + │UPLOADING(5) │ │ + │ 图片上传中 │ │ + └──────┬──────┘ │ + │ │ + ▼ │ + ┌─────────────┐ │ + │ UPLOADED(6) │ │ + │图片上传完成 │ │ + └──────┬──────┘ │ + │ │ + ▼ │ + ┌─────────────┐ │ + │ COMPLETE(3) │ │ + │ 执行完成 │ │ + └─────────────┘ │ + │ + (任务完成后可创建新任务) ───────────┘ + +状态说明: +- PENDING(1): 任务创建后的初始状态,等待用户确认执行 +- CANCELED(2): 用户取消任务(仅PENDING状态可取消) +- DOING(4): 任务正在执行中 +- UPLOADING(5): 任务执行完成,正在上传采集的图片/视频 +- UPLOADED(6): 图片/视频上传完成 +- COMPLETE(3): 任务完全完成 +``` + +### 6.4 与无人机任务对比 + +| 流程步骤 | 无人机任务 | 无人船任务 | +|---------|-----------|-----------| +| 1. 创建任务 | saveMission(missionType=1) | saveMission(missionType=3) | +| 2. 执行任务 | executeMission | executeMission (相同) | +| 3. 任务下发 | deviceCenterService.executeWayline | deviceCenterService.executeBoatRoute | +| 4. 状态更新 | updateMissionStatus | updateMissionStatus (相同) | +| 5. 任务取消 | cancelMission | cancelMission (相同) | +| 6. 任务完成 | completeMission | completeMission (相同) | +| 7. 实时控制 | pause/resume/return | pause/resume/return (接口不同) | + +--- + +## 7. 安全与性能考虑 + +### 7.1 安全措施 + +| 安全项 | 措施 | +|-------|------| +| 接口鉴权 | OAuth2 + JWT Token验证 | +| 数据隔离 | 多租户数据隔离(tenantId) | +| 参数校验 | 后端@Valid + 自定义校验器 | +| 边界检测 | 航线规划时强制边界检测 | +| 操作审计 | 关键操作记录日志 | +| 紧急停止 | 提供紧急停止按钮(最高优先级) | + +### 7.2 性能优化 + +| 优化项 | 方案 | +|-------|------| +| 轨迹存储 | 批量写入 + 定时归档历史数据 | +| 实时推送 | SSE分级推送(低频状态 + 高频位置) | +| 地图渲染 | Cesium LOD + 按需加载航线 | +| 边界检测 | 预计算边界包围盒快速排除 | +| 缓存 | Redis缓存设备实时位置 | + +### 7.3 扩展性设计 + +``` +扩展点: +├─ 设备类型扩展 +│ └─ 通过deviceType区分无人船/无人机,复用核心航线逻辑 +├─ 动作类型扩展 +│ └─ 航点动作通过JSON配置,易于添加新动作类型 +├─ 边界检测算法扩展 +│ └─ 策略模式,支持更复杂的障碍物检测算法 +└─ 模型识别扩展 + └─ 预留接口,后续可接入AI边界识别服务 +``` + +--- + +## 8. 实施计划 + +### 8.1 阶段划分 + +| 阶段 | 内容 | 关键产出 | +|-----|------|---------| +| Phase 1 | 数据模型 + 基础CRUD | 数据库表、实体类、基础接口 | +| Phase 2 | 前端航线编辑器 | RouteEditor组件、绘制交互 | +| Phase 3 | 边界检测服务 | 水域边界管理、航线验证 | +| Phase 4 | 设备控制集成 | 命令下发、状态订阅 | +| Phase 5 | 实时轨迹展示 | SSE订阅、轨迹渲染 | +| Phase 6 | 优化与测试 | 性能优化、边界测试 | + +### 8.2 核心文件清单 + +``` +====================================================================== + order-center 扩展文件 +====================================================================== + +修改文件: +├─ src/main/java/com/central/order/mission/enums/ +│ └─ MissionType.java # 新增 BOAT_ROUTE(3, "无人船航线任务") +│ +├─ src/main/java/com/central/order/mission/model/ +│ └─ Mission.java # 新增 boatRouteId, boatRouteName 字段 +│ +├─ src/main/java/com/central/order/mission/controller/ +│ └─ MissionController.java # saveMission方法增加BOAT_ROUTE类型校验 +│ +├─ src/main/java/com/central/order/mission/service/impl/ +│ └─ MissionServiceImpl.java # dispatchMissionToDevice方法增加无人船分支 +│ +├─ src/main/java/com/central/order/feign/ +│ └─ DeviceCenterService.java # 新增 executeBoatRoute 等Feign接口 +│ +├─ src/main/java/com/central/order/feign/fallback/ +│ └─ DeviceCenterServiceFallbackFactory.java # 新增fallback实现 +│ +└─ src/main/resources/mapper/ + └─ MissionMapper.xml # 新增 boat_route_id, boat_route_name 字段映射 + +SQL变更: +└─ ALTER TABLE missions ADD COLUMN boat_route_id, boat_route_name + +====================================================================== + device-center 新增文件 +====================================================================== + +新增实体: +├─ src/main/java/com/central/device/entity/ +│ ├─ BoatRoute.java # 无人船航线实体 +│ ├─ BoatWaypoint.java # 无人船航点实体 +│ ├─ BoatTrack.java # 无人船轨迹实体 +│ └─ WaterBoundary.java # 水域边界实体 + +新增Controller: +├─ src/main/java/com/central/device/controller/ +│ ├─ BoatRouteController.java # 航线CRUD管理 +│ ├─ BoatCommandController.java # 设备命令控制(接收Feign调用) +│ ├─ WaterBoundaryController.java # 水域边界管理 +│ ├─ BoatTrackController.java # 轨迹查询 +│ └─ BoatTelemetrySSEController.java # SSE遥测推送 + +新增Service: +├─ src/main/java/com/central/device/service/ +│ ├─ IBoatRouteService.java +│ ├─ impl/BoatRouteServiceImpl.java +│ ├─ IWaterBoundaryService.java +│ ├─ impl/WaterBoundaryServiceImpl.java +│ ├─ IBoatControlService.java +│ ├─ impl/BoatControlServiceImpl.java +│ ├─ IBoatTrackService.java +│ └─ impl/BoatTrackServiceImpl.java + +新增Mapper: +├─ src/main/java/com/central/device/mapper/ +│ ├─ BoatRouteMapper.java +│ ├─ BoatWaypointMapper.java +│ ├─ BoatTrackMapper.java +│ └─ WaterBoundaryMapper.java + +新增Mapper XML: +└─ src/main/resources/mapper/ + ├─ BoatRouteMapper.xml + ├─ BoatWaypointMapper.xml + ├─ BoatTrackMapper.xml + └─ WaterBoundaryMapper.xml + +====================================================================== + yingyan 前端新增文件 +====================================================================== + +新增组件: +├─ src/pages/map3d/components/RouteEditor/ +│ ├─ index.tsx # 航线编辑器主组件 +│ ├─ RouteDrawer.tsx # 航线绘制器 +│ ├─ WaypointEditor.tsx # 航点编辑器 +│ ├─ RouteToolbar.tsx # 工具栏 +│ ├─ RoutePreview.tsx # 航线预览 +│ ├─ hooks/useRouteDrawing.ts # 绘制逻辑Hook +│ ├─ hooks/useRouteValidation.ts # 验证逻辑Hook +│ └─ types.ts # 类型定义 + +新增Hooks: +├─ src/hooks/ +│ └─ useBoatSSE.ts # 无人船遥测订阅 + +新增Services: +├─ src/services/ +│ ├─ boatRoute.ts # 航线CRUD API +│ ├─ mission.ts # 任务管理API (扩展现有或新建) +│ └─ boatControl.ts # 无人船控制API + +新增Types: +└─ src/types/ + └─ boatRoute.ts # 无人船相关类型定义 +``` + +--- + +## 9. 附录 + +### 9.1 GeoJSON多边形格式示例 + +```json +{ + "type": "Polygon", + "coordinates": [ + [ + [116.397428, 39.90923], + [116.407428, 39.90923], + [116.407428, 39.91923], + [116.397428, 39.91923], + [116.397428, 39.90923] + ] + ] +} +``` + +### 9.2 航点动作配置示例 + +```json +{ + "actions": [ + { + "actionType": "photo", + "params": { "count": 3, "interval": 2 } + }, + { + "actionType": "video_start", + "duration": 30, + "params": {} + }, + { + "actionType": "horn", + "params": { "message": "安全警示" } + } + ] +} +``` + +### 9.3 遥测数据结构示例 + +```json +{ + "deviceSn": "BOAT001", + "longitude": 116.397428, + "latitude": 39.90923, + "speed": 2.5, + "heading": 45.0, + "batteryPercent": 85, + "status": "navigating", + "currentWaypointIndex": 3, + "deviationDistance": 0.5, + "timestamp": "2026-01-05T10:30:00Z" +} +``` + +--- + +**文档版本**: v1.1 +**编写日期**: 2026-01-05 +**更新说明**: 集成现有Mission任务系统,保持与无人机任务下发流程一致 +**作者**: dzc +**审核状态**: 已审核 diff --git a/zlt-business/device-center/src/main/resources/mapper/BoatRouteMapper.xml b/zlt-business/device-center/src/main/resources/mapper/BoatRouteMapper.xml new file mode 100644 index 00000000..87e7a949 --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/BoatRouteMapper.xml @@ -0,0 +1,137 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + UPDATE boat_route + SET status = #{status}, + update_time = NOW() + WHERE route_id = #{routeId} + + + + + UPDATE boat_route + SET waypoint_count = #{waypointCount}, + total_distance = #{totalDistance}, + total_duration = #{totalDuration}, + update_time = NOW() + WHERE route_id = #{routeId} + + + + + UPDATE boat_route + SET device_sn = #{deviceSn}, + device_name = #{deviceName}, + update_time = NOW() + WHERE route_id = #{routeId} + + + + + UPDATE boat_route + SET device_sn = NULL, + device_name = NULL, + update_time = NOW() + WHERE route_id = #{routeId} + + + + + UPDATE boat_route + SET is_template = #{isTemplate}, + update_time = NOW() + WHERE route_id = #{routeId} + + + + + UPDATE boat_route + SET show_in_model = 0, + update_time = NOW() + WHERE device_sn = #{deviceSn} + AND tenant_id = #{tenantId} + AND deleted = 0 + + + + + UPDATE boat_route + SET show_in_model = 1, + update_time = NOW() + WHERE device_sn = #{deviceSn} + AND tenant_id = #{tenantId} + AND deleted = 0 + AND route_id IN + + #{id} + + + + diff --git a/zlt-business/device-center/src/main/resources/mapper/BoatTrackMapper.xml b/zlt-business/device-center/src/main/resources/mapper/BoatTrackMapper.xml new file mode 100644 index 00000000..0b2b57e4 --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/BoatTrackMapper.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + ( + #{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() + ) + + + + + + DELETE FROM boat_track + WHERE record_time < #{beforeTime} + + + diff --git a/zlt-business/device-center/src/main/resources/mapper/BoatWaypointMapper.xml b/zlt-business/device-center/src/main/resources/mapper/BoatWaypointMapper.xml new file mode 100644 index 00000000..3b5d211f --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/BoatWaypointMapper.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + DELETE FROM boat_waypoint + WHERE route_id = #{routeId} + + + + + 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 + + ( + #{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() + ) + + + + + + + + + + diff --git a/zlt-business/device-center/src/main/resources/mapper/WaterBoundaryMapper.xml b/zlt-business/device-center/src/main/resources/mapper/WaterBoundaryMapper.xml new file mode 100644 index 00000000..e84305ba --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/WaterBoundaryMapper.xml @@ -0,0 +1,104 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + UPDATE water_boundary + SET status = #{status}, + update_time = NOW() + WHERE boundary_id = #{boundaryId} + + + + + UPDATE water_boundary + SET show_in_model = 0, + update_time = NOW() + WHERE device_sn = #{deviceSn} + AND tenant_id = #{tenantId} + AND deleted = 0 + + + + + UPDATE water_boundary + SET show_in_model = 1, + update_time = NOW() + WHERE device_sn = #{deviceSn} + AND tenant_id = #{tenantId} + AND deleted = 0 + AND boundary_id IN + + #{id} + + + + + + + diff --git a/zlt-business/device-center/src/main/resources/sql/boat_route_tables.sql b/zlt-business/device-center/src/main/resources/sql/boat_route_tables.sql new file mode 100644 index 00000000..74939c0a --- /dev/null +++ b/zlt-business/device-center/src/main/resources/sql/boat_route_tables.sql @@ -0,0 +1,166 @@ +-- ==================================================================== +-- 无人船航线规划相关数据表 +-- 创建日期: 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)', + `boundary_id` varchar(64) DEFAULT NULL COMMENT '规划水域边界ID', + `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-是', + `show_in_model` 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='无人船航线表'; + +-- 兼容已存在表:补充“模型中显示航线”字段(若已存在可忽略) +-- ALTER TABLE `boat_route` +-- ADD COLUMN `show_in_model` tinyint DEFAULT 0 COMMENT '是否在模型中显示航线:0-否,1-是' AFTER `is_template`; + +-- 兼容已存在表:补充“规划水域边界ID”字段(若已存在可忽略) +-- ALTER TABLE `boat_route` +-- ADD COLUMN `boundary_id` varchar(64) DEFAULT NULL COMMENT '规划水域边界ID' AFTER `boundary_polygon`; + +-- 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 '边界名称', + `device_sn` varchar(64) DEFAULT NULL COMMENT '绑定设备SN', + `scenic_id` bigint DEFAULT 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', + `show_in_model` tinyint DEFAULT 0 COMMENT '是否在模型中显示标绘:0-否,1-是', + + `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_device_sn` (`device_sn`), + 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`); diff --git a/zlt-business/device-center/src/main/resources/sql/water_boundary_device_sn_migration.sql b/zlt-business/device-center/src/main/resources/sql/water_boundary_device_sn_migration.sql new file mode 100644 index 00000000..2b5c307e --- /dev/null +++ b/zlt-business/device-center/src/main/resources/sql/water_boundary_device_sn_migration.sql @@ -0,0 +1,17 @@ +-- ==================================================================== +-- 水域边界表结构升级:增加 device_sn,并放宽 scenic_id 非空约束 +-- 创建日期: 2026-01-06 +-- 说明:用于已有环境的增量升级(请按需执行) +-- ==================================================================== + +-- 1) 增加 device_sn 字段(如已存在可忽略报错或自行判断) +ALTER TABLE `water_boundary` + ADD COLUMN `device_sn` varchar(64) DEFAULT NULL COMMENT '绑定设备SN' AFTER `boundary_name`; + +-- 2) scenic_id 改为可空(如后续不再使用 scenic_id) +ALTER TABLE `water_boundary` + MODIFY COLUMN `scenic_id` bigint DEFAULT NULL COMMENT '所属景区ID(可选)'; + +-- 3) 增加索引 +CREATE INDEX `idx_device_sn` ON `water_boundary` (`device_sn`); + diff --git a/zlt-business/device-center/src/main/resources/sql/water_boundary_show_in_model_migration.sql b/zlt-business/device-center/src/main/resources/sql/water_boundary_show_in_model_migration.sql new file mode 100644 index 00000000..a67d5668 --- /dev/null +++ b/zlt-business/device-center/src/main/resources/sql/water_boundary_show_in_model_migration.sql @@ -0,0 +1,5 @@ +-- 为水域边界增加“是否在模型中显示标绘”字段(用于图层管理持久化) +ALTER TABLE `water_boundary` + ADD COLUMN `show_in_model` tinyint DEFAULT 0 COMMENT '是否在模型中显示标绘:0-否,1-是' AFTER `model_id`; + +CREATE INDEX `idx_show_in_model` ON `water_boundary` (`show_in_model`); diff --git a/zlt-business/device-ops-center/pom.xml b/zlt-business/device-ops-center/pom.xml deleted file mode 100644 index 3d962348..00000000 --- a/zlt-business/device-ops-center/pom.xml +++ /dev/null @@ -1,146 +0,0 @@ - - - 4.0.0 - - com.zlt - zlt-business - 6.0.0 - - - device-ops-center - 设备运维中心 - - - 17 - 17 - UTF-8 - - - - - - com.zlt - zlt-config - - - com.zlt - zlt-log-spring-boot-starter - - - com.zlt - zlt-common-spring-boot-starter - - - com.zlt - zlt-db-spring-boot-starter - - - com.zlt - zlt-redis-spring-boot-starter - - - com.zlt - zlt-loadbalancer-spring-boot-starter - - - com.zlt - zlt-sentinel-spring-boot-starter - - - - com.github.xiaoymin - knife4j-openapi3-jakarta-spring-boot-starter - - - com.zlt - search-client - - - - org.springframework.boot - spring-boot-starter-web - - - com.alibaba.cloud - spring-cloud-starter-alibaba-nacos-discovery - - - org.springframework.boot - spring-boot-starter-actuator - - - - mysql - mysql-connector-java - - - - io.micrometer - micrometer-registry-prometheus - - - junit - junit - test - - - org.hibernate - hibernate-validator - - - - org.springframework.boot - spring-boot-starter-validation - - - cn.hutool - hutool-all - 5.8.25 - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - - - - com.spotify - docker-maven-plugin - - ${docker.image.prefix}/${project.artifactId} - - ${project.version} - latest - - true - ${docker.baseImage} - ${docker.volumes} - - ${docker.java.opts} - - ["sh","-c","java $JAVA_OPTS ${docker.java.security.egd} -jar /${project.build.finalName}.jar"] - - - / - ${project.build.directory} - ${project.build.finalName}.jar - - - - - - ${project.artifactId} - - diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/DeviceCenterApp.java b/zlt-business/device-ops-center/src/main/java/com/central/device/DeviceCenterApp.java deleted file mode 100644 index 332428f6..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/DeviceCenterApp.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.central.device; - -import com.central.common.lb.annotation.EnableFeignInterceptor; -import com.central.search.annotation.EnableSearchClient; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.client.discovery.EnableDiscoveryClient; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -/** - * @author 作者 lsl E-mail: 1272745473@qq.com - */ -@EnableDiscoveryClient -@EnableSearchClient -@EnableTransactionManagement -@EnableFeignInterceptor -@SpringBootApplication -public class DeviceCenterApp { - public static void main(String[] args) { - SpringApplication.run(DeviceCenterApp.class, args); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceController.java deleted file mode 100644 index 954ecc12..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceController.java +++ /dev/null @@ -1,273 +0,0 @@ -package com.central.device.controller; - -import cn.hutool.core.collection.CollUtil; -import com.alibaba.excel.EasyExcel; -import com.alibaba.excel.support.ExcelTypeEnum; -import com.central.common.model.PageResult; -import com.central.common.model.Result; -import com.central.device.model.AgeDevice; -import com.central.device.model.excel.AgeDeviceExcel; -import com.central.device.service.IAgeDeviceService; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import io.swagger.v3.oas.annotations.enums.ParameterIn; -import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.servlet.http.HttpServletResponse; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.BeanUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; - -import java.io.IOException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * Device information - * - * @author lsl - * @date 2024-12-19 17:51:47 - */ -@Slf4j -@RestController -@RequestMapping("/device") -@Tag(name = "设备管理") -@RequiredArgsConstructor -public class AgeDeviceController { - - - @Autowired - private IAgeDeviceService ageDeviceService; - - /** - * 列表 - */ - @Operation(summary = "查询列表") - @Parameters({ - @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), - @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) - }) - @GetMapping - public PageResult list(@RequestParam Map params) { - return ageDeviceService.findList(params); - } - - /** - * 查询 - */ - @Operation(summary = "查询") - @GetMapping("/{id}") - public Result findUserById(@PathVariable Long id) { - AgeDevice model = ageDeviceService.getById(id); - return Result.succeed(model, "查询成功"); - } - - /** - * 新增or更新 - */ - @Operation(summary = "保存") - @PostMapping - public Result save(@RequestBody AgeDevice ageDevice) { - ageDeviceService.saveOrUpdate(ageDevice); - return Result.succeed("保存成功"); - } - - /** - * 删除 - */ - @Operation(summary = "删除") - @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) - @DeleteMapping("/{id}") - public Result delete(@PathVariable Long id) { - ageDeviceService.removeById(id); - return Result.succeed("删除成功"); - } - - /** - * 导出设备信息 - */ - @Operation(summary = "导出设备信息") - @PostMapping("/export") - public void exportDevices(@RequestBody Map params, HttpServletResponse response) { - try { - // 设置响应头 - response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); - response.setCharacterEncoding(StandardCharsets.UTF_8.name()); - String fileName = URLEncoder.encode("设备信息", StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20"); - response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); - - // 查询导出数据 - List deviceList = ageDeviceService.findListByParams(params); - if (CollUtil.isEmpty(deviceList)) { - deviceList = new ArrayList<>(); - } - - // 转换并写入Excel - List excelList = deviceList.stream() - .map(AgeDeviceExcel::fromDevice) - .collect(java.util.stream.Collectors.toList()); - - EasyExcel.write(response.getOutputStream(), AgeDeviceExcel.class) - .excelType(ExcelTypeEnum.XLSX) - .sheet("设备信息") - .doWrite(excelList); - - } catch (Exception e) { - log.error("导出设备信息失败", e); - // 重置response - response.reset(); - response.setContentType("application/json"); - response.setCharacterEncoding(StandardCharsets.UTF_8.name()); - try { - response.getWriter().println("{\"code\":500,\"msg\":\"导出失败\"}"); - } catch (IOException ex) { - log.error("写入响应失败", ex); - } - } - } - - /** - * 导入设备信息 - */ - @Operation(summary = "导入设备信息") - @PostMapping("/import") - public Result importDevices(@RequestParam("file") MultipartFile file) { - try { - if (file.isEmpty()) { - return Result.failed("请选择要导入的文件"); - } - - // 文件大小校验(10MB) - if (file.getSize() > 10 * 1024 * 1024) { - return Result.failed("文件大小不能超过10MB"); - } - - // 文件类型校验 - String fileName = file.getOriginalFilename(); - if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) { - return Result.failed("请上传Excel文件"); - } - - // 读取Excel数据 - List excelList = EasyExcel.read(file.getInputStream()) - .head(AgeDeviceExcel.class) - .sheet() - .doReadSync(); - - if (CollUtil.isEmpty(excelList)) { - return Result.failed("导入数据为空"); - } - - // 数据校验和转换 - List errorMsgs = new ArrayList<>(); - List deviceList = new ArrayList<>(); - - for (int i = 0; i < excelList.size(); i++) { - AgeDeviceExcel excelData = excelList.get(i); - try { - // 数据校验 - validateExcelData(excelData, i + 1, errorMsgs); - if (errorMsgs.isEmpty()) { - deviceList.add(excelData.toDevice()); - } - } catch (Exception e) { - log.error("第{}行数据处理失败", i + 1, e); - errorMsgs.add(String.format("第%d行数据处理失败:%s", i + 1, e.getMessage())); - } - } - - if (!errorMsgs.isEmpty()) { - return Result.failed("导入失败:" + String.join("; ", errorMsgs)); - } - - // 批量保存数据 - boolean success = ageDeviceService.importDevices(deviceList); - return success ? Result.succeed("导入成功") : Result.failed("导入失败"); - - } catch (Exception e) { - log.error("导入设备信息失败", e); - return Result.failed("导入失败:" + e.getMessage()); - } - } - - @Operation(summary = "下载导入模板") - @GetMapping("/template") - public void downloadTemplate(HttpServletResponse response) { - try { - response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); - response.setCharacterEncoding(StandardCharsets.UTF_8.name()); - String fileName = URLEncoder.encode("设备导入模板", StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20"); - response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); - - // 创建模板数据 - List templateList = new ArrayList<>(); - // 可以添加一行示例数据 - AgeDeviceExcel template = new AgeDeviceExcel(); - template.setDeviceSn("示例:DEVICE001"); - template.setDeviceName("示例:测试设备1"); - templateList.add(template); - - EasyExcel.write(response.getOutputStream(), AgeDeviceExcel.class) - .excelType(ExcelTypeEnum.XLSX) - .sheet("设备信息") - .doWrite(templateList); - - } catch (Exception e) { - log.error("下载模板失败", e); - response.reset(); - response.setContentType("application/json"); - response.setCharacterEncoding(StandardCharsets.UTF_8.name()); - try { - response.getWriter().println("{\"code\":500,\"msg\":\"下载模板失败\"}"); - } catch (IOException ex) { - log.error("写入响应失败", ex); - } - } - } - - /** - * 验证Excel数据 - */ - private void validateExcelData(AgeDeviceExcel excelData, int rowIndex, List errorMsgs) { - if (excelData == null) { - errorMsgs.add(String.format("第%d行数据为空", rowIndex)); - return; - } - - // 必填字段校验 - if (org.springframework.util.StringUtils.isEmpty(excelData.getDeviceSn())) { - errorMsgs.add(String.format("第%d行:设备序列号不能为空", rowIndex)); - } - if (org.springframework.util.StringUtils.isEmpty(excelData.getDeviceName())) { - errorMsgs.add(String.format("第%d行:设备名称不能为空", rowIndex)); - } - - // 字段格式校验 - if (excelData.getDeviceType() != null && (excelData.getDeviceType() < 0 || excelData.getDeviceType() > 100)) { - errorMsgs.add(String.format("第%d行:设备类型取值范围为0-100", rowIndex)); - } - - // 重复性校验 - if (!org.springframework.util.StringUtils.isEmpty(excelData.getDeviceSn())) { - boolean exists = ageDeviceService.checkDeviceSnExists(excelData.getDeviceSn()); - if (exists) { - errorMsgs.add(String.format("第%d行:设备序列号已存在", rowIndex)); - } - } - } - - private List convertToExcelList(List deviceList) { - return deviceList.stream().map(device -> { - AgeDeviceExcel excel = new AgeDeviceExcel(); - BeanUtils.copyProperties(device, excel); - return excel; - }).collect(Collectors.toList()); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceFirmwareController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceFirmwareController.java deleted file mode 100644 index b317657e..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceFirmwareController.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.central.device.controller; - -import java.util.Map; - -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; -import io.swagger.v3.oas.annotations.tags.Tag; -import io.swagger.v3.oas.annotations.enums.ParameterIn; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import lombok.extern.slf4j.Slf4j; - -import com.central.device.model.AgeDeviceFirmware; -import com.central.device.service.IAgeDeviceFirmwareService; -import com.central.common.model.PageResult; -import com.central.common.model.Result; - -/** - * Firmware file information - * - * @author lsl - * @date 2024-12-19 17:52:54 - */ -@Slf4j -@RestController -@RequestMapping("/firmware") -@Tag(name = "Firmware file information") -@RequiredArgsConstructor -public class AgeDeviceFirmwareController { - private final IAgeDeviceFirmwareService ageDeviceFirmwareService; - - /** - * 列表 - */ - @Operation(summary = "查询列表") - @Parameters({ - @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), - @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) - }) - @GetMapping - public PageResult list(@RequestParam Map params) { - return ageDeviceFirmwareService.findList(params); - } - - /** - * 查询 - */ - @Operation(summary = "查询") - @GetMapping("/{id}") - public Result findUserById(@PathVariable Long id) { - AgeDeviceFirmware model = ageDeviceFirmwareService.getById(id); - return Result.succeed(model, "查询成功"); - } - - /** - * 新增or更新 - */ - @Operation(summary = "保存") - @PostMapping - public Result save(@RequestBody AgeDeviceFirmware ageDeviceFirmware) { - ageDeviceFirmwareService.saveOrUpdate(ageDeviceFirmware); - return Result.succeed("保存成功"); - } - - /** - * 删除 - */ - @Operation(summary = "删除") - @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) - @DeleteMapping("/{id}") - public Result delete(@PathVariable Long id) { - ageDeviceFirmwareService.removeById(id); - return Result.succeed("删除成功"); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceHmsController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceHmsController.java deleted file mode 100644 index 0c0e4cd6..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceHmsController.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.central.device.controller; - -import java.util.Map; - -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; -import io.swagger.v3.oas.annotations.tags.Tag; -import io.swagger.v3.oas.annotations.enums.ParameterIn; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import lombok.extern.slf4j.Slf4j; - -import com.central.device.model.AgeDeviceHms; -import com.central.device.service.IAgeDeviceHmsService; -import com.central.common.model.PageResult; -import com.central.common.model.Result; - -/** - * Device's hms information - * - * @author lsl - * @date 2024-12-19 17:53:01 - */ -@Slf4j -@RestController -@RequestMapping("/hms") -@Tag(name = "Device's hms information") -@RequiredArgsConstructor -public class AgeDeviceHmsController { - private final IAgeDeviceHmsService ageDeviceHmsService; - - /** - * 列表 - */ - @Operation(summary = "查询列表") - @Parameters({ - @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), - @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) - }) - @GetMapping - public PageResult list(@RequestParam Map params) { - return ageDeviceHmsService.findList(params); - } - - /** - * 查询 - */ - @Operation(summary = "查询") - @GetMapping("/{id}") - public Result findUserById(@PathVariable Long id) { - AgeDeviceHms model = ageDeviceHmsService.getById(id); - return Result.succeed(model, "查询成功"); - } - - /** - * 新增or更新 - */ - @Operation(summary = "保存") - @PostMapping - public Result save(@RequestBody AgeDeviceHms ageDeviceHms) { - ageDeviceHmsService.saveOrUpdate(ageDeviceHms); - return Result.succeed("保存成功"); - } - - /** - * 删除 - */ - @Operation(summary = "删除") - @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) - @DeleteMapping("/{id}") - public Result delete(@PathVariable Long id) { - ageDeviceHmsService.removeById(id); - return Result.succeed("删除成功"); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceLogsController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceLogsController.java deleted file mode 100644 index 8526c968..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDeviceLogsController.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.central.device.controller; - -import java.util.Map; - -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; -import io.swagger.v3.oas.annotations.tags.Tag; -import io.swagger.v3.oas.annotations.enums.ParameterIn; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import lombok.extern.slf4j.Slf4j; - -import com.central.device.model.AgeDeviceLogs; -import com.central.device.service.IAgeDeviceLogsService; -import com.central.common.model.PageResult; -import com.central.common.model.Result; - -/** - * Log for uploading logs - * - * @author lsl - * @date 2024-12-19 17:53:03 - */ -@Slf4j -@RestController -@RequestMapping("/logs") -@Tag(name = "Log for uploading logs") -@RequiredArgsConstructor -public class AgeDeviceLogsController { - private final IAgeDeviceLogsService ageDeviceLogsService; - - /** - * 列表 - */ - @Operation(summary = "查询列表") - @Parameters({ - @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), - @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) - }) - @GetMapping - public PageResult list(@RequestParam Map params) { - return ageDeviceLogsService.findList(params); - } - - /** - * 查询 - */ - @Operation(summary = "查询") - @GetMapping("/{id}") - public Result findUserById(@PathVariable Long id) { - AgeDeviceLogs model = ageDeviceLogsService.getById(id); - return Result.succeed(model, "查询成功"); - } - - /** - * 新增or更新 - */ - @Operation(summary = "保存") - @PostMapping - public Result save(@RequestBody AgeDeviceLogs ageDeviceLogs) { - ageDeviceLogsService.saveOrUpdate(ageDeviceLogs); - return Result.succeed("保存成功"); - } - - /** - * 删除 - */ - @Operation(summary = "删除") - @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) - @DeleteMapping("/{id}") - public Result delete(@PathVariable Long id) { - ageDeviceLogsService.removeById(id); - return Result.succeed("删除成功"); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDevicePayloadController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDevicePayloadController.java deleted file mode 100644 index 2bc7f5fa..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeDevicePayloadController.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.central.device.controller; - -import java.util.Map; - -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; -import io.swagger.v3.oas.annotations.tags.Tag; -import io.swagger.v3.oas.annotations.enums.ParameterIn; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import lombok.extern.slf4j.Slf4j; - -import com.central.device.model.AgeDevicePayload; -import com.central.device.service.IAgeDevicePayloadService; -import com.central.common.model.PageResult; -import com.central.common.model.Result; - -/** - * The payload information of the device. - * - * @author lsl - * @date 2024-12-19 17:53:19 - */ -@Slf4j -@RestController -@RequestMapping("/payload") -@Tag(name = "The payload information of the device.") -@RequiredArgsConstructor -public class AgeDevicePayloadController { - private final IAgeDevicePayloadService ageDevicePayloadService; - - /** - * 列表 - */ - @Operation(summary = "查询列表") - @Parameters({ - @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), - @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) - }) - @GetMapping - public PageResult list(@RequestParam Map params) { - return ageDevicePayloadService.findList(params); - } - - /** - * 查询 - */ - @Operation(summary = "查询") - @GetMapping("/{id}") - public Result findUserById(@PathVariable Long id) { - AgeDevicePayload model = ageDevicePayloadService.getById(id); - return Result.succeed(model, "查询成功"); - } - - /** - * 新增or更新 - */ - @Operation(summary = "保存") - @PostMapping - public Result save(@RequestBody AgeDevicePayload ageDevicePayload) { - ageDevicePayloadService.saveOrUpdate(ageDevicePayload); - return Result.succeed("保存成功"); - } - - /** - * 删除 - */ - @Operation(summary = "删除") - @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) - @DeleteMapping("/{id}") - public Result delete(@PathVariable Long id) { - ageDevicePayloadService.removeById(id); - return Result.succeed("删除成功"); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeFirmwareModelController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeFirmwareModelController.java deleted file mode 100644 index 54c3446b..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeFirmwareModelController.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.central.device.controller; - -import java.util.Map; - -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; -import io.swagger.v3.oas.annotations.tags.Tag; -import io.swagger.v3.oas.annotations.enums.ParameterIn; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import lombok.extern.slf4j.Slf4j; - -import com.central.device.model.AgeFirmwareModel; -import com.central.device.service.IAgeFirmwareModelService; -import com.central.common.model.PageResult; -import com.central.common.model.Result; - -/** - * - * - * @author lsl - * @date 2024-12-19 17:53:20 - */ -@Slf4j -@RestController -@RequestMapping("/firmware/model") -@Tag(name = "") -@RequiredArgsConstructor -public class AgeFirmwareModelController { - private final IAgeFirmwareModelService ageFirmwareModelService; - - /** - * 列表 - */ - @Operation(summary = "查询列表") - @Parameters({ - @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), - @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) - }) - @GetMapping - public PageResult list(@RequestParam Map params) { - return ageFirmwareModelService.findList(params); - } - - /** - * 查询 - */ - @Operation(summary = "查询") - @GetMapping("/{id}") - public Result findUserById(@PathVariable Long id) { - AgeFirmwareModel model = ageFirmwareModelService.getById(id); - return Result.succeed(model, "查询成功"); - } - - /** - * 新增or更新 - */ - @Operation(summary = "保存") - @PostMapping - public Result save(@RequestBody AgeFirmwareModel ageFirmwareModel) { - ageFirmwareModelService.saveOrUpdate(ageFirmwareModel); - return Result.succeed("保存成功"); - } - - /** - * 删除 - */ - @Operation(summary = "删除") - @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) - @DeleteMapping("/{id}") - public Result delete(@PathVariable Long id) { - ageFirmwareModelService.removeById(id); - return Result.succeed("删除成功"); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeWorkspaceController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeWorkspaceController.java deleted file mode 100644 index 56c9e747..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/AgeWorkspaceController.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.central.device.controller; - -import java.util.Map; - -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; -import io.swagger.v3.oas.annotations.tags.Tag; -import io.swagger.v3.oas.annotations.enums.ParameterIn; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import lombok.extern.slf4j.Slf4j; - -import com.central.device.model.AgeWorkspace; -import com.central.device.service.IAgeWorkspaceService; -import com.central.common.model.PageResult; -import com.central.common.model.Result; - -/** - * - * - * @author lsl - * @date 2024-12-19 17:52:26 - */ -@Slf4j -@RestController -@RequestMapping("/workspace") -@Tag(name = "") -@RequiredArgsConstructor -public class AgeWorkspaceController { - private final IAgeWorkspaceService ageWorkspaceService; - - /** - * 列表 - */ - @Operation(summary = "查询列表") - @Parameters({ - @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), - @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) - }) - @GetMapping - public PageResult list(@RequestParam Map params) { - return ageWorkspaceService.findList(params); - } - - /** - * 查询 - */ - @Operation(summary = "查询") - @GetMapping("/{id}") - public Result findUserById(@PathVariable Long id) { - AgeWorkspace model = ageWorkspaceService.getById(id); - return Result.succeed(model, "查询成功"); - } - - /** - * 新增or更新 - */ - @Operation(summary = "保存") - @PostMapping - public Result save(@RequestBody AgeWorkspace ageWorkspace) { - ageWorkspaceService.saveOrUpdate(ageWorkspace); - return Result.succeed("保存成功"); - } - - /** - * 删除 - */ - @Operation(summary = "删除") - @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) - @DeleteMapping("/{id}") - public Result delete(@PathVariable Long id) { - ageWorkspaceService.removeById(id); - return Result.succeed("删除成功"); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/ApiDeviceController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/ApiDeviceController.java deleted file mode 100644 index b67da03f..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/ApiDeviceController.java +++ /dev/null @@ -1,178 +0,0 @@ -package com.central.device.controller; - -import com.alibaba.fastjson.JSONObject; -import com.alibaba.nacos.shaded.com.google.gson.Gson; -import com.alibaba.nacos.shaded.com.google.gson.JsonElement; -import com.alibaba.nacos.shaded.com.google.gson.JsonObject; -import com.central.common.model.Result; -import com.central.device.feign.OrderCenterService; -import com.central.device.message.ControlEnum; -import com.central.device.message.ControlMessageConstant; -import com.central.device.model.LineFile; -import com.central.device.service.ILineFileService; -import com.central.device.service.LiveStreamService; -import com.central.device.util.IotRequestResult; -import com.central.device.util.MapUtil; -import com.central.device.util.RequestUtils; -import com.fasterxml.jackson.core.JsonProcessingException; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.tags.Tag; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; -import org.springframework.web.bind.annotation.*; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -/** - * 设备操作controller - * @author lishilin - * @date 2024-12-31 - */ -@Tag(name = "MQTT设备管理") -@Slf4j -@RestController -public class ApiDeviceController { - - @Value("${jetlinks.server.baseUrl}") - private String baseUrl;// = "http://119.45.169.13:8848/"; - - @Autowired - private LiveStreamService liveStreamService; - - @Autowired - private RequestUtils requestUtils; - - private ControlMessageConstant controlMessageConstant = new ControlMessageConstant(); - - @Autowired - private OrderCenterService orderCenterService; - - @Autowired - private ILineFileService lineFileService; - /** - * 获取设备属性 - */ - @Operation(summary = "获取设备属性") - @GetMapping("/property/_query/{deviceId}/{property}") - public Result getProperty(@RequestParam Map param,@PathVariable("deviceId") String deviceId) throws IOException { - - //温度属性,属性在设备管理的设备型号中设置 - String property = MapUtil.getStrValue(param, "property"); - String url = baseUrl + "/device/" + deviceId + "/property/" + property; - - Map result = requestUtils.getGetRequestResultMap(url,new HashMap<>()); - return Result.succeed(result,"查询成功"); - - - } - - /** - * 设置设备属性测试 - */ - @Operation(summary = "设备属性设置") - @PostMapping("/setting/{deviceId}/property") - public Result writeProperties(@RequestBody Map param, @PathVariable("deviceId") String deviceId) { - log.info("开始设置设备属性: deviceId={}, param={}", deviceId, param); - try { - // 1. 参数校验 - String control = MapUtil.getStrValue(param, "control"); - String orderNo = MapUtil.getStrValue(param, "order_no"); - if (!validateParams(control, orderNo)) { - return Result.failed("参数错误"); - } - - // 2. 检查订单状态 - String orderStatus = orderCenterService.getOrderStatusByOrderNo(orderNo); - if (!isValidOrderStatus(orderStatus)) { - return Result.succeed("设备已执行"); - } - - // 3. 构建控制消息 - JsonObject controlMessage = buildControlMessage(control, orderNo, deviceId); - if (controlMessage == null) { - return Result.succeed("暂未开放控制权限"); - } - - // 4. 发送设备控制请求 - String url = baseUrl + "/device/instance/" + deviceId + "/property"; - Map result = requestUtils.getPostRequestResultMap(url, controlMessage.toString()); - - // 5. 处理响应结果 - return handleDeviceResponse(result, orderNo); - - } catch (Exception e) { - log.error("设置设备属性异常: deviceId={}, error={}", deviceId, e.getMessage(), e); - return Result.failed("系统异常"); - } - } - - private boolean validateParams(String control, String orderNo) { - return !StringUtils.isEmpty(control) && !StringUtils.isEmpty(orderNo); - } - - private boolean isValidOrderStatus(String orderStatus) { - return !StringUtils.isEmpty(orderStatus) && orderStatus.equals("1"); - } - - private JsonObject buildControlMessage(String control, String orderNo, String deviceId) { - if (!ControlEnum.contains(ControlEnum.valueOf(control.toUpperCase()))) { - return null; - } - - Gson gson = new Gson(); - JsonObject jsonObject = gson.fromJson(controlMessageConstant.CONTROL_MESSAGE_MAP.get(control), JsonObject.class); - JsonObject data = jsonObject.getAsJsonObject("data"); - // 设置订单信息 - data.addProperty("order_no", orderNo); - - // 获取航线信息 - Map wayResult = orderCenterService.getWaylineByOrderNo(orderNo); - String waylineFilePath = MapUtil.getStrValue(wayResult, "waylineFilePath"); - String waylineId = MapUtil.getStrValue(wayResult, "waylineId"); - log.info("waylineFilePath:{}, waylineId:{}", waylineFilePath, waylineId); - data.addProperty("wayline_link_url", waylineFilePath); - LineFile lineFile = lineFileService.findLineFileByWaylineId(waylineId); - Assert.notNull(lineFile,"航线文件签名不正确"); - data.addProperty("file_md5", lineFile.getSign()); - // 设置设备视频流地址 - try { - data.add("stream_urls", gson.fromJson(liveStreamService.generateStreamUrls(deviceId).toJSONString(), JsonElement.class)); - } catch (Exception e) { - log.error("生成设备推流/拉流地址异常: deviceId={}, error={}", deviceId, e.getMessage(), e); - data.addProperty("stream_urls", "{}"); // 或者空字符串 "" - } - - return jsonObject; - } - - private Result handleDeviceResponse(Map result, String orderNo) throws JsonProcessingException { - JSONObject object = JSONObject.parseObject(result.get("")); - if (object == null) { - return Result.failed("请求IOT平台异常"); - } - - IotRequestResult requestResult = IotRequestResult.getInstance(object); - if (requestResult.getStatus() == 200 || requestResult.getStatus() == 500) { - log.info("设置设备属性返回消息: message={}", requestResult.getMessage()); - if (requestResult.getMessage().equals("Device is offline")){ - return Result.failed("设备已离线请稍后重试"); - } - Result updateResult = orderCenterService.updateOrderStatusDoing(orderNo); - if (updateResult.getResp_code() != null && updateResult.getResp_code() == 0) { - return Result.succeed(updateResult.getData(), "设置成功"); - } - } - - return Result.failed("请重试"); - } - - @GetMapping("/device/wayline") - public Result getWayline(@RequestParam String no){ - return Result.succeed(orderCenterService.getWaylineByOrderNo(no)); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/IaFileController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/IaFileController.java deleted file mode 100644 index 1bf1806a..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/IaFileController.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.central.device.controller; - -import java.util.Map; - -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; -import io.swagger.v3.oas.annotations.tags.Tag; -import io.swagger.v3.oas.annotations.enums.ParameterIn; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import lombok.extern.slf4j.Slf4j; - -import com.central.device.model.IaFile; -import com.central.device.service.IIaFileService; -import com.central.common.model.PageResult; -import com.central.common.model.Result; - -/** - * Media file information - * - * @author lsl - * @date 2024-12-19 17:52:18 - */ -@Slf4j -@RestController -@RequestMapping("/file") -@Tag(name = "Media file information") -@RequiredArgsConstructor -public class IaFileController { - private final IIaFileService iaFileService; - - /** - * 列表 - */ - @Operation(summary = "查询列表") - @Parameters({ - @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), - @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) - }) - @GetMapping - public PageResult list(@RequestParam Map params) { - return iaFileService.findList(params); - } - - /** - * 查询 - */ - @Operation(summary = "查询") - @GetMapping("/{id}") - public Result findUserById(@PathVariable Long id) { - IaFile model = iaFileService.getById(id); - return Result.succeed(model, "查询成功"); - } - - /** - * 新增or更新 - */ - @Operation(summary = "保存") - @PostMapping - public Result save(@RequestBody IaFile iaFile) { - iaFileService.saveOrUpdate(iaFile); - return Result.succeed("保存成功"); - } - - /** - * 删除 - */ - @Operation(summary = "删除") - @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) - @DeleteMapping("/{id}") - public Result delete(@PathVariable Long id) { - iaFileService.removeById(id); - return Result.succeed("删除成功"); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LineFileController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LineFileController.java deleted file mode 100644 index 1ebdb1c8..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LineFileController.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.central.device.controller; - -import com.central.common.model.PageResult; -import com.central.common.model.Result; -import com.central.device.model.LineFile; -import com.central.device.service.ILineFileService; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import io.swagger.v3.oas.annotations.enums.ParameterIn; -import io.swagger.v3.oas.annotations.tags.Tag; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.web.bind.annotation.*; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * Wayline file information - * - * @author lsl - * @date 2024-12-19 17:51:52 - */ -@Slf4j -@RestController -@RequestMapping("/wayline") -@Tag(name = "Wayline file information") -@RequiredArgsConstructor -public class LineFileController { - private final ILineFileService lineFileService; - - /** - * 列表 - */ - @Operation(summary = "查询列表") - @Parameters({ - @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), - @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) - }) - @GetMapping - public PageResult list(@RequestParam Map params) { - return lineFileService.findList(params); - } - - /** - * 查询 - */ - @Operation(summary = "查询") - @GetMapping("/{id}") - public Result findById(@PathVariable String id) { - try { - LineFile model = lineFileService.findLineFileByWaylineId(id); - if (model == null) { - return Result.failed("未找到对应的航线文件信息"); - } - return Result.succeed(model, "查询成功"); - } catch (Exception e) { - log.error("查询航线文件失败,id: {}", id, e); - return Result.failed("查询航线文件失败:" + e.getMessage()); - } - } - - /** - * 查询 - */ - @Operation(summary = "查询") - @GetMapping("/sign/{id}") - public Result findLineSignById(@PathVariable String id) { - try { - LineFile model = lineFileService.findLineFileByWaylineId(id); - if (model == null) { - return Result.failed("未找到对应的航线文件信息"); - } - return Result.succeed(model.getSign(), "查询成功"); - } catch (Exception e) { - log.error("查询航线文件签名失败,id: {}", id, e); - return Result.failed("查询航线文件签名失败:" + e.getMessage()); - } - } - - /** - * 新增or更新 - */ - @Operation(summary = "保存") - @PostMapping - public Result save(@RequestBody LineFile lineFile) { - lineFileService.saveOrUpdate(lineFile); - return Result.succeed("保存成功"); - } - - /** - * 删除 - */ - @Operation(summary = "删除") - @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) - @DeleteMapping("/{id}") - public Result delete(@PathVariable Long id) { - lineFileService.removeById(id); - return Result.succeed("删除成功"); - } - - /** - * 诊断航线文件数据 - */ - @Operation(summary = "诊断航线文件数据") - @GetMapping("/diagnose") - public Result diagnoseLineFileData() { - try { - // 查询所有航线文件 - List allLineFiles = lineFileService.list(); - - Map diagnosis = new HashMap<>(); - diagnosis.put("totalCount", allLineFiles.size()); - - // 按waylineId分组统计 - Map waylineIdStats = allLineFiles.stream() - .collect(Collectors.groupingBy( - f -> f.getWaylineId() == null ? "NULL_WAYLINE_ID" : f.getWaylineId(), - Collectors.counting() - )); - diagnosis.put("waylineIdStats", waylineIdStats); - - // 检查有sign字段的文件 - List filesWithSign = allLineFiles.stream() - .filter(f -> f.getSign() != null && !f.getSign().isEmpty()) - .collect(Collectors.toList()); - diagnosis.put("filesWithSign", filesWithSign.size()); - - // 最近的文件示例 - List> recentFiles = allLineFiles.stream() - .limit(10) - .map(f -> { - Map fileInfo = new HashMap<>(); - fileInfo.put("id", f.getId()); - fileInfo.put("name", f.getName()); - fileInfo.put("waylineId", f.getWaylineId()); - fileInfo.put("sign", f.getSign()); - fileInfo.put("createTime", f.getCreateTime()); - return fileInfo; - }) - .collect(Collectors.toList()); - diagnosis.put("recentFiles", recentFiles); - - return Result.succeed(diagnosis, "诊断完成"); - } catch (Exception e) { - log.error("诊断航线文件数据失败", e); - return Result.failed("诊断失败:" + e.getMessage()); - } - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LineJobController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LineJobController.java deleted file mode 100644 index 3cc5af40..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LineJobController.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.central.device.controller; - -import java.util.Map; - -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; -import io.swagger.v3.oas.annotations.tags.Tag; -import io.swagger.v3.oas.annotations.enums.ParameterIn; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import lombok.extern.slf4j.Slf4j; - -import com.central.device.model.LineJob; -import com.central.device.service.ILineJobService; -import com.central.common.model.PageResult; -import com.central.common.model.Result; - -/** - * Wayline mission information of the dock. - * - * @author lsl - * @date 2024-12-19 17:51:53 - */ -@Slf4j -@RestController -@RequestMapping("/linejob") -@Tag(name = "Wayline mission information of the dock.") -@RequiredArgsConstructor -public class LineJobController { - private final ILineJobService lineJobService; - - /** - * 列表 - */ - @Operation(summary = "查询列表") - @Parameters({ - @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), - @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) - }) - @GetMapping - public PageResult list(@RequestParam Map params) { - return lineJobService.findList(params); - } - - /** - * 查询 - */ - @Operation(summary = "查询") - @GetMapping("/{id}") - public Result findUserById(@PathVariable Long id) { - LineJob model = lineJobService.getById(id); - return Result.succeed(model, "查询成功"); - } - - /** - * 新增or更新 - */ - @Operation(summary = "保存") - @PostMapping - public Result save(@RequestBody LineJob lineJob) { - lineJobService.saveOrUpdate(lineJob); - return Result.succeed("保存成功"); - } - - /** - * 删除 - */ - @Operation(summary = "删除") - @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) - @DeleteMapping("/{id}") - public Result delete(@PathVariable Long id) { - lineJobService.removeById(id); - return Result.succeed("删除成功"); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LiveStreamController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LiveStreamController.java deleted file mode 100644 index 04344b2a..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/LiveStreamController.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.central.device.controller; - -import com.alibaba.fastjson.JSONObject; -import com.central.common.model.Result; -import com.central.device.service.LiveStreamService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class LiveStreamController { - - @Autowired - private LiveStreamService liveStreamService; - - @GetMapping("/live/stream-urls") - public JSONObject getJsonStreamUrls(@RequestParam String deviceId) { - return liveStreamService.generateStreamUrls(deviceId); - } - - @GetMapping("/stream-urls") - public Result getStreamUrls(@RequestParam String deviceId) { - return Result.succeed(liveStreamService.generateStreamUrls(deviceId)); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/SFileController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/SFileController.java deleted file mode 100644 index afd99353..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/SFileController.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.central.device.controller; - -import java.util.Map; - -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; -import io.swagger.v3.oas.annotations.tags.Tag; -import io.swagger.v3.oas.annotations.enums.ParameterIn; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import lombok.extern.slf4j.Slf4j; - -import com.central.device.model.SFile; -import com.central.device.service.ISFileService; -import com.central.common.model.PageResult; -import com.central.common.model.Result; - -/** - * Logs file information - * - * @author lsl - * @date 2024-12-19 17:53:36 - */ -@Slf4j -@RestController -@RequestMapping("/sfile") -@Tag(name = "Logs file information") -@RequiredArgsConstructor -public class SFileController { - private final ISFileService sFileService; - - /** - * 列表 - */ - @Operation(summary = "查询列表") - @Parameters({ - @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), - @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) - }) - @GetMapping - public PageResult list(@RequestParam Map params) { - return sFileService.findList(params); - } - - /** - * 查询 - */ - @Operation(summary = "查询") - @GetMapping("/{id}") - public Result findUserById(@PathVariable Long id) { - SFile model = sFileService.getById(id); - return Result.succeed(model, "查询成功"); - } - - /** - * 新增or更新 - */ - @Operation(summary = "保存") - @PostMapping - public Result save(@RequestBody SFile sFile) { - sFileService.saveOrUpdate(sFile); - return Result.succeed("保存成功"); - } - - /** - * 删除 - */ - @Operation(summary = "删除") - @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) - @DeleteMapping("/{id}") - public Result delete(@PathVariable Long id) { - sFileService.removeById(id); - return Result.succeed("删除成功"); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/SFileIndexController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/SFileIndexController.java deleted file mode 100644 index c41912cb..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/SFileIndexController.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.central.device.controller; - -import java.util.Map; - -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; -import io.swagger.v3.oas.annotations.tags.Tag; -import io.swagger.v3.oas.annotations.enums.ParameterIn; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import lombok.extern.slf4j.Slf4j; - -import com.central.device.model.SFileIndex; -import com.central.device.service.ISFileIndexService; -import com.central.common.model.PageResult; -import com.central.common.model.Result; - -/** - * The boot index table corresponding to the logs file. - * - * @author lsl - * @date 2024-12-19 17:53:23 - */ -@Slf4j -@RestController -@RequestMapping("/sfile/index") -@Tag(name = "The boot index table corresponding to the logs file.") -@RequiredArgsConstructor -public class SFileIndexController { - private final ISFileIndexService sFileIndexService; - - /** - * 列表 - */ - @Operation(summary = "查询列表") - @Parameters({ - @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), - @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) - }) - @GetMapping - public PageResult list(@RequestParam Map params) { - return sFileIndexService.findList(params); - } - - /** - * 查询 - */ - @Operation(summary = "查询") - @GetMapping("/{id}") - public Result findUserById(@PathVariable Long id) { - SFileIndex model = sFileIndexService.getById(id); - return Result.succeed(model, "查询成功"); - } - - /** - * 新增or更新 - */ - @Operation(summary = "保存") - @PostMapping - public Result save(@RequestBody SFileIndex sFileIndex) { - sFileIndexService.saveOrUpdate(sFileIndex); - return Result.succeed("保存成功"); - } - - /** - * 删除 - */ - @Operation(summary = "删除") - @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) - @DeleteMapping("/{id}") - public Result delete(@PathVariable Long id) { - sFileIndexService.removeById(id); - return Result.succeed("删除成功"); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/token/ApiTokenController.java b/zlt-business/device-ops-center/src/main/java/com/central/device/controller/token/ApiTokenController.java deleted file mode 100644 index 84330f00..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/controller/token/ApiTokenController.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.central.device.controller.token; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.central.common.model.Result; -import com.central.device.util.Utils; -import com.central.device.util.http.HeaderUtils; -import com.central.device.util.http.HttpRequest; -import com.central.device.util.http.Response; -import com.central.device.util.http.SimpleHttpRequest; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.tags.Tag; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.util.Assert; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -/** - * token获取 - * @author lishilin - * @date 2024-12-31 - */ -@Tag(name = "token获取") -@RestController -@RequestMapping("/token") -public class ApiTokenController { - - @Value("${jetlinks.server.baseUrl}") - private String jetlinksServiceUrl;//= "http://119.45.169.13:8848/"; - - @Autowired - private HeaderUtils headerUtils; - - @Operation(summary = "客户端获取通信平台token") - @GetMapping("/query") - public Result token() throws IOException { - - String url = jetlinksServiceUrl+"/token"; - - HttpRequest request = new SimpleHttpRequest(url); - - Map param = new HashMap<>(2); - param.put("expires",7200*24); - request.headers(headerUtils.createHeadersOfJsonString(JSON.toJSONString(param))); - request.requestBody(JSON.toJSONString(param)); - - - Response response = request.post(); - Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); - JSONObject jsonObject = JSON.parseObject(result.get("")); - Assert.notNull(jsonObject,"获取IOT数据异常"); - if (jsonObject.getString("message").equals("success")) { - return Result.succeed(jsonObject,"获取成功"); - } - return Result.failed("请重试"); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/feign/OrderCenterService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/feign/OrderCenterService.java deleted file mode 100644 index 448d65fd..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/feign/OrderCenterService.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.central.device.feign; - -import com.central.common.constant.ServiceNameConstants; -import com.central.common.model.Result; -import com.central.device.feign.fallback.OrderCenterServiceFallbackFactory; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; - -import java.util.Map; - -/** - * user-center模块远程调用 - * - * @author lsl - * @version 1.0 - * @description user-center模块远程调用 - * @create 2025/1/13 - **/ -@FeignClient(name = ServiceNameConstants.ORDER_SERVICE, fallbackFactory = OrderCenterServiceFallbackFactory.class, dismiss404 = true) -public interface OrderCenterService { - - @PostMapping("/status") - Result updateOrderStatusDoing(@RequestBody String orderNo); - - @GetMapping("/{orderNo}/status") - String getOrderStatusByOrderNo(@PathVariable("orderNo") String orderNo); - - @GetMapping("/qrcode/wayline/{orderNo}") - Map getWaylineByOrderNo(@PathVariable("orderNo") String orderNo); -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/feign/fallback/OrderCenterServiceFallbackFactory.java b/zlt-business/device-ops-center/src/main/java/com/central/device/feign/fallback/OrderCenterServiceFallbackFactory.java deleted file mode 100644 index 80ad4c5f..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/feign/fallback/OrderCenterServiceFallbackFactory.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.central.device.feign.fallback; - -import com.central.common.model.Result; -import com.central.device.feign.OrderCenterService; -import lombok.extern.slf4j.Slf4j; -import org.springframework.cloud.openfeign.FallbackFactory; -import org.springframework.stereotype.Component; - -import java.util.Map; - -/** - * 任务中心调用失败回调 - * - * @author lsl - * @version 1.0 - * @description 任务中心调用失败回调 - * @create 2025/1/17 11:33 - **/ -@Slf4j -@Component -public class OrderCenterServiceFallbackFactory implements FallbackFactory { - - - @Override - public OrderCenterService create(Throwable cause) { - return new OrderCenterService() { - @Override - public Result updateOrderStatusDoing(String orderNo) { - return null; - } - - @Override - public String getOrderStatusByOrderNo(String orderNo) { - return ""; - } - - @Override - public Map getWaylineByOrderNo(String orderNo) { - return null; - } - }; - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/listener/DeviceImportListener.java b/zlt-business/device-ops-center/src/main/java/com/central/device/listener/DeviceImportListener.java deleted file mode 100644 index 74a01388..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/listener/DeviceImportListener.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.central.device.listener; - -import com.alibaba.excel.context.AnalysisContext; -import com.alibaba.excel.read.listener.ReadListener; -import com.central.device.model.AgeDevice; -import com.central.device.model.excel.AgeDeviceExcel; -import com.central.device.service.IAgeDeviceService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -@Slf4j -@RequiredArgsConstructor -public class DeviceImportListener implements ReadListener { - private final IAgeDeviceService deviceService; - private final List deviceList = new ArrayList<>(); - private static final int BATCH_COUNT = 100; - - @Override - public void invoke(AgeDeviceExcel data, AnalysisContext context) { - log.info("解析到一条数据: {}", data); - - // 数据校验 - validateData(data); - - // 转换为实体 - AgeDevice device = data.toDevice(); - - // 设置默认值 - if (device.getCreateTime() == null) { - device.setCreateTime(new Date()); - } - device.setUpdateTime(new Date()); - - deviceList.add(device); - - if (deviceList.size() >= BATCH_COUNT) { - saveData(); - deviceList.clear(); - } - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - saveData(); - log.info("所有数据解析完成!"); - } - - private void validateData(AgeDeviceExcel data) { - if (StringUtils.isEmpty(data.getDeviceSn())) { - throw new IllegalArgumentException("设备序列号不能为空"); - } - if (StringUtils.isEmpty(data.getDeviceName())) { - throw new IllegalArgumentException("设备名称不能为空"); - } - // 检查设备序列号是否已存在 - AgeDevice existDevice = deviceService.getByDeviceSn(data.getDeviceSn()); - if (existDevice != null) { - throw new IllegalArgumentException("设备序列号已存在:" + data.getDeviceSn()); - } - } - - private void saveData() { - if (!deviceList.isEmpty()) { - log.info("开始保存数据,数量:{}", deviceList.size()); - deviceService.saveBatch(deviceList); - } - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceFirmwareMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceFirmwareMapper.java deleted file mode 100644 index b85f42d8..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceFirmwareMapper.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.central.device.mapper; - -import com.central.device.model.AgeDeviceFirmware; -import com.central.db.mapper.SuperMapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Mapper; - -import java.util.List; -import java.util.Map; - -/** - * Firmware file information - * - * @author lsl - * @date 2024-12-19 17:52:54 - */ -@Mapper -public interface AgeDeviceFirmwareMapper extends SuperMapper { - /** - * 分页查询用户列表 - * @param page - * @param params - * @return - */ - List findList(Page page, @Param("p") Map params); -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceHmsMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceHmsMapper.java deleted file mode 100644 index 2c77e129..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceHmsMapper.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.central.device.mapper; - -import com.central.device.model.AgeDeviceHms; -import com.central.db.mapper.SuperMapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Mapper; - -import java.util.List; -import java.util.Map; - -/** - * Device's hms information - * - * @author lsl - * @date 2024-12-19 17:53:01 - */ -@Mapper -public interface AgeDeviceHmsMapper extends SuperMapper { - /** - * 分页查询用户列表 - * @param page - * @param params - * @return - */ - List findList(Page page, @Param("p") Map params); -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceLogsMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceLogsMapper.java deleted file mode 100644 index e6f23dc6..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceLogsMapper.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.central.device.mapper; - -import com.central.device.model.AgeDeviceLogs; -import com.central.db.mapper.SuperMapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Mapper; - -import java.util.List; -import java.util.Map; - -/** - * Log for uploading logs - * - * @author lsl - * @date 2024-12-19 17:53:03 - */ -@Mapper -public interface AgeDeviceLogsMapper extends SuperMapper { - /** - * 分页查询用户列表 - * @param page - * @param params - * @return - */ - List findList(Page page, @Param("p") Map params); -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceMapper.java deleted file mode 100644 index 9ac2fd69..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDeviceMapper.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.central.device.mapper; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.central.db.mapper.SuperMapper; -import com.central.device.model.AgeDevice; -import com.central.device.model.vo.DistributionDataVO; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; - -import java.util.List; -import java.util.Map; - -/** - * Device information - * - * @author lsl - * @date 2024-12-19 17:51:47 - */ -@Mapper -public interface AgeDeviceMapper extends SuperMapper { - /** - * 分页查询用户列表 - * @param page - * @param params - * @return - */ - List findList(Page page, @Param("p") Map params); - - @Select("SELECT COUNT(*) FROM manage_device WHERE is_del = 0") - Long getTotalDevices(); - - @Select("SELECT COUNT(*) FROM manage_device WHERE is_del = 0 AND status = 1") - Long getOnlineDevices(); - - @Select({ - "SELECT", - " device_type as type,", - " COUNT(*) as value", - "FROM manage_device", - "WHERE is_del = 0", - "GROUP BY device_type" - }) - List getDeviceDistribution(); -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDevicePayloadMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDevicePayloadMapper.java deleted file mode 100644 index 35ffe43c..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeDevicePayloadMapper.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.central.device.mapper; - -import com.central.device.model.AgeDevicePayload; -import com.central.db.mapper.SuperMapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Mapper; - -import java.util.List; -import java.util.Map; - -/** - * The payload information of the device. - * - * @author lsl - * @date 2024-12-19 17:53:19 - */ -@Mapper -public interface AgeDevicePayloadMapper extends SuperMapper { - /** - * 分页查询用户列表 - * @param page - * @param params - * @return - */ - List findList(Page page, @Param("p") Map params); -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeFirmwareModelMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeFirmwareModelMapper.java deleted file mode 100644 index 7ee21448..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeFirmwareModelMapper.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.central.device.mapper; - -import com.central.device.model.AgeFirmwareModel; -import com.central.db.mapper.SuperMapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Mapper; - -import java.util.List; -import java.util.Map; - -/** - * - * - * @author lsl - * @date 2024-12-19 17:53:20 - */ -@Mapper -public interface AgeFirmwareModelMapper extends SuperMapper { - /** - * 分页查询用户列表 - * @param page - * @param params - * @return - */ - List findList(Page page, @Param("p") Map params); -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeWorkspaceMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeWorkspaceMapper.java deleted file mode 100644 index 7da5231e..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/AgeWorkspaceMapper.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.central.device.mapper; - -import com.central.device.model.AgeWorkspace; -import com.central.db.mapper.SuperMapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Mapper; - -import java.util.List; -import java.util.Map; - -/** - * - * - * @author lsl - * @date 2024-12-19 17:52:26 - */ -@Mapper -public interface AgeWorkspaceMapper extends SuperMapper { - /** - * 分页查询用户列表 - * @param page - * @param params - * @return - */ - List findList(Page page, @Param("p") Map params); -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/IaFileMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/IaFileMapper.java deleted file mode 100644 index 2b92b51a..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/IaFileMapper.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.central.device.mapper; - -import com.central.device.model.IaFile; -import com.central.db.mapper.SuperMapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Mapper; - -import java.util.List; -import java.util.Map; - -/** - * Media file information - * - * @author lsl - * @date 2024-12-19 17:52:18 - */ -@Mapper -public interface IaFileMapper extends SuperMapper { - /** - * 分页查询用户列表 - * @param page - * @param params - * @return - */ - List findList(Page page, @Param("p") Map params); -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/LineFileMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/LineFileMapper.java deleted file mode 100644 index 1818583a..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/LineFileMapper.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.central.device.mapper; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.central.db.mapper.SuperMapper; -import com.central.device.model.LineFile; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; - -import java.util.List; -import java.util.Map; - -/** - * Wayline file information - * - * @author lsl - * @date 2024-12-19 17:51:52 - */ -@Mapper -public interface LineFileMapper extends SuperMapper { - /** - * 分页查询用户列表 - * @param page - * @param params - * @return - */ - List findList(Page page, @Param("p") Map params); - - @Select("SELECT COUNT(*) FROM wayline_file WHERE is_del = 0") - Long getTotalWaylines(); - - @Select("SELECT COUNT(*) FROM wayline_file WHERE is_del = 0 AND last_use_time >= DATE_SUB(NOW(), INTERVAL 7 DAY)") - Long getActiveWaylines(); -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/LineJobMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/LineJobMapper.java deleted file mode 100644 index f3ccce11..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/LineJobMapper.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.central.device.mapper; - -import com.central.device.model.LineJob; -import com.central.db.mapper.SuperMapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Mapper; - -import java.util.List; -import java.util.Map; - -/** - * Wayline mission information of the dock. - * - * @author lsl - * @date 2024-12-19 17:51:53 - */ -@Mapper -public interface LineJobMapper extends SuperMapper { - /** - * 分页查询用户列表 - * @param page - * @param params - * @return - */ - List findList(Page page, @Param("p") Map params); -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/SFileIndexMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/SFileIndexMapper.java deleted file mode 100644 index 06d359d9..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/SFileIndexMapper.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.central.device.mapper; - -import com.central.device.model.SFileIndex; -import com.central.db.mapper.SuperMapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Mapper; - -import java.util.List; -import java.util.Map; - -/** - * The boot index table corresponding to the logs file. - * - * @author lsl - * @date 2024-12-19 17:53:23 - */ -@Mapper -public interface SFileIndexMapper extends SuperMapper { - /** - * 分页查询用户列表 - * @param page - * @param params - * @return - */ - List findList(Page page, @Param("p") Map params); -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/SFileMapper.java b/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/SFileMapper.java deleted file mode 100644 index 793235b3..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/mapper/SFileMapper.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.central.device.mapper; - -import com.central.device.model.SFile; -import com.central.db.mapper.SuperMapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Mapper; - -import java.util.List; -import java.util.Map; - -/** - * Logs file information - * - * @author lsl - * @date 2024-12-19 17:53:36 - */ -@Mapper -public interface SFileMapper extends SuperMapper { - /** - * 分页查询用户列表 - * @param page - * @param params - * @return - */ - List findList(Page page, @Param("p") Map params); -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/message/ControlEnum.java b/zlt-business/device-ops-center/src/main/java/com/central/device/message/ControlEnum.java deleted file mode 100644 index 5d5c0c07..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/message/ControlEnum.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.central.device.message; - -import lombok.AllArgsConstructor; -import lombok.Getter; - -@Getter -@AllArgsConstructor -public enum ControlEnum { - RETURN_HOME("return_home"), - TAKEOFF_TO_POINT("takeoff_to_point"), - FLY_TO_POINT("fly_to_point"), - FLY_TO_POINT_STOP("fly_to_point_stop"), - FLY_TO_POINT_UPDATE("fly_to_point_stop"), - FLIGHTTASK_PAUSE("flighttask_pause"), - FLIGHTTASK_PREPARE ("flighttask_prepare"), - FLIGHTTASK_RECOVERY( "flighttask_recovery"); - - private final String name; - - // 静态方法:检查某个参数是否是枚举的一个实例 - public static boolean contains(ControlEnum value) { - for (ControlEnum v : ControlEnum.values()) { - if (v == value) { - return true; - } - } - return false; - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/message/ControlMessageConstant.java b/zlt-business/device-ops-center/src/main/java/com/central/device/message/ControlMessageConstant.java deleted file mode 100644 index 15ac1d6c..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/message/ControlMessageConstant.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.central.device.message; - -import lombok.Getter; - -import java.util.HashMap; -import java.util.Map; - - -@Getter -public class ControlMessageConstant { - - - public final static String TAKEOFF_TO_POINT = "{\n" + - " \"data\": {\n" + - "\t \"flight_id\": flight_id,\n" + - "\t \"max_speed\": 5,\n" + - "\t \"rc_lost_action\": 2,\n" + - "\t \"rth_altitude\": 60.0,\n" + - "\t \"rth_mode\": 1,\n" + - "\t \"security_takeoff_height\": 60.0,\n" + - "\t \"target_height\": 70.0,\n" + - "\t \"target_latitude\": 39.102603,\n" + - "\t \"target_longitude\": 117.711972,\n" + - "\t \"commander_mode_lost_action\": 0,\n" + - "\t \"commander_flight_mode\": 1,\n" + - "\t \"commander_flight_height\": 70.0,\n" + - "\t \"simulate_mission\": {\n" + - "\t },\n" + - "\t \"flight_safety_advance_check\": 0\n" + - "\t},\n" + - "\t\"method\": \"takeoff_to_point\"\n" + - "}"; - - public final static String FLY_TO_ID = "{\n" + - "\t\"data\": {\n" + - "\t\t\"fly_to_id\": \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx\",\n" + - "\t\t\"max_speed\": 12,\n" + - "\t\t\"points\": [\n" + - "\t\t\t{\n" + - "\t\t\t\t\"height\": 100,\n" + - "\t\t\t\t\"latitude\": 12.23,\n" + - "\t\t\t\t\"longitude\": 12.23\n" + - "\t\t\t}\n" + - "\t\t]\n" + - "\t},\n" + - "\t\"method\": \"fly_to_point\"\n" + - "}"; - public final static String FLY_TO_ID_STOP = "{\n" + - "\t\"data\": {},\n" + - "\t\"method\": \"fly_to_point_stop\"\n" + - "}"; - public final static String FLY_TO_POINT_UPDATE = "{\n" + - "\t\"data\": {\n" + - "\t\t\"max_speed\": 12,\n" + - "\t\t\"points\": [\n" + - "\t\t\t{\n" + - "\t\t\t\t\"height\": 100,\n" + - "\t\t\t\t\"latitude\": 12.23,\n" + - "\t\t\t\t\"longitude\": 12.23\n" + - "\t\t\t}\n" + - "\t\t]\n" + - "\t},\n" + - "\t\"method\": \"fly_to_point_update\"\n" + - "}"; - public final static String RETURN_HOME = "{\n" + - "\t\"data\": {},\n" + - "\t\"method\": \"return_home\"\n" + - "}"; - - public final static String FLIGHTTASK_PAUSE = "{\"data\": {}, \"method\": \"flighttask_pause\"}"; - - public final static String FLIGHTTASK_PREPARE = "{\"data\": {},\"method\": \"flighttask_prepare\"}"; - - public final static String FLIGHTTASK_RECOVERY = "{\"data\": {}, \"method\": \"flighttask_recovery\"}"; - - public Map CONTROL_MESSAGE_MAP - = new HashMap(); - - public ControlMessageConstant(){ - CONTROL_MESSAGE_MAP.put("fly_to_point_stop", FLY_TO_ID_STOP); - CONTROL_MESSAGE_MAP.put("fly_to_point", FLY_TO_ID); - CONTROL_MESSAGE_MAP.put("fly_to_point_update", FLY_TO_POINT_UPDATE); - CONTROL_MESSAGE_MAP.put("flighttask_pause", FLIGHTTASK_PAUSE); - CONTROL_MESSAGE_MAP.put("flighttask_prepare", FLIGHTTASK_PREPARE); - CONTROL_MESSAGE_MAP.put("return_home", RETURN_HOME); - CONTROL_MESSAGE_MAP.put("flighttask_recovery", FLIGHTTASK_RECOVERY); - - } - - -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/message/iot说明#上报主题.md b/zlt-business/device-ops-center/src/main/java/com/central/device/message/iot说明#上报主题.md deleted file mode 100644 index b515d017..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/message/iot说明#上报主题.md +++ /dev/null @@ -1,747 +0,0 @@ -# iot说明 - -# 上报主题说明: - -设备运行日志上报主题:/fire_alarm - -# 上报内容: - -## 状态包: - -| home_position_is_valid | Home 点有效性 | enum_int | {"0":"无效","1":"有效"} | | r | 0 | -| --- | --- | --- | --- | --- | --- | --- | -| heading | 机场朝向角 | double | {"max":"180","min":"-180","step":"","unit_name":"度 / °"} | | r | 0 | -| rtcm_info | 机场 RTK 标定源 | struct | | | r | 1 | -| »mount_point | 网络 RTK 挂载点信息 | text | | | | 0 | -| »port | 网络端口信息 | text | | | | 0 | -| »host | 网络 host 信息 | text | | | | 0 | -| »rtcm_device_type | 设备类型 | enum_int | {"1":"机场"} | | | 0 | -| »source_type | 标定类型 | enum_int | {"0":"未标定","1":"自收敛标定","2":"手动标定","3":"网络RTK标定"} | | | 0 | -| wireless_link_topo | 图传连接拓扑 | struct | | | r | 1 | -| »secret_code | 加密编码 | array | {"size": 28, "item_type": int} | | | 0 | -| »center_node | 飞行器对频信息 | struct | | | | 0 | -| »»sdr_id | 扰码信息 | int | | | | 0 | -| »»sn | 设备sn | text | | | | 0 | -| »leaf_nodes | 机场或遥控器对频信息 | array | {"size": -, "item_type": struct} | | | 0 | -| »»sdr_id | 扰码信息 | int | | | | 0 | -| »»sn | 设备sn | text | | | | 0 | -| »»control_source_index | 控制源序号 | int | {"max":"2","min":"1","step":"1","unit_name":"无 / "} | | | 0 | -| air_conditioner | 机场空调工作状态信息 | struct | | | r | 0 | -| »air_conditioner_state | 机场空调状态 | enum_int | {"0":"空闲模式(无制冷、制热、除湿等)","1":"制冷模式","2":"制热模式","3":"除湿模式","4":"制冷退出模式","5":"制热退出模式","6":"除湿退出模式","7":"制冷准备模式","8":"制热准备模式","9":"除湿准备模式"} | 机场空调工作状态信息,空调仅存在一种工作模式 | | 0 | -| »switch_time | 剩余等待可切换时间 | int | {"unit_name":"秒 / s"} | 空调状态顺序为准备模式切换到工作状模式、随后可操作后切换到退出模式、退出完成后切换到空闲模式,因此本物模型表示进行某个指令操作后还需要多久可以切换至下一状态。例如当前为空闲状态,开启制冷模式后将进入制冷准备模式,则本时间表示还需要多久可以进入制冷工作模式。以此类推 | | 0 | -| air_transfer_enable | 空中回传 | bool | {"false":"关闭","true":"开启"} | 用户在指令飞行过程中拍照的照片快速回传至云端 | rw | 1 | -| silent_mode | 机场静音模式 | enum_int | {"0":"非静音模式","1":"静音模式"} | 开启静音模式,意味着:1. 风扇转速降低、空调制冷性能下降、炎热天气下作业间隔变长。2. 蜂鸣器声音将关闭,开关舱盖时请注意周围安全。3. 机场待机状态的白色指示灯关闭,其他运行状态的指示灯正常。 | rw | 1 | -| user_experience_improvement | 用户体验改善计划 | enum_int | {"0":"初始状态","1":"拒绝加入用户体验改善计划","2":"同意加入用户体验改善计划"} | | rw | 1 | -| dongle_infos | 4G Dongle信息 | array | {"size": -, "item_type": struct} | | r | 1 | -| »imei | dongle imei | text | | Dongle 的唯一识别标志 | r | 0 | -| »dongle_type | Dongle 类型 | enum_int | {"6":"旧 Dongle","10":"支持 eSIM 的新 Dongle"} | Dongle 类型 | r | 0 | -| »eid | dongle eid | text | | eSIM 的唯一识别标志,用于公众号查询套餐、购买服务 | r | 0 | -| »esim_activate_state | eSIM 激活状态 | enum_int | {"0":"未激活","1":"已激活"} | 需要激活才能使用 | r | 0 | -| »sim_card_state | SIM 卡状态 | enum_int | {"0":"未插入","1":"已插入"} | Dongle 中实体 SIM 卡的插入状态 | r | 0 | -| »sim_slot | SIM 卡槽使能状态 | enum_int | {"0":"未知","1":"实体 SIM 卡","2":"eSIM"} | 标识 Dongle 当前正在使用的 SIM 卡槽 | r | 0 | -| »esim_infos | eSIM 信息 | array | {"size": -, "item_type": struct} | | r | 0 | -| »»telecom_operator | 支持的运营商 | enum_int | {"0":"未知","1":"移动","2":"联通","3":"电信"} | eSIM 支持的运营商 | r | 0 | -| »»enabled | eSIM 使能状态 | bool | {"false":"未使用","true":"使用中"} | 同时刻只能有一个 eSIM 是使能的 | r | 0 | -| »»iccid | sim iccid | text | | SIM 卡的唯一识别标志,可以用于实体 SIM 卡的套餐购买 | r | 0 | -| »sim_info | SIM 卡信息 | struct | | 可插入 Dongle 的实体 SIM 卡信息 | r | 0 | -| »»telecom_operator | 支持的运营商 | enum_int | {"0":"未知","1":"移动","2":"联通","3":"电信"} | SIM 卡支持的运营商 | r | 0 | -| »»sim_type | SIM 卡类型 | enum_int | {"0":"未知","1":"其他普通 SIM 卡","2":"三网卡"} | 实体 SIM 卡的类型 | r | 0 | -| »»iccid | sim iccid | text | | SIM 卡的唯一识别标志,可以用于实体 SIM 卡的套餐购买 | r | 0 | -| drone_battery_maintenance_info | 飞行器电池保养信息 | struct | | | | 0 | -| »maintenance_state | 保养状态 | enum_int | {"0":"无需保养","1":"待保养","2":"正在保养"} | | | 0 | -| »maintenance_time_left | 电池保养剩余时间 | int | {"unit_name":"小时 / h"} | 向下取整 | | 0 | -| »heat_state | 电池加热保温状态 | enum_int | {"0":"电池未开启加热或保温","1":"电池在加热中","2":"电池在保温中"} | 当飞行器舱内关机时由本物模型上报机场连接飞行器的电池加热保温信息 | | 0 | -| »batteries | 电池详细信息 | array | {"size": -, "item_type": struct} | 当飞行器舱内关机时由本物模型上报机场连接飞行器的电池信息,基本数据与飞行器物模型中电池信息基本保持一致 | | 0 | -| »»capacity_percent | 电池剩余电量 | int | {"max":100,"min":0} | 保留小数点后一位,正常范围0-100,设备端获取不到数据的异常值为 32767 | | 0 | -| »»index | 电池序号 | enum_int | {"0":"左电池","1":"右电池"} | | | 0 | -| »»voltage | 电压 | int | {"unit_name":"毫伏 / mV"} | 正常范围0-28000mV,设备端获取不到数据的异常值为32767 | | 0 | -| »»temperature | 温度 | float | {"unit_name":"摄氏度 / °C"} | 保留小数点后一位,正常范围-40-150°C,设备端获取不到数据的异常值为32767 | | 0 | -| air_conditioner | 机场空调工作状态信息 | struct | | | r | 0 | -| »air_conditioner_state | 机场空调状态 | enum_int | {"0":"空闲模式(无制冷、制热、除湿等)","1":"制冷模式","2":"制热模式","3":"除湿模式","4":"制冷退出模式","5":"制热退出模式","6":"除湿退出模式","7":"制冷准备模式","8":"制热准备模式","9":"除湿准备模式"} | 机场空调工作状态信息,空调仅存在一种工作模式 | | 0 | -| »switch_time | 剩余等待可切换时间 | int | {"unit_name":"秒 / s"} | 模式切换顺序为准备模式、工作(制冷、制热、除湿)模式、退出模式、空闲模式。本属性将上报,可以切换下一个模式指令还需要等待的时间。例如当前机场空调在进入制冷模式后,必须制冷5分钟后才可以退出制冷模式,本属性将上报还需要多久退出制冷模式,为0表示随时可退出 | | 0 | -| maintain_status | 保养信息 | struct | | | r | 0 | -| »maintain_status_array | 保养信息数组 | array | {"size": -, "item_type": struct} | | | 0 | -| »»state | 保养状态 | enum_int | {"0":"无保养","1":"有保养"} | | | 0 | -| »»last_maintain_type | 上一次保养类型 | enum_int | {"0":"无保养","17":"机场常规保养","18":"机场深度保养"} | | | 0 | -| »»last_maintain_time | 上一次保养时间 | date | {"unit_name":"秒 / s"} | | | 0 | -| »»last_maintain_work_sorties | 上一次保养时作业架次 | int | {"max":"2147483647","min":"0","step":"1"} | | | 0 | -| position_state | 搜星状态 | struct | | | r | 0 | -| »is_calibration | 是否标定 | enum_int | {"0":"未标定","1":"已标定"} | | | 0 | -| »is_fixed | 是否收敛 | enum_int | {"0":"未开始","1":"收敛中","2":"收敛成功","3":"收敛失败"} | | | 0 | -| »quality | 搜星档位 | enum_int | {"1":"1档","2":"2档","3":"3档","4":"4档","5":"5档","10":"RTK fixed"} | | | 0 | -| »gps_number | GPS 搜星数量 | int | | | | 0 | -| »rtk_number | RTK 搜星数量 | int | | | | 0 | -| emergency_stop_state | 紧急停止按钮状态 | enum_int | {"0":"关闭","1":"开启"} | | r | 0 | -| drone_charge_state | 飞行器充电状态 | struct | | 飞行器充电状态 | r | 0 | -| »capacity_percent | 电量百分比 | int | {"max":"100","min":"0"} | | | 0 | -| »state | 充电状态 | enum_int | {"0":"空闲","1":"充电中"} | | | 0 | -| backup_battery | 机场备用电池信息 | struct | | | r | 0 | -| »switch | 备用电池开关 | enum_int | {"0":"关闭","1":"开启"} | | | 0 | -| »voltage | 备用电池电压 | int | {"desc":"备用电池关闭时电压为0","max":"30000","min":"0","step":"1","unit_name":"毫伏 / mV"} | | | 0 | -| »temperature | 备用电池温度 | float | {"step":"0.1","unit_name":"摄氏度 / °C"} | 保留小数点后一位 | | 0 | -| alarm_state | 机场声光报警状态 | enum_int | {"0":"关闭","1":"开启"} | | r | 0 | -| battery_store_mode | 电池运行模式 | enum_int | {"1":"计划模式","2":"待命模式"} | 计划模式适合规律作业场景,无任务时电池电量保持在55%~60%,电池寿命较长。待命模式适合应急作业场景,无任务时电池电量保持在90%~95%,电池寿命较短。 | r | 0 | -| activation_time | 机场激活时间(unix 时间戳) | int | {"unit_name":"秒 / s"} | | r | 0 | -| height | 椭球高度 | double | {"unit_name":"米 / m"} | | r | 0 | -| alternate_land_point | 备降点 | struct | | | r | 0 | -| »longitude | 经度 | float | {} | | | 0 | -| »latitude | 纬度 | float | {} | | | 0 | -| »safe_land_height | 安全高度(备降转移高) | float | {} | | | 0 | -| »is_configured | 是否设置备降点 | enum_int | {"0":"未设置","1":"已设置"} | | | 0 | -| »height | 椭球高度 | float | | | | 0 | -| compatible_status | 固件一致性 | enum_int | {"0":"不需要一致性升级","1":"需要一致性升级"} | 一致性升级:指飞行器某些模块的固件版本与系统匹配版本不一致,需要进行升级。常见的情况例如:飞行器与遥控器已经升级至最新版本,但替换电池时发现电池未升级,此时一致性升级将被提示。普通升级:开发者将飞行器所有模块升级至指定固件版本。 | r | 1 | -| acc_time | 机场累计运行时长 | int | {"unit_name":"秒 / s"} | | r | 1 | -| first_power_on | 首次上电时间 | int | {"unit_name":"毫秒 / ms"} | | r | 0 | -| storage | 存储容量 | struct | | | r | 0 | -| »total | 总容量 | int | {"unit_name":"千字节 / KB"} | | | 0 | -| »used | 已使用容量 | int | {"unit_name":"千字节 / KB"} | | | 0 | -| working_current | 工作电流 | float | {"unit_name":"毫安 / mA"} | | r | 0 | -| working_voltage | 工作电压 | int | {"unit_name":"毫伏 / mV"} | | r | 0 | -| humidity | 舱内湿度 | float | {"max":"100","min":"0","step":"0.1","unit_name":"相对湿度 / %RH"} | | r | 0 | -| temperature | 舱内温度 | float | {"unit_name":"摄氏度 / °C"} | | r | 0 | -| environment_temperature | 环境温度 | float | {"unit_name":"摄氏度 / °C"} | | r | 0 | -| wind_speed | 风速 | float | {"unit_name":"米每秒 / m/s"} | | r | 0 | -| rainfall | 降雨量 | enum_int | {"0":"无雨","1":"小雨","2":"中雨","3":"大雨"} | | r | 0 | -| live_capacity | 网关设备直播能力 | struct | | | r | 1 | -| »available_video_number | 可选择推流的码流数量 | int | | | | 0 | -| »coexist_video_number_max | 可同时推流的最大码流数量 | int | | | | 0 | -| »device_list | 可选择的视频设备源 | array | {"size": -, "item_type": struct} | 可选择的视频设备源(设备层,比如飞行器) | | 0 | -| »»sn | 飞行器等视频源设备序列号(SN) | text | | | | 0 | -| »»available_video_number | 该序列号设备可以被选择推流的码流数 | int | | | | 0 | -| »»coexist_video_number_max | 该序列号设备可以同时被推流的码流数 | int | | | | 0 | -| »»camera_list | 该序列号设备上的相机列表 | array | {"size": -, "item_type": struct} | | | 0 | -| »»»camera_index | 相机索引 | text | | 使用 *{type-subtype-gimbalindex}* 的格式 | | 0 | -| »»»available_video_number | 该相机级别的视频源可以被选择推流的码流数 | int | | | | 0 | -| »»»coexist_video_number_max | 该相机级别的视频源可以同时被推流的码流数 | int | | | | 0 | -| »»»video_list | 该相机级别的视频源可以选择的码流列表 | array | {"size": -, "item_type": struct} | | | 0 | -| »»»»video_index | 该相机级别的视频源可以选择的码流索引 | text | | | | 0 | -| »»»»video_type | 该相机级别的视频源可以选择的码流类型 | text | | | | 0 | -| »»»»switchable_video_types | 该视频流支持切换的视频镜头类型 | array | {"size": -, "item_type": text} | | | 0 | -| live_status | 网关当前整体直播状态推送 | array | {"size": -, "item_type": struct} | | r | 1 | -| »video_id | 直播码流标识符 | text | | 某路在推视频码流的标识符,格式为 *{sn}/{camera_index}/{video_index}*。其中 *{sn}* 为视频源设备序列号。*{camera_index}* 为相机索引,使用 *{type-subtype-gimbalindex}* 的格式。*{video_index}* 为该相机级别的视频源可以选择的码流索引。 | | 0 | -| »video_type | 视频类型 | text | {"length":"24"} | 表明视频镜头的类型,如normal/wide/zoom/infrared等 | | 0 | -| »video_quality | 直播码流的质量 | enum_int | {"0":"自适应","1":"流畅","2":"标清","3":"高清","4":"超清"} | | | 0 | -| »status | 直播状态 | enum_int | {"0":"未直播","1":"在直播"} | | | 0 | -| »error_status | 错误码 | int | {"length":6} | | | 0 | -| wireless_link | 图传链路 | struct | | | r | 0 | -| »dongle_number | 飞行器上 Dongle 数量 | int | | | | 0 | -| »4g_link_state | 4G 链路连接状态 | enum_int | {"0":"断开","1":"连接"} | | | 0 | -| »sdr_link_state | SDR 链路连接状态 | enum_int | {"0":"断开","1":"连接"} | | | 0 | -| »link_workmode | 机场的图传链路模式 | enum_int | {"0":"SDR 模式","1":"4G 融合模式"} | | | 0 | -| »sdr_quality | SDR 信号质量 | int | {"max":"5","min":"0","step":"1"} | | | 0 | -| »4g_quality | 总体 4G 信号质量 | int | {"max":"5","min":"0","step":"1"} | | | 0 | -| »4g_uav_quality | 天端 4G 信号质量 | int | {"max":"5","min":"0","step":"1"} | 飞行器端与 4G 服务器之间的信号质量 | | 0 | -| »4g_gnd_quality | 地端 4G 信号质量 | int | {"max":"5","min":"0","step":"1"} | 地面端(如遥控器、DJI Dock等)与 4G 服务器之间的信号质量 | | 0 | -| »sdr_freq_band | SDR 频段 | float | | | | 0 | -| »4g_freq_band | 4G 频段 | float | | | | 0 | -| media_file_detail | 媒体文件上传细节 | struct | | | r | 0 | -| »remain_upload | 待上传数量 | int | | | | 0 | -| job_number | 机场累计作业次数 | int | {"unit_name":"次 / count"} | | r | 0 | -| drone_in_dock | 飞行器是否在舱 | enum_int | {"0":"舱外","1":"舱内"} | | r | 0 | -| network_state | 网络状态 | struct | | | r | 0 | -| »type | 网络类型 | enum_int | {"1":"4G","2":"以太网"} | | | 0 | -| »quality | 网络质量 | enum_int | {"0":"无信号","1":"差","2":"较差","3":"一般","4":"较好","5":"好"} | | | 0 | -| »rate | 网络速率 | float | {"unit_name":"千字节每秒 / KB/s"} | | | 0 | -| supplement_light_state | 补光灯状态 | enum_int | {"0":"关闭","1":"打开"} | | r | 0 | -| cover_state | 舱盖状态 | enum_int | {"0":"关闭","1":"打开","2":"半开","3":"舱盖状态异常"} | | r | 0 | -| sub_device | 子设备状态 | struct | | | r | 0 | -| »device_sn | 子设备序列号(SN) | text | | | | 0 | -| »device_model_key | 子设备枚举值 | text | | 格式为 *{domain-type-subtype}* | | 0 | -| »device_online_status | 机场停机坪上的飞行器开机状态 | enum_int | {"0":"关机","1":"开机"} | | | 0 | -| »device_paired | 机场停机坪上的飞行器是否与机场对频 | enum_int | {"0":"未对频","1":"已对频"} | | | 0 | -| flighttask_step_code | 机场任务状态 | enum_int | {"0":"作业准备中","1":"飞行作业中","2":"作业后状态恢复","3":"自定义飞行区更新中","4":"地形障碍物更新中","5":"任务空闲","255":"飞行器异常","256":"未知状态"} | | r | 0 | -| mode_code | 机场状态 | enum_int | {"0":"空闲中","1":"现场调试","2":"远程调试","3":"固件升级中","4":"作业中"} | | r | 0 | -| firmware_upgrade_status | 固件升级状态 | enum_int | {"0":"未升级","1":"升级中"} | | r | 1 | -| firmware_version | 固件版本 | text | {"length":"64"} | | r | 1 | -| latitude | 纬度 | double | {"max":"90","min":"-90","step":"0.01"} | | r | 0 | -| longitude | 经度 | double | {"max":"180","min":"-180","step":"0.01"} | 网关设备的经度 | r | | - -```json -{ - "bid": "939bf66d-eb0a-4804-baad-7cbc4e175253", - "data": { - "drc_state": 0, - "flighttask_prepare_capacity": 1, - "flighttask_step_code": 1, - "media_file_detail": { "remain_upload": 0 }, - "sdr": { "down_quality": 100, "frequency_band": 2.4, "up_quality": 100 }, - "user_experience_improvement": 3, - "wireless_link": { - "4g_freq_band": 5.8, - "4g_gnd_quality": 5, - "4g_link_state": 1, - "4g_quality": 5, - "4g_uav_quality": 5, - "dongle_number": 1, - "link_workmode": 1, - "sdr_freq_band": 5.8, - "sdr_link_state": 1, - "sdr_quality": 5 - } - }, - "tid": "795e35f0-109c-4ff5-bd83-f9a7ceb8e2c6", - "timestamp": 1735466829704, - "gateway": "7CTDM6F00B744S" -} -``` - -```json -{ - "tid": "3c2afb04-e637-4b16-8cd0-c15094527398", - "bid": "933bac6c-338e-4ecd-90b9-951308c439e0", - "timestamp": 1735466829710, - "data": { - "network_state": { "type": 2, "quality": 0, "rate": 32 }, - "drone_charge_state": { "state": 0, "capacity_percent": 72 }, - "drone_in_dock": 0, - "rainfall": 0, - "wind_speed": 0, - "environment_temperature": 7.1, - "temperature": 6.6, - "humidity": 45, - "heading": -72.980140686035156, - "home_position_is_valid": 1, - "latitude": 39.10260381347603, - "longitude": 117.71197297315571, - "height": 5.8588995933532715, - "alternate_land_point": { - "latitude": 39.102598739909752, - "longitude": 117.71198964942272, - "height": 0, - "safe_land_height": 30, - "is_configured": 1 - }, - "first_power_on": 1631945855969, - "position_state": { - "is_calibration": 1, - "is_fixed": 2, - "quality": 5, - "gps_number": 7, - "rtk_number": 36 - }, - "storage": { "total": 79981124, "used": 69124 }, - "mode_code": 4, - "cover_state": 0, - "silent_mode": 1, - "supplement_light_state": 0, - "emergency_stop_state": 0, - "air_conditioner": { "air_conditioner_state": 0, "switch_time": 0 }, - "battery_store_mode": 2, - "alarm_state": 0, - "putter_state": 0, - "sub_device": { - "device_sn": "1581F6QAD249M00GCRF5", - "device_online_status": 1, - "device_paired": 1 - } - }, - "gateway": "7CTDM6F00B744S" -} -``` - -```json -{ - "tid": "f219d8d5-2c57-4a0e-b9a9-d72c77ea7dbe", - "bid": "f188e509-41d3-4e70-bb63-938b15193387", - "timestamp": 1735466829726, - "data": { - "job_number": 48, - "acc_time": 618911, - "activation_time": 1734482524, - "maintain_status": { - "maintain_status_array": [ - { - "state": 0, - "last_maintain_type": 17, - "last_maintain_time": 0, - "last_maintain_work_sorties": 0 - }, - { - "state": 0, - "last_maintain_type": 18, - "last_maintain_time": 0, - "last_maintain_work_sorties": 0 - } - ] - }, - "electric_supply_voltage": 32767, - "working_voltage": 27742, - "working_current": 0, - "backup_battery": { "voltage": 13601, "temperature": 12.4, "switch": 1 }, - "drone_battery_maintenance_info": { - "maintenance_state": 0, - "maintenance_time_left": 0, - "heat_state": 0, - "batteries": [ - { - "index": 0, - "capacity_percent": 72, - "voltage": 15366, - "temperature": 24.9 - } - ] - } - }, - "gateway": "7CTDM6F00B744S" -} -``` - -```json -{ - "bid": "883e903f-1ff7-4015-8c5c-a0c0c267aff5", - "data": { - "rtcm_info": { - "host": "120.253.226.97", - "mount_point": "RTCM33_GRCEJ", - "port": "8002", - "rtcm_device_type": 1, - "source_type": 3 - } - }, - "need_reply": 1, - "tid": "3116ca3e-3335-4467-8b8e-c2b028fce07f", - "timestamp": 1735466831441, - "gateway": "7CTDM6F00B744S" -} -``` - -飞机: - -| best_link_gateway | 飞行器图传连接质量最好的网关SN | text | | 蛙跳任务场景下,当飞行器对频了两个机场后,推送连接最好的机场SN | r | 1 | -| --- | --- | --- | --- | --- | --- | --- | -| wireless_link_topo | 图传连接拓扑 | struct | | | r | 1 | -| »secret_code | 加密编码 | array | {"size": 28, "item_type": int} | | | 0 | -| »center_node | 飞行器对频信息 | struct | | | | 0 | -| »»sdr_id | 扰码信息 | int | | | | 0 | -| »»sn | 设备sn | text | | | | 0 | -| »leaf_nodes | 当前连接的机场或遥控器对频信息 | array | {"size": -, "item_type": struct} | | | 0 | -| »»sdr_id | 扰码信息 | int | | | | 0 | -| »»sn | 设备sn | text | | | | 0 | -| »»control_source_index | 控制源序号 | int | {"max":"2","min":"1","step":"1","unit_name":"无 / "} | | | 0 | -| cameras | 飞行器相机信息 | array | {"size": -, "item_type": struct} | | r | 0 | -| »remain_photo_num | 剩余拍照张数 | int | | 剩余拍照张数 | | 0 | -| »remain_record_duration | 剩余录像时间 | int | {"unit_name":"秒 / s"} | 剩余录像时间 | | 0 | -| »record_time | 视频录制时长 | int | {"unit_name":"秒 / s"} | 视频录制时长 | | 0 | -| »payload_index | 负载编号 | text | | 负载编号,相机枚举值。非标准的 device_mode_key,格式为 {type-subtype-gimbalindex},可以参考[**产品支持open in new window**](https://developer.dji.com/doc/cloud-api-tutorial/cn/overview/product-support.html) | | 0 | -| »camera_mode | 相机模式 | enum_int | {"0":"拍照","1":"录像","2":"智能低光","3":"全景拍照"} | 相机模式 | | 0 | -| »photo_state | 拍照状态 | enum_int | {"0":"空闲","1":"拍照中"} | 拍照状态 | | 0 | -| »screen_split_enable | 分屏是否使能 | bool | {"0":"分屏使能关闭","1":"分屏使能开启"} | | | 0 | -| »recording_state | 录像状态 | enum_int | {"0":"空闲","1":"录像中"} | 录像状态 | | 0 | -| »zoom_factor | 变焦倍数 | float | | | | 0 | -| »ir_zoom_factor | 红外变焦倍数 | float | | 红外变焦倍数 | | 0 | -| »liveview_world_region | 视场角(FOV)在 liveview 中的区域 | struct | | 变焦相机的视场角相对于广角相机或者红外相机的视场角,在 liveview 中会有所不同。坐标原点为镜头左上角。 | | 0 | -| »»left | 左上角的 x 轴起始点 | float | | 左上角的 x 轴起始点 | r | 0 | -| »»top | 左上角的 y 轴起始点 | float | | 左上角的 y 轴起始点 | r | 0 | -| »»right | 右下角的 x 轴起始点 | float | | 右下角的 x 轴起始点 | r | 0 | -| »»bottom | 右下角的 y 轴起始点 | float | | 右下角的 y 轴起始点 | r | 0 | -| »photo_storage_settings | 照片存储设置集合 | array | {"size": -, "item_type": enum_string} | 取值范围{current, vision, ir} | | 0 | -| »video_storage_settings | 视频存储设置集合 | array | {"size": -, "item_type": enum_string} | 取值范围{current, vision, ir} | | 0 | -| »wide_exposure_mode | 广角镜头曝光模式 | enum_int | {"1":"自动","2":"快门优先曝光","3":"光圈优先曝光","4":"手动曝光"} | 当前配置的广角镜头曝光模式 | | 0 | -| »wide_iso | 广角镜头感光度 | enum_int | {"0":"Auto","1":"Auto(High Sense)","2":"50","3":"100","4":"200","5":"400","6":"800","7":"1600","8":"3200","9":"6400","10":"12800","11":"25600","255":"FIXED"} | 当前配置的广角镜头感光度 | | 0 | -| »wide_shutter_speed | 广角镜头快门速度 | enum_int | {"0":"1/8000 s","1":"1/6400 s","2":"1/6000 s","3":"1/5000 s","4":"1/4000 s","5":"1/3200 s","6":"1/3000 s","7":"1/2500 s","8":"1/2000 s","9":"1/1600 s","10":"1/1500 s","11":"1/1250 s","12":"1/1000 s","13":"1/800 s","14":"1/725 s","15":"1/640 s","16":"1/500 s","17":"1/400 s","18":"1/350 s","19":"1/320 s","20":"1/250 s","21":"1/240 s","22":"1/200 s","23":"1/180 s","24":"1/160 s","25":"1/125 s","26":"1/120 s","27":"1/100 s","28":"1/90 s","29":"1/80 s","30":"1/60 s","31":"1/50 s","32":"1/40 s","33":"1/30 s","34":"1/25 s","35":"1/20 s","36":"1/15 s","37":"1/12.5 s","38":"1/10 s","39":"1/8 s","40":"1/6.25 s","41":"1/5 s","42":"1/4 s","43":"1/3 s","44":"1/2.5 s","45":"1/2 s","46":"1/1.67 s","47":"1/1.25 s","48":"1.0 s","49":"1.3 s","50":"1.6 s","51":"2.0 s","52":"2.5 s","53":"3.0 s","54":"3.2 s","55":"4.0 s","56":"5.0 s","57":"6.0 s","58":"7.0 s","59":"8.0 s","65534":"Auto"} | 当前配置的广角镜头快门速度 | | 0 | -| »wide_exposure_value | 广角镜头曝光值 | enum_int | {"1":"-5.0EV","2":"-4.7EV","3":"-4.3EV","4":"-4.0EV","5":"-3.7EV","6":"-3.3EV","7":"-3.0EV","8":"-2.7EV","9":"-2.3EV","10":"-2.0EV","11":"-1.7EV","12":"-1.3EV","13":"-1.0EV","14":"-0.7EV","15":"-0.3EV","16":"0EV","17":"0.3EV","18":"0.7EV","19":"1.0EV","20":"1.3EV","21":"1.7EV","22":"2.0EV","23":"2.3EV","24":"2.7EV","25":"3.0EV","26":"3.3EV","27":"3.7EV","28":"4.0EV","29":"4.3EV","30":"4.7EV","31":"5.0EV","255":"FIXED"} | 当前配置的广角镜头曝光值 | | 0 | -| »zoom_exposure_mode | 变焦镜头曝光模式 | enum_int | {"1":"自动","2":"快门优先曝光","3":"光圈优先曝光","4":"手动曝光"} | 当前配置的变焦镜头曝光模式 | | 0 | -| »zoom_iso | 变焦镜头感光度 | enum_int | {"0":"Auto","1":"Auto(High Sense)","2":"50","3":"100","4":"200","5":"400","6":"800","7":"1600","8":"3200","9":"6400","10":"12800","11":"25600","255":"FIXED"} | 当前配置的变焦镜头感光度 | | 0 | -| »zoom_shutter_speed | 变焦镜头快门速度 | enum_int | {"0":"1/8000 s","1":"1/6400 s","2":"1/6000 s","3":"1/5000 s","4":"1/4000 s","5":"1/3200 s","6":"1/3000 s","7":"1/2500 s","8":"1/2000 s","9":"1/1600 s","10":"1/1500 s","11":"1/1250 s","12":"1/1000 s","13":"1/800 s","14":"1/725 s","15":"1/640 s","16":"1/500 s","17":"1/400 s","18":"1/350 s","19":"1/320 s","20":"1/250 s","21":"1/240 s","22":"1/200 s","23":"1/180 s","24":"1/160 s","25":"1/125 s","26":"1/120 s","27":"1/100 s","28":"1/90 s","29":"1/80 s","30":"1/60 s","31":"1/50 s","32":"1/40 s","33":"1/30 s","34":"1/25 s","35":"1/20 s","36":"1/15 s","37":"1/12.5 s","38":"1/10 s","39":"1/8 s","40":"1/6.25 s","41":"1/5 s","42":"1/4 s","43":"1/3 s","44":"1/2.5 s","45":"1/2 s","46":"1/1.67 s","47":"1/1.25 s","48":"1.0 s","49":"1.3 s","50":"1.6 s","51":"2.0 s","52":"2.5 s","53":"3.0 s","54":"3.2 s","55":"4.0 s","56":"5.0 s","57":"6.0 s","58":"7.0 s","59":"8.0 s","65534":"Auto"} | 当前配置的变焦镜头快门速度 | | 0 | -| »zoom_exposure_value | 变焦镜头曝光值 | enum_int | {"1":"-5.0EV","2":"-4.7EV","3":"-4.3EV","4":"-4.0EV","5":"-3.7EV","6":"-3.3EV","7":"-3.0EV","8":"-2.7EV","9":"-2.3EV","10":"-2.0EV","11":"-1.7EV","12":"-1.3EV","13":"-1.0EV","14":"-0.7EV","15":"-0.3EV","16":"0EV","17":"0.3EV","18":"0.7EV","19":"1.0EV","20":"1.3EV","21":"1.7EV","22":"2.0EV","23":"2.3EV","24":"2.7EV","25":"3.0EV","26":"3.3EV","27":"3.7EV","28":"4.0EV","29":"4.3EV","30":"4.7EV","31":"5.0EV","255":"FIXED"} | 当前配置的变焦镜头曝光值 | | 0 | -| »zoom_focus_mode | 变焦镜头对焦模式 | enum_int | {"0":"MF","1":"AFS","2":"AFC"} | | | 0 | -| »zoom_focus_value | 变焦镜头对焦值 | int | | | | 0 | -| »zoom_max_focus_value | 变焦镜头最大对焦值 | int | | | | 0 | -| »zoom_min_focus_value | 变焦镜头最小对焦值 | int | | | | 0 | -| »zoom_calibrate_farthest_focus_value | 变焦镜头标定的最远对焦值 | int | | 最清晰的最远位置对焦值 | | 0 | -| »zoom_calibrate_nearest_focus_value | 变焦镜头标定的最近对焦值 | int | | 最清晰的最近位置对焦值 | | 0 | -| »zoom_focus_state | 变焦镜头对焦状态 | enum_int | {"0":"空闲","1":"对焦中","2":"对焦成功","3":"对焦失败"} | | | 0 | -| »ir_metering_mode | 红外测温模式 | enum_int | {"0":"关闭测温","1":"点测温","2":"区域测温"} | | | 0 | -| »ir_metering_point | 红外测温点 | struct | | 红外测温点相关信息 | | 0 | -| »»x | 测温点坐标 x | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,水平方向为 x | r | 0 | -| »»y | 测温点坐标 y | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,竖直方向为 y | r | 0 | -| »»temperature | 测温点的温度 | double | | | r | 0 | -| »ir_metering_area | 红外测温区域 | struct | | 红外测温区域相关信息 | | 0 | -| »»x | 测温区域左上角点坐标 x | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,水平方向为 x | r | 0 | -| »»y | 测温区域左上角点坐标 y | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,竖直方向为 y | r | 0 | -| »»width | 测温区域宽度 | double | {"max":1,"min":0} | 测温区域宽度 | r | 0 | -| »»height | 测温区域高度 | double | {"max":1,"min":0} | 测温区域高度 | r | 0 | -| »»aver_temperature | 测温区域平均温度 | double | | 测温区域平均温度 | r | 0 | -| »»min_temperature_point | 测温区域最低温度点 | struct | | 测温区域最低温度点相关信息 | r | 0 | -| »»»x | 最低温度点坐标 x | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,水平方向为 x | r | 0 | -| »»»y | 最低温度点坐标 y | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,竖直方向为 y | r | 0 | -| »»»temperature | 最低温度点的温度 | double | | 最低温度点的温度 | r | 0 | -| »»max_temperature_point | 测温区域最高温度点 | struct | | 测温区域最高温度点相关信息 | r | 0 | -| »»»x | 最高温度点坐标 x | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,水平方向为 x | r | 0 | -| »»»y | 最高温度点坐标 y | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,竖直方向为 y | r | 0 | -| »»»temperature | 最高温度点的温度 | double | | 最高温度点的温度 | r | 0 | -| flysafe_database_version | 飞行安全数据库版本 | text | {"length":"64"} | | r | 1 | -| offline_map_enable | 离线地图开关 | bool | {"0":"关闭","1":"开启"} | 当离线地图关闭后,离线地图同步不再进行自动同步 | r | 1 | -| dongle_infos | 4G Dongle信息 | array | {"size": -, "item_type": struct} | | r | 1 | -| »imei | dongle imei | text | | Dongle 的唯一识别标志 | r | 0 | -| »dongle_type | Dongle 类型 | enum_int | {"6":"旧 Dongle","10":"支持 eSIM 的新 Dongle"} | Dongle 类型 | r | 0 | -| »eid | dongle eid | text | | eSIM 的唯一识别标志,用于公众号查询套餐、购买服务 | r | 0 | -| »esim_activate_state | eSIM 激活状态 | enum_int | {"0":"未激活","1":"已激活"} | 需要激活才能使用 | r | 0 | -| »sim_card_state | SIM 卡状态 | enum_int | {"0":"未插入","1":"已插入"} | Dongle 中实体 SIM 卡的插入状态 | r | 0 | -| »sim_slot | SIM 卡槽使能状态 | enum_int | {"0":"未知","1":"实体 SIM 卡","2":"eSIM"} | 标识 Dongle 当前正在使用的 SIM 卡槽 | r | 0 | -| »esim_infos | eSIM 信息 | array | {"size": -, "item_type": struct} | | r | 0 | -| »»telecom_operator | 支持的运营商 | enum_int | {"0":"未知","1":"移动","2":"联通","3":"电信"} | eSIM 支持的运营商 | r | 0 | -| »»enabled | eSIM 使能状态 | bool | {"false":"未使用","true":"使用中"} | 同时刻只能有一个 eSIM 是使能的 | r | 0 | -| »»iccid | sim iccid | text | | SIM 卡的唯一识别标志,可以用于实体 SIM 卡的套餐购买 | r | 0 | -| »sim_info | SIM 卡信息 | struct | | 可插入 Dongle 的实体 SIM 卡信息 | r | 0 | -| »»telecom_operator | 支持的运营商 | enum_int | {"0":"未知","1":"移动","2":"联通","3":"电信"} | SIM 卡支持的运营商 | r | 0 | -| »»sim_type | SIM 卡类型 | enum_int | {"0":"未知","1":"其他普通 SIM 卡","2":"三网卡"} | 实体 SIM 卡的类型 | r | 0 | -| »»iccid | sim iccid | text | | SIM 卡的唯一识别标志,可以用于实体 SIM 卡的套餐购买 | r | 0 | -| current_rth_mode | 返航高度模式当前值 | enum_int | {"0":"智能高度","1":"设定高度"} | 大疆机场当前实际使用的返航高度模式 | r | 1 | -| rth_mode | 返航高度模式设置值 | enum_int | {"0":"智能高度","1":"设定高度"} | 智能返航模式下,飞行器将自动规划最佳返航高度。大疆机场当前不支持设置返航高度模式,只能选择'设定高度'模式。当环境,光线不满足视觉系统要求时(譬如傍晚阳光直射、夜间弱光无光),飞行器将使用您设定的返航高度进行直线返航 | r | 1 | -| obstacle_avoidance | 飞行器避障状态 | struct | | | rw | 0 | -| »horizon | 水平避障状态 | enum_int | {"0":"关闭","1":"开启"} | | | 0 | -| »upside | 上视避障状态 | enum_int | {"0":"关闭","1":"开启"} | | | 0 | -| »downside | 下视避障状态 | enum_int | {"0":"关闭","1":"开启"} | | | 0 | -| is_near_area_limit | 是否接近限飞区 | enum_int | {"0":"未达到限飞区","1":"接近限飞区"} | | r | 0 | -| is_near_height_limit | 是否接近设定的限制高度 | enum_int | {"0":"未达到设定的限制高度","1":"接近设定的限制高度"} | | r | 0 | -| height_limit | 飞行器限高 | int | {"max":"1500","min":"20","step":"1","unit_name":"米 / m"} | | rw | 0 | -| night_lights_state | 飞行器夜航灯状态 | enum_int | {"0":"关闭","1":"打开"} | | rw | 0 | -| activation_time | 飞行器激活时间(unix 时间戳) | int | {"unit_name":"秒 / s"} | | r | 0 | -| maintain_status | 保养信息 | struct | | | r | 0 | -| »maintain_status_array | 保养信息数组 | array | {"size": -, "item_type": struct} | | | 0 | -| »»state | 保养状态 | enum_int | {"0":"无保养","1":"有保养"} | | | 0 | -| »»last_maintain_type | 上一次保养类型 | enum_int | {"1":"飞行器基础保养","2":"飞行器常规保养","3":"飞行器深度保养"} | | | 0 | -| »»last_maintain_time | 上一次保养时间 | date | {"unit_name":"秒 / s"} | | | 0 | -| »»last_maintain_flight_time | 上一次保养时飞行航时 | int | {"unit_name":"小时 / h"} | | | 0 | -| »»last_maintain_flight_sorties | 上一次保养时飞行架次 | int | {"max":"2147483647","min":"0","step":"1"} | | | 0 | -| total_flight_sorties | 飞行器累计飞行总架次 | int | {"max":"2147483647","min":"0","step":"1"} | | r | 0 | -| type_subtype_gimbalindex | 负载编号 | struct | | 与字段 payload_index 保持一致 | r | 0 | -| »gimbal_pitch | 云台俯仰轴角度 | double | {"max":"180","min":"-180","step":0.1,"unit_name":"度 / °"} | | | 0 | -| »gimbal_roll | 云台横滚轴角度 | double | {"max":"180","min":"-180","step":0.1,"unit_name":"度 / °"} | | | 0 | -| »gimbal_yaw | 云台偏航轴角度 | double | {"max":"180","min":"-180","step":0.1,"unit_name":"度 / °"} | | | 0 | -| »payload_index | 负载索引,格式为 *{type-subtype-gimbalindex}* | text | | | | 0 | -| »zoom_factor | 变焦倍数 | double | | | | 0 | -| track_id | 航迹 ID | text | {"length":"64"} | | r | 0 | -| position_state | 搜星状态 | struct | | | r | 0 | -| »is_fixed | 是否收敛 | enum_int | {"0":"未开始","1":"收敛中","2":"收敛成功","3":"收敛失败"} | | | 0 | -| »quality | 搜星档位 | enum_int | {"1":"1档","2":"2档","3":"3档","4":"4档","5":"5档","10":"RTK fixed"} | | | 0 | -| »gps_number | GPS 搜星数量 | int | | | | 0 | -| »rtk_number | RTK 搜星数量 | int | | | | 0 | -| storage | 存储容量 | struct | | kb | r | 0 | -| »total | 总容量 | int | {"unit_name":"千字节 / KB"} | | | 0 | -| »used | 已使用容量 | int | {"unit_name":"千字节 / KB"} | | | 0 | -| battery | 飞行器电池信息 | struct | | | r | 0 | -| »capacity_percent | 电池的总剩余电量 | int | {"max":100,"min":0} | | | 0 | -| »remain_flight_time | 剩余飞行时间 | int | {"unit_name":"秒 / s"} | | | 0 | -| »return_home_power | 返航所需电量百分比 | int | {"max":100,"min":0} | | | 0 | -| »landing_power | 强制降落电量百分比 | int | {"max":100,"min":0} | | | 0 | -| »batteries | 电池详细信息 | array | {"size": -, "item_type": struct} | | | 0 | -| »»capacity_percent | 电池剩余电量 | int | {"max":100,"min":0} | | | 0 | -| »»index | 电池序号 | int | {"min":"0"} | | | 0 | -| »»sn | 电池序列号(SN) | text | | | | 0 | -| »»type | 电池类型 | enum_int | {} | | | 0 | -| »»sub_type | 电池子类型 | enum_int | {} | | | 0 | -| »»firmware_version | 固件版本 | text | | | | 0 | -| »»loop_times | 电池循环次数 | int | | | | 0 | -| »»voltage | 电压 | int | {"unit_name":"毫伏 / mV"} | | | 0 | -| »»temperature | 温度 | float | {"unit_name":"摄氏度 / °C"} | 保留小数点后一位 | | 0 | -| »»high_voltage_storage_days | 高电压存储天数 | int | {"unit_name":"日 / day"} | | | 0 | -| total_flight_distance | 飞行器累计飞行总里程 | float | {"unit_name":"米 / m"} | | r | 0 | -| total_flight_time | 飞行器累计飞行航时 | int | {"unit_name":"秒 / s"} | | r | 0 | -| serious_low_battery_warning_threshold | 严重低电量告警 | int | | 用户设置的电池严重低电量告警百分比 | r | 1 | -| low_battery_warning_threshold | 低电量告警 | int | | 用户设置的电池低电量告警百分比 | r | 1 | -| control_source | 当前控制源 | text | | 可以为设备,也可以为某个浏览器。设备使用 A/B 表示 A 控,B 控,浏览器以自生成的 uuid 作为标识符 | r | 1 | -| wind_direction | 当前风向 | enum_int | {"1":"正北","2":"东北","3":"东","4":"东南","5":"南","6":"西南","7":"西","8":"西北"} | | r | 0 | -| wind_speed | 风速 | float | | 风速估计,该风速是通过飞行器姿态推测出的,有一定的误差,仅供参考,不能作为气象数据使用 | r | 0 | -| home_distance | 距离 Home 点的距离 | float | | | r | 0 | -| home_latitude | Home 点纬度 | float | | | r | 1 | -| home_longitude | Home 点经度 | float | | | r | 1 | -| attitude_head | 偏航轴角度 | int | | 偏航轴角度与真北角(经线)的角度,0到6点钟方向为正值,6到12点钟方向为负值 | r | 0 | -| attitude_roll | 横滚轴角度 | float | | | r | 0 | -| attitude_pitch | 俯仰轴角度 | float | | | r | 0 | -| elevation | 相对起飞点高度 | float | | | r | 0 | -| height | 绝对高度 | float | | 相对地球椭球面高度, 计算:相对起飞点的高度 + 起飞点的椭球高 | r | 0 | -| latitude | 当前位置纬度 | float | {"max":"3.4028235E38","min":"-1.4E-45","step":"0.1"} | | r | 0 | -| longitude | 当前位置经度 | float | {"max":"3.4028235E38","min":"-1.4E-45","step":"0.1"} | | r | 0 | -| vertical_speed | 垂直速度 | float | {"unit_name":"米每秒 / m/s"} | | r | 0 | -| horizontal_speed | 水平速度 | float | | | r | 0 | -| firmware_upgrade_status | 固件升级状态 | enum_int | {"0":"未升级","1":"升级中"} | | r | 1 | -| compatible_status | 固件一致性 | enum_int | {"0":"不需要一致性升级","1":"需要一致性升级"} | 一致性升级:指飞行器某些模块的固件版本与系统匹配版本不一致,需要进行升级。常见的情况例如:飞行器与遥控器已经升级至最新版本,但替换电池时发现电池未升级,此时一致性升级将被提示。普通升级:开发者将飞行器所有模块升级至指定固件版本。 | r | 1 | -| firmware_version | 固件版本 | text | {"length":"64"} | | r | 1 | -| gear | 档位 | enum_int | {"0":"A","1":"P","2":"NAV","3":"FPV","4":"FARM","5":"S","6":"F","7":"M","8":"G","9":"T"} | | r | 0 | -| mode_code_reason | 飞行器进入当前状态的原因 | enum_int | {"0":"无意义","1":"电池电量不足(返航、降落)","2":"电池电压不足(返航、降落)","3":"电压严重过低(返航、降落)","4":"遥控器按键请求(起飞、返航、降落)","5":"App 请求(起飞、返航、降落)","6":"遥控信号丢失(返航、降落、悬停)","7":"导航、SDK 等外部设备触发(起飞、返航、降落)","8":"进入机场限飞区(降落)","9":"虽然触发了返航但是因为距离 Home 点距离太近(降落)","10":"虽然触发了返航但是因为距离 Home 点距离太远(降落)","11":"执行航点任务时请求(起飞)","12":"返航阶段到达 Home 点上方后请求(降落)","13":"飞行器高度下降,距地面 0.7m(二段降落限低)时,继续下降导致(降落)","14":"App、SDK 等设备强制突破限低保护进行(降落)","15":"因为周围有航班经过而请求(返航、降落)","16":"因为高度控制失败请求(返航、降落)","17":"智能低电量返航后进入(降落)","18":"AP控制飞行模式(手动飞行)","19":"硬件异常(返航、降落)","20":"防触地保护结束(降落)","21":"返航取消 (悬停)","22":"返航时遇到障碍物(降落)","23":"机场场景下大风触发(返航)"} | | r | 1 | -| commander_flight_height | 指点飞行高度 | float | {"max":3000,"min":2,"step":0.1,"unit_name":"米 / m"} | 相对(机场)起飞点的高度,相对高 ALT | rw | 1 | -| commander_flight_mode | 指点飞行模式设置值 | enum_int | {"0":"智能高度飞行","1":"设定高度飞行"} | 指点飞行模式设置值 | rw | 1 | -| commander_mode_lost_action | 指点飞行失控动作 | enum_int | {"0":"继续执行指点飞行任务","1":"退出指点飞行任务,执行普通失控行为"} | 执行指点飞行时失控了,选择继续执行完,还是执行普通失控行为 | rw | 1 | -| camera_watermark_settings | 相机水印设置 | struct | | 用户对相机拍摄的照片和录像文件进行水印配置, 目前暂不支持直播画面水印 | rw | 1 | -| »global_enable | 水印显示全局开关 | enum_int | {"0":"关闭","1":"开启"} | 需要开启全局开关才能显示水印 | rw | 1 | -| »drone_type_enable | 机型显示开关 | enum_int | {"0":"关闭","1":"开启"} | | rw | 1 | -| »drone_sn_enable | 飞行器序列号显示开关 | enum_int | {"0":"关闭","1":"开启"} | | rw | 1 | -| »datetime_enable | 日期时间显示开关 | enum_int | {"0":"关闭","1":"开启"} | 时区默认为当地时区 | rw | 1 | -| »gps_enable | 经纬度&海拔高显示开关 | enum_int | {"0":"关闭","1":"开启"} | | rw | 1 | -| »user_custom_string_enable | 自定义文案显示开关 | enum_int | {"0":"关闭","1":"开启"} | | rw | 1 | -| »user_custom_string | 自定义文案内容 | text | | 最多可显示 250 字节 | rw | 1 | -| »layout | 水印在画面中位置 | enum_int | {"0":"左上","1":"左下","2":"右上","3":"右下"} | | rw | 1 | -| mode_code | 飞行器状态 | enum_int | {"0":"待机","1":"起飞准备","2":"起飞准备完毕","3":"手动飞行","4":"自动起飞","5":"航线飞行","6":"全景拍照","7":"智能跟随","8":"ADS-B 躲避","9":"自动返航","10":"自动降落","11":"强制降落","12":"三桨叶降落","13":"升级中","14":"未连接","15":"APAS","16":"虚拟摇杆状态","17":"指令飞行","18":"空中 RTK 收敛模式","19":"机场选址中"} | 机场选址指飞行器在空中悬停,为机场选址以及检查 RTK 信号质量 | r | 0 | - -```json -{ - "bid": "f7f2dd20-a08a-4865-9211-f0ced31a798c", - "data": { - "80-0-0": { - "gimbal_pitch": 0, - "gimbal_roll": 0, - "gimbal_yaw": -72.9804724552571, - "payload_index": "80-0-0", - "zoom_factor": 0.56782334384858046 - }, - "activation_time": 1734637617, - "attitude_head": -72.9, - "attitude_pitch": -0.4, - "attitude_roll": -3, - "battery": { - "batteries": [ - { - "capacity_percent": 78, - "firmware_version": "26.03.00.48", - "high_voltage_storage_days": 8, - "index": 0, - "loop_times": 6, - "sn": "6Q7PM4ADA100QQ", - "sub_type": 0, - "temperature": 23.9, - "type": 0, - "voltage": 15544 - } - ], - "capacity_percent": 78, - "landing_power": 8, - "remain_flight_time": 1553, - "return_home_power": 26 - }, - "best_link_gateway": "7CTDM6F00B744S", - "cameras": [ - { - "camera_mode": 1, - "liveview_world_region": { - "bottom": 1, - "left": 1, - "right": 1, - "top": 1 - }, - "payload_index": "80-0-0", - "photo_state": 0, - "record_time": 0, - "recording_state": 0, - "remain_photo_num": 0, - "remain_record_duration": 29207, - "wide_calibrate_farthest_focus_value": 35, - "wide_calibrate_nearest_focus_value": 84, - "wide_exposure_mode": 1, - "wide_exposure_value": 16, - "wide_focus_mode": 2, - "wide_focus_state": 1, - "wide_focus_value": 26, - "wide_iso": 9, - "wide_max_focus_value": 84, - "wide_min_focus_value": 35, - "wide_shutter_speed": 33, - "zoom_calibrate_farthest_focus_value": 35, - "zoom_calibrate_nearest_focus_value": 84, - "zoom_exposure_mode": 1, - "zoom_exposure_value": 16, - "zoom_factor": 1, - "zoom_focus_mode": 2, - "zoom_focus_state": 1, - "zoom_focus_value": 26, - "zoom_iso": 9, - "zoom_max_focus_value": 84, - "zoom_min_focus_value": 35, - "zoom_shutter_speed": 33 - } - ], - "country": "CN", - "distance_limit_status": { - "distance_limit": 5000, - "is_near_distance_limit": 0, - "state": 0 - }, - "elevation": 64, - "gear": 1, - "height": 69.8617935180664, - "height_limit": 220, - "home_distance": 0.11966302990913391, - "horizontal_speed": 0, - "is_near_area_limit": 1, - "is_near_height_limit": 0, - "latitude": 39.102602928799222, - "longitude": 117.71197176283638, - "maintain_status": { - "maintain_status_array": [ - { - "last_maintain_flight_sorties": 0, - "last_maintain_flight_time": 0, - "last_maintain_time": 0, - "last_maintain_type": 1, - "state": 0 - }, - { - "last_maintain_flight_sorties": 0, - "last_maintain_flight_time": 0, - "last_maintain_time": 0, - "last_maintain_type": 2, - "state": 0 - }, - { - "last_maintain_flight_sorties": 0, - "last_maintain_flight_time": 0, - "last_maintain_time": 0, - "last_maintain_type": 3, - "state": 0 - } - ] - }, - "mode_code": 9, - "night_lights_state": 0, - "obstacle_avoidance": { "downside": 0, "horizon": 0, "upside": 0 }, - "position_state": { - "gps_number": 32, - "is_fixed": 2, - "quality": 5, - "rtk_number": 33 - }, - "rc_lost_action": 2, - "rid_state": true, - "rth_altitude": 60, - "storage": { "total": 243702000, "used": 4000 }, - "total_flight_distance": 174010.89760393579, - "total_flight_sorties": 57, - "total_flight_time": 28866.739354778081, - "track_id": "586f7b33-4727-4026-a203-cf35a68626e5", - "vertical_speed": 0, - "wind_direction": 6, - "wind_speed": 35 - }, - "tid": "795fbf18-8bc1-43f7-bd10-895973319cb5", - "timestamp": 1735473362062, - "gateway": "7CTDM6F00B744S" -} -``` - -```json -{ - "bid": "78f3725d-34c3-4498-b0d5-98d50dc0310d", - "data": { "mode_code_reason": 12 }, - "need_reply": 1, - "tid": "88933f47-e55e-4e9e-a100-7a073cc09086", - "timestamp": 1735473362258, - "gateway": "7CTDM6F00B744S" -} -``` - -## 指令 - -### 起飞指令: - -| target_latitude | 目标点纬度 | double | {"max":90,"min":-90} | 目标点纬度,角度值,南纬是负,北纬是正,精度到小数点后6位 | -| --- | --- | --- | --- | --- | -| target_longitude | 目标点经度 | double | {"max":180,"min":-180} | 目标点经度,角度值,东经是正,西经是负,精度到小数点后6位 | -| target_height | 目标点高度 | float | {"max":1500,"min":2,"step":0.1,"unit_name":"米 / m"} | 目标点高度(椭球高),使用 WGS84 模型,飞行器到点后默认行为:悬停 | -| security_takeoff_height | 安全起飞高度 | float | {"max":1500,"min":20,"step":0.1,"unit_name":"米 / m"} | 相对(机场)起飞点的高度(ALT),飞行器先升到特定的高度,然后再飞向目标点。 | -| rth_mode | 【必填】返航模式设置值 | enum_int | {"0":"智能高度","1":"设定高度"} | 智能返航模式下,飞行器将自动规划最佳返航高度。大疆机场当前不支持设置返航高度模式,只能选择'设定高度'模式。当环境,光线不满足视觉系统要求时(譬如傍晚阳光直射、夜间弱光无光),飞行器将使用您设定的返航高度进行直线返航 | -| rth_altitude | 返航高度 | int | {"max":1500,"min":2,"step":1,"unit_name":"米 / m"} | 相对(机场)起飞点的高度,相对高 ALT | -| rc_lost_action | 遥控器失控动作 | enum_int | {"0":"悬停","1":"着陆(降落)","2":"返航"} | 遥控器失控动作 | -| commander_mode_lost_action | 【必填】指点飞行失控动作 | enum_int | {"0":"继续执行指点飞行任务","1":"退出指点飞行任务,执行普通失控行为"} | | -| commander_flight_mode | 【必填】指点飞行模式设置值 | enum_int | {"0":"智能高度飞行","1":"设定高度飞行"} | | -| commander_flight_height | 【必填】指点飞行高度 | float | {"max":3000,"min":2,"step":0.1,"unit_name":"米 / m"} | 相对(机场)起飞点的高度,相对高 ALT | -| flight_id | 一键起飞任务 UUID | text | | 任务 UUID,全局唯一,用于染色,云端区分该值是普通计划任务还是一键起飞任务 | -| max_speed | 一键起飞的飞行过程中能达到的最大速度 | int | {"max":15,"min":1,"unit_name":"米每秒 / m/s"} | | -| simulate_mission | 是否在模拟器中执行任务 | struct | | 可选字段,用于在室内进行模拟任务调试。 | -| »is_enable | 是否开启模拟器任务 | enum_int | {"0":"不开启","1":"开启"} | 当次任务打开或关闭模拟器 | -| »latitude | 纬度 | double | {"max":"90.0","min":"-90.0"} | | -| »longitude | 经度 | double | {"max":"180.0","min":"-180.0"} | | -| flight_safety_advance_check | 飞行安全预检查 | bool | {"0":"关闭","1":"开启"} | 设置一键起飞和航线任务中的飞行安全是否预先检查。此字段为可选,默认为0,值为0表示关闭,1表示开启。飞行安全预先检查表示: 飞行器执行任务前,检查自身作业区文件是否与云端一致,如果不一致则拉取文件更新,如果一致则不处理 | - -```json -{ - "data": { - "flight_id": flight_id, - "max_speed": 5, - "rc_lost_action": 2, - "rth_altitude": 60.0, - "rth_mode": 1, - "security_takeoff_height": 60.0, - "target_height": 70.0, - "target_latitude": 39.102603, - "target_longitude": 117.711972, - "commander_mode_lost_action": 0, - "commander_flight_mode": 1, - "commander_flight_height": 70.0, - "simulate_mission": { - }, - "flight_safety_advance_check": 0 - }, - "method": "takeoff_to_point" -} -``` - -### 飞向目标点: - -| fly_to_id | 飞向目标点 ID | text | | | -| --- | --- | --- | --- | --- | -| max_speed | flyto 的飞行过程中能达到的最大速度 | int | {"max":15,"min":0,"unit_name":"米每秒 / m/s"} | | -| points | flyto 目标点列表 | array | {"size": -, "item_type": struct} | 仅支持 1 个目标点 | -| »latitude | 目标点纬度 | double | {"max":90,"min":-90} | 目标点纬度,角度值,南纬是负,北纬是正,精度到小数点后6位 | -| »longitude | 目标点经度 | double | {"max":180,"min":-180} | 目标点经度,角度值,东经是正,西经是负,精度到小数点后6位 | -| »height | 目标点高度 | float | {"max":10000,"min":2,"step":0.1,"unit_name":"米 / m"} | 目标点高度(椭球高),使用 WGS84 模型 | - -```json -{ - "data": { - "fly_to_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx", - "max_speed": 12, - "points": [ - { - "height": 100, - "latitude": 12.23, - "longitude": 12.23 - } - ] - }, - "method": "fly_to_point" -} -``` - -### 结束飞向目标点: - -```json -{ - "data": {}, - "method": "fly_to_point_stop" -} -``` - -### 更新飞向目标点: - -| max_speed | 指令飞行过程中能达到的最大速度 | int | {"max":15,"min":1,"unit_name":"米每秒 / m/s"} | | -| --- | --- | --- | --- | --- | -| points | 更新的目标点列表 | array | {"size": -, "item_type": struct} | 仅支持 1 个目标点 | -| »latitude | 目标点纬度 | double | {"max":90,"min":-90} | 目标点纬度,角度值,南纬是负,北纬是正,精度到小数点后6位 | -| »longitude | 目标点经度 | double | {"max":180,"min":-180} | 目标点经度,角度值,东经是正,西经是负,精度到小数点后6位 | -| »height | 目标点高度 | float | {"max":10000,"min":2,"step":0.1,"unit_name":"米 / m"} | 目标点高度(椭球高),使用 WGS84 模型 | - -```json -{ - "data": { - "max_speed": 12, - "points": [ - { - "height": 100, - "latitude": 12.23, - "longitude": 12.23 - } - ] - }, - "method": "fly_to_point_update" -} -``` - -### 返航: - -```json -{ - "data": {}, - "method": "return_home" -} -``` diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDevice.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDevice.java deleted file mode 100644 index 0611d524..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDevice.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.central.device.model; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import com.central.common.model.SuperEntity; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; - -import java.util.Date; - -/** - * Device information - * - * @author lsl - * @date 2024-12-19 17:51:47 - */ -@Getter -@Setter -@EqualsAndHashCode(callSuper = false) -@TableName("manage_device") -public class AgeDevice extends SuperEntity { - - private String deviceSn; - private String deviceName; - private String userId; - private String nickname; - private String workspaceId; - private Integer deviceType; - private Integer subType; - private Integer domain; - private String firmwareVersion; - private Integer compatibleStatus; - private String version; - private String deviceIndex; - private String childSn; - @TableField(fill = FieldFill.INSERT) - private Date createTime; - @TableField(fill = FieldFill.INSERT_UPDATE) - private Date updateTime; - private Long boundTime; - private Integer boundStatus; - private Long loginTime; - private String deviceDesc; - private String urlNormal; - private String urlSelect; - private String tenantId; -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceFirmware.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceFirmware.java deleted file mode 100644 index 1f9e6ada..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceFirmware.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.central.device.model; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.TableField; -import com.central.common.model.SuperEntity; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; -import lombok.EqualsAndHashCode; -import java.util.Date; - -/** - * Firmware file information - * - * @author lsl - * @date 2024-12-19 17:52:54 - */ -@Getter -@Setter -@EqualsAndHashCode(callSuper = false) -@TableName("manage_device_firmware") -public class AgeDeviceFirmware extends SuperEntity { - private static final long serialVersionUID=1L; - - private String firmwareId; - private String fileName; - private String firmwareVersion; - private String objectKey; - private Long fileSize; - private String fileMd5; - private String workspaceId; - private String releaseNote; - private Long releaseDate; - private String userName; - private Integer status; - - @TableField(fill = FieldFill.INSERT) - private Date createTime; - @TableField(fill = FieldFill.INSERT_UPDATE) - private Date updateTime; -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceHms.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceHms.java deleted file mode 100644 index 4137d1e2..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceHms.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.central.device.model; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.TableField; -import com.central.common.model.SuperEntity; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; -import lombok.EqualsAndHashCode; -import java.util.Date; - -/** - * Device's hms information - * - * @author lsl - * @date 2024-12-19 17:53:01 - */ -@Getter -@Setter -@EqualsAndHashCode(callSuper = false) -@TableName("manage_device_hms") -public class AgeDeviceHms extends SuperEntity { - private static final long serialVersionUID=1L; - - private String hmsId; - private String tid; - private String bid; - private String sn; - private Integer level; - private Integer module; - private String hmsKey; - private String messageZh; - private String messageEn; - @TableField(fill = FieldFill.INSERT) - private Date createTime; - @TableField(fill = FieldFill.INSERT_UPDATE) - private Date updateTime; -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceLogs.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceLogs.java deleted file mode 100644 index 89a3e500..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDeviceLogs.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.central.device.model; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.TableField; -import com.central.common.model.SuperEntity; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; -import lombok.EqualsAndHashCode; -import java.util.Date; - -/** - * Log for uploading logs - * - * @author lsl - * @date 2024-12-19 17:53:03 - */ -@Getter -@Setter -@EqualsAndHashCode(callSuper = false) -@TableName("manage_device_logs") -public class AgeDeviceLogs extends SuperEntity { - private static final long serialVersionUID=1L; - - private String logsId; - private String username; - private String deviceSn; - private String logsInfo; - private Long happenTime; - private Integer status; - @TableField(fill = FieldFill.INSERT) - private Date createTime; - @TableField(fill = FieldFill.INSERT_UPDATE) - private Date updateTime; -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDevicePayload.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDevicePayload.java deleted file mode 100644 index ffbdf5eb..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeDevicePayload.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.central.device.model; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.TableField; -import com.central.common.model.SuperEntity; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; -import lombok.EqualsAndHashCode; -import java.util.Date; - -/** - * The payload information of the device. - * - * @author lsl - * @date 2024-12-19 17:53:19 - */ -@Getter -@Setter -@EqualsAndHashCode(callSuper = false) -@TableName("manage_device_payload") -public class AgeDevicePayload extends SuperEntity { - private static final long serialVersionUID=1L; - - private String payloadSn; - private String payloadName; - private Integer payloadType; - private Integer subType; - private String firmwareVersion; - private Integer payloadIndex; - private String deviceSn; - private String payloadDesc; - private String controlSource; - @TableField(fill = FieldFill.INSERT) - private Date createTime; - @TableField(fill = FieldFill.INSERT_UPDATE) - private Date updateTime; -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeFirmwareModel.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeFirmwareModel.java deleted file mode 100644 index ea19462f..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeFirmwareModel.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.central.device.model; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.TableField; -import com.central.common.model.SuperEntity; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; -import lombok.EqualsAndHashCode; -import java.util.Date; - -/** - * - * - * @author lsl - * @date 2024-12-19 17:53:20 - */ -@Getter -@Setter -@EqualsAndHashCode(callSuper = false) -@TableName("manage_firmware_model") -public class AgeFirmwareModel extends SuperEntity { - private static final long serialVersionUID=1L; - - private String firmwareId; - private String deviceName; - @TableField(fill = FieldFill.INSERT) - private Date createTime; - @TableField(fill = FieldFill.INSERT_UPDATE) - private Date updateTime; -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeWorkspace.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeWorkspace.java deleted file mode 100644 index ce85a7cd..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/model/AgeWorkspace.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.central.device.model; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.TableField; -import com.central.common.model.SuperEntity; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; -import lombok.EqualsAndHashCode; -import java.util.Date; - -/** - * - * - * @author lsl - * @date 2024-12-19 17:52:26 - */ -@Getter -@Setter -@EqualsAndHashCode(callSuper = false) -@TableName("manage_workspace") -public class AgeWorkspace extends SuperEntity { - private static final long serialVersionUID=1L; - - private String workspaceId; - private String workspaceName; - private String workspaceDesc; - private String platformName; - @TableField(fill = FieldFill.INSERT) - private Date createTime; - @TableField(fill = FieldFill.INSERT_UPDATE) - private Date updateTime; - private String bindCode; -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/IaFile.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/IaFile.java deleted file mode 100644 index f10e5d7d..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/model/IaFile.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.central.device.model; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.TableField; -import com.central.common.model.SuperEntity; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; -import lombok.EqualsAndHashCode; -import java.util.Date; - -/** - * Media file information - * - * @author lsl - * @date 2024-12-19 17:52:18 - */ -@Getter -@Setter -@EqualsAndHashCode(callSuper = false) -@TableName("media_file") -public class IaFile extends SuperEntity { - private static final long serialVersionUID=1L; - - private String fileId; - private String fileName; - private String filePath; - private String workspaceId; - private String fingerprint; - private String tinnyFingerprint; - private String objectKey; - private Integer subFileType; - private Integer isOriginal; - private String drone; - private String payload; - private String jobId; - @TableField(fill = FieldFill.INSERT) - private Date createTime; - @TableField(fill = FieldFill.INSERT_UPDATE) - private Date updateTime; -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/LineFile.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/LineFile.java deleted file mode 100644 index 29240efa..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/model/LineFile.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.central.device.model; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import com.central.common.model.SuperEntity; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; - -import java.util.Date; - -/** - * Wayline file information - * - * @author lsl - * @date 2024-12-19 17:51:52 - */ -@Getter -@Setter -@EqualsAndHashCode(callSuper = false) -@TableName("wayline_file") -public class LineFile extends SuperEntity { - private static final long serialVersionUID=1L; - - private String name; - private String waylineId; - private String droneModelKey; - private String payloadModelKeys; - private String workspaceId; - private String sign; - private Integer favorited; - private String templateTypes; - private String objectKey; - private String userName; - @TableField(fill = FieldFill.INSERT) - private Date createTime; - @TableField(fill = FieldFill.INSERT_UPDATE) - private Date updateTime; - private String tenantId; -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/LineJob.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/LineJob.java deleted file mode 100644 index 2ce273d0..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/model/LineJob.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.central.device.model; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.TableField; -import com.central.common.model.SuperEntity; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; -import lombok.EqualsAndHashCode; -import java.util.Date; - -/** - * Wayline mission information of the dock. - * - * @author lsl - * @date 2024-12-19 17:51:53 - */ -@Getter -@Setter -@EqualsAndHashCode(callSuper = false) -@TableName("wayline_job") -public class LineJob extends SuperEntity { - private static final long serialVersionUID=1L; - - private String jobId; - private String name; - private String fileId; - private String dockSn; - private String workspaceId; - private Integer taskType; - private Integer waylineType; - private Long executeTime; - private Long completedTime; - private String username; - private Long beginTime; - private Long endTime; - private Integer errorCode; - private Integer status; - private Integer rthAltitude; - private Integer outOfControl; - private Integer mediaCount; - @TableField(fill = FieldFill.INSERT) - private Date createTime; - @TableField(fill = FieldFill.INSERT_UPDATE) - private Date updateTime; - private String parentId; -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/SFile.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/SFile.java deleted file mode 100644 index 2006dc7b..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/model/SFile.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.central.device.model; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.TableField; -import com.central.common.model.SuperEntity; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; -import lombok.EqualsAndHashCode; -import java.util.Date; - -/** - * Logs file information - * - * @author lsl - * @date 2024-12-19 17:53:36 - */ -@Getter -@Setter -@EqualsAndHashCode(callSuper = false) -@TableName("logs_file") -public class SFile extends SuperEntity { - private static final long serialVersionUID=1L; - - private String fileId; - private String name; - private Long size; - private String logsId; - private String deviceSn; - private String fingerprint; - private String objectKey; - private Integer status; - @TableField(fill = FieldFill.INSERT) - private Date createTime; - @TableField(fill = FieldFill.INSERT_UPDATE) - private Date updateTime; -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/SFileIndex.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/SFileIndex.java deleted file mode 100644 index 1aed54a5..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/model/SFileIndex.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.central.device.model; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.TableField; -import com.central.common.model.SuperEntity; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; -import lombok.EqualsAndHashCode; -import java.util.Date; - -/** - * The boot index table corresponding to the logs file. - * - * @author lsl - * @date 2024-12-19 17:53:23 - */ -@Getter -@Setter -@EqualsAndHashCode(callSuper = false) -@TableName("logs_file_index") -public class SFileIndex extends SuperEntity { - private static final long serialVersionUID=1L; - - private Integer bootIndex; - private String fileId; - private Long startTime; - private Long endTime; - private Long size; - private String deviceSn; - private Integer domain; - @TableField(fill = FieldFill.INSERT) - private Date createTime; - @TableField(fill = FieldFill.INSERT_UPDATE) - private Date updateTime; -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/excel/AgeDeviceExcel.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/excel/AgeDeviceExcel.java deleted file mode 100644 index 2aed8665..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/model/excel/AgeDeviceExcel.java +++ /dev/null @@ -1,174 +0,0 @@ -package com.central.device.model.excel; - -import com.alibaba.excel.annotation.ExcelIgnore; -import com.alibaba.excel.annotation.ExcelProperty; -import com.alibaba.excel.annotation.write.style.ColumnWidth; -import com.central.device.model.AgeDevice; -import com.fasterxml.jackson.annotation.JsonFormat; -import jakarta.validation.constraints.NotBlank; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.util.Date; - -/** - * 设备信息Excel导入导出实体 - * - * @author lsl - * @date 2024-12-19 - */ -@Data -@EqualsAndHashCode(callSuper = false) -public class AgeDeviceExcel { - - @ExcelProperty(value = "设备序列号", index = 0) - @ColumnWidth(20) - @NotBlank(message = "设备序列号不能为空") - private String deviceSn; - - @ExcelProperty(value = "设备名称", index = 1) - @ColumnWidth(20) - @NotBlank(message = "设备名称不能为空") - private String deviceName; - - @ExcelProperty(value = "设备类型", index = 2) - @ColumnWidth(15) - private Integer deviceType; - - @ExcelProperty(value = "子类型", index = 3) - @ColumnWidth(15) - private Integer subType; - - @ExcelProperty(value = "固件版本", index = 4) - @ColumnWidth(20) - private String firmwareVersion; - - @ExcelProperty(value = "设备描述", index = 6) - @ColumnWidth(30) - private String deviceDesc; - - @ExcelProperty(value = "工作空间ID", index = 7) - @ColumnWidth(20) - private String workspaceId; - - @ExcelProperty(value = "域", index = 8) - @ColumnWidth(15) - private Integer domain; - - @ExcelProperty(value = "兼容状态", index = 9) - @ColumnWidth(15) - private Integer compatibleStatus; - - @ExcelProperty(value = "版本", index = 10) - @ColumnWidth(15) - private String version; - - @ExcelProperty(value = "设备索引", index = 11) - @ColumnWidth(20) - private String deviceIndex; - - @ExcelProperty(value = "子设备序列号", index = 12) - @ColumnWidth(20) - private String childSn; - - @ExcelProperty(value = "绑定状态", index = 13) - @ColumnWidth(15) - private Integer boundStatus; - - @ExcelProperty(value = "租户ID", index = 14) - @ColumnWidth(20) - private String tenantId; - - // 以下字段在Excel中不显示,但在实体转换时需要 - @ExcelIgnore - private String userId; - - @ExcelIgnore - private String nickname; - - @ExcelIgnore - private Long boundTime; - - @ExcelIgnore - private Long loginTime; - - @ExcelIgnore - private String urlNormal; - - @ExcelIgnore - private String urlSelect; - - @ExcelProperty(value = "创建时间", index = 15) - @ColumnWidth(20) - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") - private Date createTime; - - @ExcelProperty(value = "更新时间", index = 16) - @ColumnWidth(20) - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") - private Date updateTime; - - /** - * 转换为设备实体 - */ - public AgeDevice toDevice() { - AgeDevice device = new AgeDevice(); - // 必填字段 - device.setDeviceSn(this.deviceSn); - device.setDeviceName(this.deviceName); - device.setDeviceType(this.deviceType); - - // 可选字段,需要判空 - device.setSubType(this.subType); - device.setFirmwareVersion(this.firmwareVersion); - device.setDeviceDesc(this.deviceDesc); - device.setWorkspaceId(this.workspaceId); - device.setDomain(this.domain); - device.setCompatibleStatus(this.compatibleStatus); - device.setVersion(this.version); - device.setDeviceIndex(this.deviceIndex); - device.setChildSn(this.childSn); - device.setBoundStatus(this.boundStatus); - device.setTenantId(this.tenantId); - - // 系统字段 - device.setCreateTime(this.createTime); - device.setUpdateTime(this.updateTime); - - return device; - } - - /** - * 从设备实体转换 - */ - public static AgeDeviceExcel fromDevice(AgeDevice device) { - if (device == null) { - return null; - } - - AgeDeviceExcel excel = new AgeDeviceExcel(); - // 必填字段 - excel.setDeviceSn(device.getDeviceSn()); - excel.setDeviceName(device.getDeviceName()); - excel.setDeviceType(device.getDeviceType()); - - // 可选字段 - excel.setSubType(device.getSubType()); - excel.setFirmwareVersion(device.getFirmwareVersion()); - excel.setDeviceDesc(device.getDeviceDesc()); - excel.setWorkspaceId(device.getWorkspaceId()); - excel.setDomain(device.getDomain()); - excel.setCompatibleStatus(device.getCompatibleStatus()); - excel.setVersion(device.getVersion()); - excel.setDeviceIndex(device.getDeviceIndex()); - excel.setChildSn(device.getChildSn()); - excel.setBoundStatus(device.getBoundStatus()); - excel.setTenantId(device.getTenantId()); - - // 系统字段 - excel.setCreateTime(device.getCreateTime()); - excel.setUpdateTime(device.getUpdateTime()); - - return excel; - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/model/vo/DistributionDataVO.java b/zlt-business/device-ops-center/src/main/java/com/central/device/model/vo/DistributionDataVO.java deleted file mode 100644 index d02f41d8..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/model/vo/DistributionDataVO.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.central.device.model.vo; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -import java.math.BigDecimal; - -@Data -@Schema(description = "分布数据") -public class DistributionDataVO { - @Schema(description = "类型") - private String type; - - @Schema(description = "数值") - private BigDecimal value; -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceFirmwareService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceFirmwareService.java deleted file mode 100644 index 33c98966..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceFirmwareService.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.central.device.service; - -import com.central.device.model.AgeDeviceFirmware; -import com.central.common.model.PageResult; -import com.central.common.service.ISuperService; - -import java.util.Map; - -/** - * Firmware file information - * - * @author lsl - * @date 2024-12-19 17:52:54 - */ -public interface IAgeDeviceFirmwareService extends ISuperService { - /** - * 列表 - * @param params - * @return - */ - PageResult findList(Map params); -} - diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceHmsService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceHmsService.java deleted file mode 100644 index ee8f1ceb..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceHmsService.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.central.device.service; - -import com.central.device.model.AgeDeviceHms; -import com.central.common.model.PageResult; -import com.central.common.service.ISuperService; - -import java.util.Map; - -/** - * Device's hms information - * - * @author lsl - * @date 2024-12-19 17:53:01 - */ -public interface IAgeDeviceHmsService extends ISuperService { - /** - * 列表 - * @param params - * @return - */ - PageResult findList(Map params); -} - diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceLogsService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceLogsService.java deleted file mode 100644 index 3fcc6be4..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceLogsService.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.central.device.service; - -import com.central.device.model.AgeDeviceLogs; -import com.central.common.model.PageResult; -import com.central.common.service.ISuperService; - -import java.util.Map; - -/** - * Log for uploading logs - * - * @author lsl - * @date 2024-12-19 17:53:03 - */ -public interface IAgeDeviceLogsService extends ISuperService { - /** - * 列表 - * @param params - * @return - */ - PageResult findList(Map params); -} - diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDevicePayloadService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDevicePayloadService.java deleted file mode 100644 index 91f3de0d..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDevicePayloadService.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.central.device.service; - -import com.central.device.model.AgeDevicePayload; -import com.central.common.model.PageResult; -import com.central.common.service.ISuperService; - -import java.util.Map; - -/** - * The payload information of the device. - * - * @author lsl - * @date 2024-12-19 17:53:19 - */ -public interface IAgeDevicePayloadService extends ISuperService { - /** - * 列表 - * @param params - * @return - */ - PageResult findList(Map params); -} - diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceService.java deleted file mode 100644 index 4f342ab7..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeDeviceService.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.central.device.service; - -import com.central.device.model.AgeDevice; -import com.central.common.model.PageResult; -import com.central.common.service.ISuperService; - -import java.util.List; -import java.util.Map; - -/** - * Device information - * - * @author lsl - * @date 2024-12-19 17:51:47 - */ -public interface IAgeDeviceService extends ISuperService { - /** - * 列表 - * @param params - * @return - */ - PageResult findList(Map params); - - /** - * 根据参数查询设备列表 - */ - List findListByParams(Map params); - - /** - * 根据设备序列号查询设备 - */ - AgeDevice getByDeviceSn(String deviceSn); - - /** - * 检查设备序列号是否存在 - */ - boolean checkDeviceSnExists(String deviceSn); - - /** - * 批量导入设备信息 - */ - boolean importDevices(List deviceList); -} - diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeFirmwareModelService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeFirmwareModelService.java deleted file mode 100644 index c2a674eb..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeFirmwareModelService.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.central.device.service; - -import com.central.device.model.AgeFirmwareModel; -import com.central.common.model.PageResult; -import com.central.common.service.ISuperService; - -import java.util.Map; - -/** - * - * - * @author lsl - * @date 2024-12-19 17:53:20 - */ -public interface IAgeFirmwareModelService extends ISuperService { - /** - * 列表 - * @param params - * @return - */ - PageResult findList(Map params); -} - diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeWorkspaceService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeWorkspaceService.java deleted file mode 100644 index 97375734..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IAgeWorkspaceService.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.central.device.service; - -import com.central.device.model.AgeWorkspace; -import com.central.common.model.PageResult; -import com.central.common.service.ISuperService; - -import java.util.Map; - -/** - * - * - * @author lsl - * @date 2024-12-19 17:52:26 - */ -public interface IAgeWorkspaceService extends ISuperService { - /** - * 列表 - * @param params - * @return - */ - PageResult findList(Map params); -} - diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IIaFileService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/IIaFileService.java deleted file mode 100644 index 8477e62a..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/IIaFileService.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.central.device.service; - -import com.central.device.model.IaFile; -import com.central.common.model.PageResult; -import com.central.common.service.ISuperService; - -import java.util.Map; - -/** - * Media file information - * - * @author lsl - * @date 2024-12-19 17:52:18 - */ -public interface IIaFileService extends ISuperService { - /** - * 列表 - * @param params - * @return - */ - PageResult findList(Map params); -} - diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/ILineFileService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/ILineFileService.java deleted file mode 100644 index 5071320f..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/ILineFileService.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.central.device.service; - -import com.central.common.model.PageResult; -import com.central.common.service.ISuperService; -import com.central.device.model.LineFile; - -import java.util.Map; - -/** - * Wayline file information - * - * @author lsl - * @date 2024-12-19 17:51:52 - */ -public interface ILineFileService extends ISuperService { - /** - * 列表 - * @param params - * @return - */ - PageResult findList(Map params); - - LineFile findLineFileByWaylineId(String waylineId); -} - diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/ILineJobService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/ILineJobService.java deleted file mode 100644 index e7af5fc2..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/ILineJobService.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.central.device.service; - -import com.central.device.model.LineJob; -import com.central.common.model.PageResult; -import com.central.common.service.ISuperService; - -import java.util.Map; - -/** - * Wayline mission information of the dock. - * - * @author lsl - * @date 2024-12-19 17:51:53 - */ -public interface ILineJobService extends ISuperService { - /** - * 列表 - * @param params - * @return - */ - PageResult findList(Map params); -} - diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/ISFileIndexService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/ISFileIndexService.java deleted file mode 100644 index c05a71a5..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/ISFileIndexService.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.central.device.service; - -import com.central.device.model.SFileIndex; -import com.central.common.model.PageResult; -import com.central.common.service.ISuperService; - -import java.util.Map; - -/** - * The boot index table corresponding to the logs file. - * - * @author lsl - * @date 2024-12-19 17:53:23 - */ -public interface ISFileIndexService extends ISuperService { - /** - * 列表 - * @param params - * @return - */ - PageResult findList(Map params); -} - diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/ISFileService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/ISFileService.java deleted file mode 100644 index 6dc34343..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/ISFileService.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.central.device.service; - -import com.central.device.model.SFile; -import com.central.common.model.PageResult; -import com.central.common.service.ISuperService; - -import java.util.Map; - -/** - * Logs file information - * - * @author lsl - * @date 2024-12-19 17:53:36 - */ -public interface ISFileService extends ISuperService { - /** - * 列表 - * @param params - * @return - */ - PageResult findList(Map params); -} - diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/LiveStreamService.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/LiveStreamService.java deleted file mode 100644 index 851573d7..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/LiveStreamService.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.central.device.service; - -import com.alibaba.fastjson.JSONObject; -import com.central.device.util.TencentLiveUtil; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.stereotype.Service; - -import java.util.concurrent.TimeUnit; - -@Service -public class LiveStreamService { - - @Value("${tencent.live.push-domain}") - private String pushDomain; - @Value("${tencent.live.play-domain}") - private String playDomain; - @Value("${tencent.live.app-name}") - private String appName; - @Value("${tencent.live.key}") - private String key; - @Value("${tencent.live.expire-seconds:3600}") - private long expireSeconds; - - private static final String STREAM_URL_KEY_PREFIX = "device:stream_urls:"; - - @Autowired - private StringRedisTemplate redisTemplate; - - /** - * 生成设备推流和拉流地址,并缓存到Redis - */ - public JSONObject generateStreamUrls(String deviceId) { - String cacheKey = STREAM_URL_KEY_PREFIX + deviceId; - String cacheValue = redisTemplate.opsForValue().get(cacheKey); - if (cacheValue != null) { - return JSONObject.parseObject(cacheValue); - } - - long expire = System.currentTimeMillis() / 1000 + expireSeconds; - String pushUrl = TencentLiveUtil.generatePushUrl(pushDomain, appName, deviceId, key, expire); - String playRtmpUrl = TencentLiveUtil.generatePlayUrl(playDomain, appName, deviceId, "rtmp"); - String playFlvUrl = TencentLiveUtil.generatePlayUrl(playDomain, appName, deviceId, "flv"); - String playM3u8Url = TencentLiveUtil.generatePlayUrl(playDomain, appName, deviceId, "m3u8"); - - JSONObject result = new JSONObject(); - result.put("pushUrl", pushUrl); - result.put("playRtmpUrl", playRtmpUrl); - result.put("playFlvUrl", playFlvUrl); - result.put("playM3u8Url", playM3u8Url); - - // 缓存到redis,设置过期时间(如1小时) - redisTemplate.opsForValue().set(cacheKey, result.toJSONString(), 1, TimeUnit.HOURS); - - return result; - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceFirmwareServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceFirmwareServiceImpl.java deleted file mode 100644 index 99ffce09..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceFirmwareServiceImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.central.device.service.impl; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.central.common.model.PageResult; -import com.central.common.service.impl.SuperServiceImpl; -import com.central.device.mapper.AgeDeviceFirmwareMapper; -import com.central.device.model.AgeDeviceFirmware; -import com.central.device.service.IAgeDeviceFirmwareService; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections4.MapUtils; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Map; - -/** - * Firmware file information - * - * @author lsl - * @date 2024-12-19 17:52:54 - */ -@Slf4j -@Service -public class AgeDeviceFirmwareServiceImpl extends SuperServiceImpl implements IAgeDeviceFirmwareService { - /** - * 列表 - * @param params - * @return - */ - @Override - public PageResult findList(Map params){ - Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); - List list = baseMapper.findList(page, params); - return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceHmsServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceHmsServiceImpl.java deleted file mode 100644 index 7061a557..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceHmsServiceImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.central.device.service.impl; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.central.common.model.PageResult; -import com.central.common.service.impl.SuperServiceImpl; -import com.central.device.mapper.AgeDeviceHmsMapper; -import com.central.device.model.AgeDeviceHms; -import com.central.device.service.IAgeDeviceHmsService; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections4.MapUtils; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Map; - -/** - * Device's hms information - * - * @author lsl - * @date 2024-12-19 17:53:01 - */ -@Slf4j -@Service -public class AgeDeviceHmsServiceImpl extends SuperServiceImpl implements IAgeDeviceHmsService { - /** - * 列表 - * @param params - * @return - */ - @Override - public PageResult findList(Map params){ - Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); - List list = baseMapper.findList(page, params); - return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceLogsServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceLogsServiceImpl.java deleted file mode 100644 index fd7ad125..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceLogsServiceImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.central.device.service.impl; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.central.common.model.PageResult; -import com.central.common.service.impl.SuperServiceImpl; -import com.central.device.mapper.AgeDeviceLogsMapper; -import com.central.device.model.AgeDeviceLogs; -import com.central.device.service.IAgeDeviceLogsService; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections4.MapUtils; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Map; - -/** - * Log for uploading logs - * - * @author lsl - * @date 2024-12-19 17:53:03 - */ -@Slf4j -@Service -public class AgeDeviceLogsServiceImpl extends SuperServiceImpl implements IAgeDeviceLogsService { - /** - * 列表 - * @param params - * @return - */ - @Override - public PageResult findList(Map params){ - Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); - List list = baseMapper.findList(page, params); - return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDevicePayloadServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDevicePayloadServiceImpl.java deleted file mode 100644 index 555676c5..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDevicePayloadServiceImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.central.device.service.impl; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.central.common.model.PageResult; -import com.central.common.service.impl.SuperServiceImpl; -import com.central.device.mapper.AgeDevicePayloadMapper; -import com.central.device.model.AgeDevicePayload; -import com.central.device.service.IAgeDevicePayloadService; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections4.MapUtils; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Map; - -/** - * The payload information of the device. - * - * @author lsl - * @date 2024-12-19 17:53:19 - */ -@Slf4j -@Service -public class AgeDevicePayloadServiceImpl extends SuperServiceImpl implements IAgeDevicePayloadService { - /** - * 列表 - * @param params - * @return - */ - @Override - public PageResult findList(Map params){ - Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); - List list = baseMapper.findList(page, params); - return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceServiceImpl.java deleted file mode 100644 index 68ae00cd..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeDeviceServiceImpl.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.central.device.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.central.common.model.PageResult; -import com.central.common.service.impl.SuperServiceImpl; -import com.central.device.mapper.AgeDeviceMapper; -import com.central.device.model.AgeDevice; -import com.central.device.service.IAgeDeviceService; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections4.MapUtils; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.CollectionUtils; - -import java.util.List; -import java.util.Map; - -/** - * Device information - * - * @author lsl - * @date 2024-12-19 17:51:47 - */ -@Slf4j -@Service -public class AgeDeviceServiceImpl extends SuperServiceImpl implements IAgeDeviceService { - /** - * 列表 - * @param params - * @return - */ - @Override - public PageResult findList(Map params){ - Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); - List list = baseMapper.findList(page, params); - return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); - } - - @Override - public List findListByParams(Map params) { - QueryWrapper wrapper = new QueryWrapper<>(); - // 添加查询条件 - if (params.get("deviceSn") != null) { - wrapper.like("device_sn", params.get("deviceSn")); - } - if (params.get("deviceName") != null) { - wrapper.like("device_name", params.get("deviceName")); - } - if (params.get("deviceType") != null) { - wrapper.eq("device_type", params.get("deviceType")); - } - // 可以添加更多查询条件... - return this.list(wrapper); - } - - @Override - public AgeDevice getByDeviceSn(String deviceSn) { - return this.getOne(new QueryWrapper().eq("device_sn", deviceSn)); - } - - @Override - public boolean checkDeviceSnExists(String deviceSn) { - return this.baseMapper.exists(new QueryWrapper() - .eq("device_sn", deviceSn)); - } - - @Transactional(rollbackFor = Exception.class) - @Override - public boolean importDevices(List deviceList) { - if (CollectionUtils.isEmpty(deviceList)) { - return false; - } - - try { - // 批量保存,每批100条 - int batchSize = 100; - int totalSize = deviceList.size(); - - for (int i = 0; i < totalSize; i += batchSize) { - int endIndex = Math.min(i + batchSize, totalSize); - List batch = deviceList.subList(i, endIndex); - this.saveBatch(batch, batchSize); - } - return true; - } catch (Exception e) { - log.error("批量导入设备信息失败", e); - throw new RuntimeException("批量导入设备信息失败", e); - } - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeFirmwareModelServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeFirmwareModelServiceImpl.java deleted file mode 100644 index c9f2485e..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeFirmwareModelServiceImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.central.device.service.impl; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.central.common.model.PageResult; -import com.central.common.service.impl.SuperServiceImpl; -import com.central.device.mapper.AgeFirmwareModelMapper; -import com.central.device.model.AgeFirmwareModel; -import com.central.device.service.IAgeFirmwareModelService; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections4.MapUtils; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Map; - -/** - * - * - * @author lsl - * @date 2024-12-19 17:53:20 - */ -@Slf4j -@Service -public class AgeFirmwareModelServiceImpl extends SuperServiceImpl implements IAgeFirmwareModelService { - /** - * 列表 - * @param params - * @return - */ - @Override - public PageResult findList(Map params){ - Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); - List list = baseMapper.findList(page, params); - return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeWorkspaceServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeWorkspaceServiceImpl.java deleted file mode 100644 index 99c1c297..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/AgeWorkspaceServiceImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.central.device.service.impl; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.central.common.model.PageResult; -import com.central.common.service.impl.SuperServiceImpl; -import com.central.device.mapper.AgeWorkspaceMapper; -import com.central.device.model.AgeWorkspace; -import com.central.device.service.IAgeWorkspaceService; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections4.MapUtils; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Map; - -/** - * - * - * @author lsl - * @date 2024-12-19 17:52:26 - */ -@Slf4j -@Service -public class AgeWorkspaceServiceImpl extends SuperServiceImpl implements IAgeWorkspaceService { - /** - * 列表 - * @param params - * @return - */ - @Override - public PageResult findList(Map params){ - Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); - List list = baseMapper.findList(page, params); - return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/IaFileServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/IaFileServiceImpl.java deleted file mode 100644 index 23bd3271..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/IaFileServiceImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.central.device.service.impl; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.central.common.model.PageResult; -import com.central.common.service.impl.SuperServiceImpl; -import com.central.device.mapper.IaFileMapper; -import com.central.device.model.IaFile; -import com.central.device.service.IIaFileService; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections4.MapUtils; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Map; - -/** - * Media file information - * - * @author lsl - * @date 2024-12-19 17:52:18 - */ -@Slf4j -@Service -public class IaFileServiceImpl extends SuperServiceImpl implements IIaFileService { - /** - * 列表 - * @param params - * @return - */ - @Override - public PageResult findList(Map params){ - Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); - List list = baseMapper.findList(page, params); - return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/LineFileServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/LineFileServiceImpl.java deleted file mode 100644 index 50a65f8b..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/LineFileServiceImpl.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.central.device.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.central.common.model.PageResult; -import com.central.common.service.impl.SuperServiceImpl; -import com.central.device.mapper.LineFileMapper; -import com.central.device.model.LineFile; -import com.central.device.service.ILineFileService; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections4.MapUtils; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Map; - -/** - * Wayline file information - * - * @author lsl - * @date 2024-12-19 17:51:52 - */ -@Slf4j -@Service -public class LineFileServiceImpl extends SuperServiceImpl implements ILineFileService { - /** - * 列表 - * @param params - * @return - */ - @Override - public PageResult findList(Map params){ - Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); - List list = baseMapper.findList(page, params); - return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); - } - - @Override - public LineFile findLineFileByWaylineId(String waylineId) { - return baseMapper.selectOne(new QueryWrapper() - .eq("wayline_id",waylineId)); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/LineJobServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/LineJobServiceImpl.java deleted file mode 100644 index 8f3b1c95..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/LineJobServiceImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.central.device.service.impl; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.central.common.model.PageResult; -import com.central.common.service.impl.SuperServiceImpl; -import com.central.device.mapper.LineJobMapper; -import com.central.device.model.LineJob; -import com.central.device.service.ILineJobService; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections4.MapUtils; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Map; - -/** - * Wayline mission information of the dock. - * - * @author lsl - * @date 2024-12-19 17:51:53 - */ -@Slf4j -@Service -public class LineJobServiceImpl extends SuperServiceImpl implements ILineJobService { - /** - * 列表 - * @param params - * @return - */ - @Override - public PageResult findList(Map params){ - Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); - List list = baseMapper.findList(page, params); - return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/SFileIndexServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/SFileIndexServiceImpl.java deleted file mode 100644 index 40ec93b1..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/SFileIndexServiceImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.central.device.service.impl; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.central.common.model.PageResult; -import com.central.common.service.impl.SuperServiceImpl; -import com.central.device.mapper.SFileIndexMapper; -import com.central.device.model.SFileIndex; -import com.central.device.service.ISFileIndexService; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections4.MapUtils; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Map; - -/** - * The boot index table corresponding to the logs file. - * - * @author lsl - * @date 2024-12-19 17:53:23 - */ -@Slf4j -@Service -public class SFileIndexServiceImpl extends SuperServiceImpl implements ISFileIndexService { - /** - * 列表 - * @param params - * @return - */ - @Override - public PageResult findList(Map params){ - Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); - List list = baseMapper.findList(page, params); - return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/SFileServiceImpl.java b/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/SFileServiceImpl.java deleted file mode 100644 index 3d508db3..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/service/impl/SFileServiceImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.central.device.service.impl; - -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.central.common.model.PageResult; -import com.central.common.service.impl.SuperServiceImpl; -import com.central.device.mapper.SFileMapper; -import com.central.device.model.SFile; -import com.central.device.service.ISFileService; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections4.MapUtils; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Map; - -/** - * Logs file information - * - * @author lsl - * @date 2024-12-19 17:53:36 - */ -@Slf4j -@Service -public class SFileServiceImpl extends SuperServiceImpl implements ISFileService { - /** - * 列表 - * @param params - * @return - */ - @Override - public PageResult findList(Map params){ - Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); - List list = baseMapper.findList(page, params); - return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/IotRequestResult.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/IotRequestResult.java deleted file mode 100644 index b0dffef1..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/util/IotRequestResult.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.central.device.util; - -import com.alibaba.fastjson.JSONObject; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.Getter; -import lombok.Setter; - -import java.util.List; - -/** - * IOT request result model - * @author lsl - * @date 2025-02-25 - * - */ -@Setter -@Getter -public class IotRequestResult { - - private String message; - private Integer status; - private Long timestamp; - private String code; - private List result; - - public static IotRequestResult getInstance(JSONObject message) throws JsonProcessingException { - ObjectMapper objectMapper = new ObjectMapper(); - - // 将JSONObject转换为JsonNode,因为ObjectMapper不直接接受JSONObject - JsonNode jsonNode = objectMapper.readTree(message.toString()); - - // 将JsonNode转换为指定的Java类 - return objectMapper.treeToValue(jsonNode, IotRequestResult.class); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/MapUtil.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/MapUtil.java deleted file mode 100644 index d86a6208..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/util/MapUtil.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.central.device.util; - -import java.util.Map; - -/** - * 获取map各类型值工具类 - * @author lishilin - * @date 2020/03/12 - */ -public class MapUtil { - public static String getStrValue(Map param, String id) { - Object val = getValue(param, id); - if (null == val) { - return null; - } - return val.toString(); - } - - public static Integer getIntValue(Map param, String id) { - Object val = getValue(param, id); - if (null == val) { - return null; - } - try { - return Integer.parseInt(param.get(id).toString()); - } catch (NumberFormatException exp) { - return null; - } - } - - public static Long getLongValue(Map param, String id) { - Object val = getValue(param, id); - if (null == val) { - return null; - } - try { - return Long.parseLong(param.get(id).toString()); - } catch (NumberFormatException exp) { - return null; - } - } - - public static Object getValue(Map param, String id) { - if (null == param && null == id) { - return null; - } - if (param.containsKey(id)) { - return param.get(id); - } - return null; - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/RequestUtils.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/RequestUtils.java deleted file mode 100644 index f59b5422..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/util/RequestUtils.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.central.device.util; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.central.device.util.http.HeaderUtils; -import com.central.device.util.http.HttpRequest; -import com.central.device.util.http.Response; -import com.central.device.util.http.SimpleHttpRequest; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.io.IOException; -import java.util.Map; - -/** - * @author LSL - */ -@Slf4j -@Component -public class RequestUtils { - - @Autowired - private HeaderUtils headerUtils; - - /** - * 获取post请求result - * @param url 请求url - * @param jsonObject 请求参数 - * @return - * @throws IOException - */ - public Map getPostRequestResultMap(String url, JSONObject jsonObject) throws IOException { - log.debug(url); - HttpRequest request = new SimpleHttpRequest(url); - request.headers(headerUtils.createHeadersOfJsonString(jsonObject.toJSONString())); - request.requestBody(jsonObject.toJSONString()); - Response response = request.post(); - Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); - return result; - } - - /** - * 获取post请求result - * @param url 请求url - * @param param 请求参数 - * @return - * @throws IOException - */ - public Map getPostRequestResultMap(String url, Map param) throws IOException { - log.debug(url); - HttpRequest request = new SimpleHttpRequest(url); - request.headers(headerUtils.createHeadersOfJsonString(JSON.toJSONString(param))); - request.requestBody(JSON.toJSONString(param)); - Response response = request.post(); - Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); - return result; - } - - /** - * 获取post请求result - * @param url 请求url - * @param body 请求参数 - * @return - * @throws IOException - */ - public Map getPostRequestResultMap(String url, String body) throws IOException { - log.debug(url); - HttpRequest request = new SimpleHttpRequest(url); - request.headers(headerUtils.createHeadersOfJsonString(body)); - request.requestBody(body); - Response response = request.post(); - Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); - log.debug(""+result.get("")); - return result; - } - - /** - * @param url 请求url - * @param map 请求参数map - * @return - * @throws IOException - */ - public Map getGetRequestResultMap(String url,Map map) throws IOException { - HttpRequest request = new SimpleHttpRequest(url); - request.headers(headerUtils.createHeadersOfParams(map)); - - Response response = request.get(); - Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); - return result; - } - - /** - * 获取post请求result - * @param url 请求url - * @param param 请求参数 - * @return - * @throws IOException - */ - public Map getThirdPartyPostRequestResultMap(String url, Map param) { - log.info("url:{} , {}",url,param); - HttpRequest request = new SimpleHttpRequest(url); - request.headers(headerUtils.createHeadersOfJsonString(JSON.toJSONString(param))); - request.requestBody(JSON.toJSONString(param)); - Response response; - Map result = null; - try { - response = request.post(); - result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); - } catch (IOException e) { - log.info("查询异常:{}",e.getMessage()); - e.printStackTrace(); - } - return result; - } - - -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/TencentLiveUtil.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/TencentLiveUtil.java deleted file mode 100644 index 13250dfa..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/util/TencentLiveUtil.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.central.device.util; - -import org.apache.commons.codec.digest.DigestUtils; - -public class TencentLiveUtil { - - /** - * 生成推流地址 - */ - public static String generatePushUrl(String pushDomain, String appName, String streamName, String key, long expireTime) { - String txTime = Long.toHexString(expireTime).toUpperCase(); - String txSecret = DigestUtils.md5Hex(key + streamName + txTime).toLowerCase(); - return String.format("rtmp://%s/%s/%s?txSecret=%s&txTime=%s", pushDomain, appName, streamName, txSecret, txTime); - } - - /** - * 生成拉流地址 - */ - public static String generatePlayUrl(String playDomain, String appName, String streamName, String type) { - switch (type.toLowerCase()) { - case "flv": - return String.format("http://%s/%s/%s.flv", playDomain, appName, streamName); - case "m3u8": - return String.format("http://%s/%s/%s.m3u8", playDomain, appName, streamName); - case "rtmp": - default: - return String.format("rtmp://%s/%s/%s", playDomain, appName, streamName); - } - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/Utils.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/Utils.java deleted file mode 100644 index fc2af9a5..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/util/Utils.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.central.device.util; - -import java.io.*; -import java.net.URLDecoder; -import java.util.HashMap; -import java.util.Map; - -/** - * @author lishilin - * @see - * @since 2.0 - */ -public class Utils { - public static Map queryStringToMap(String queryString, String charset){ - try { - Map map = new HashMap<>(); - - String[] decode = URLDecoder.decode(queryString,charset).split("&"); - for (String keyValue : decode) { - String[] kv = keyValue.split("[=]",2); - map.put(kv.length>1?kv[1]:"",kv[0]); - } - return map; - } catch (UnsupportedEncodingException e) { - throw new UnsupportedOperationException(e); - } - } - - /** - * 读文件 - * - * @param file 文件 - * @return - * @throws IOException - * @throws IOException - */ - public static String readTxt(File file) throws IOException { - String s = ""; - InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8"); - BufferedReader br = new BufferedReader(in); - StringBuffer content = new StringBuffer(); - while ((s = br.readLine()) != null) { - content = content.append(s); - } - return content.toString(); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/HeaderUtils.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/HeaderUtils.java deleted file mode 100644 index c066c6d5..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/HeaderUtils.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.central.device.util.http; - -import org.apache.commons.codec.binary.Hex; -import org.apache.commons.codec.digest.DigestUtils; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import java.security.MessageDigest; -import java.util.HashMap; -import java.util.Map; -import java.util.TreeMap; -import java.util.stream.Collectors; - -/** - * @author lishilin - * @see - * @since 1.0 - */ -@Component -public class HeaderUtils { - - @Value("${jetlinks.clientId}") - private String xClientId;// = "WFMfEGS8iHrEPRBH" ; - - @Value("${jetlinks.secureKey}") - private String secureKey;// = "ihat3zHC6T7xPZYFAEnG3tExQiFANd2n" ; - public Map createHeadersOfParams(Map params) { - //时间戳 - String xTimestamp = String.valueOf(System.currentTimeMillis()); - //openApi客户端id -// String xClientId = "rN7cpmQb884W4hcH"; - //密钥 -// String secureKey = "hBYtiNxQrA8FZbtetGhCZJPi"; - //将参数按ASCII排序后拼接为k1=v1&k2=v2的格式 - String paramString = new TreeMap<>(params).entrySet() - .stream() - .map(e -> e.getKey().concat("=").concat(String.valueOf(e.getValue()))) - .collect(Collectors.joining("&")); - - System.out.println(paramString); - - //param+X-Timestamp+SecureKey通过MD5加密 - MessageDigest digest = DigestUtils.getMd5Digest(); - System.out.println(paramString + xTimestamp + secureKey); - digest.update(paramString.getBytes()); - digest.update(xTimestamp.getBytes()); - digest.update(secureKey.getBytes()); - - Map headers = new HashMap<>(); - headers.put("X-Sign", Hex.encodeHexString(digest.digest())); - headers.put("X-Client-Id", xClientId); - headers.put("X-Timestamp", xTimestamp); - - return headers; - } - - - public Map createHeadersOfJsonString(String jsonString) { - //时间戳 - String xTimestamp = String.valueOf(System.currentTimeMillis()); - //openApi客户端id -// String xClientId = "rN7cpmQb884W4hcH"; - //密钥 -// String secureKey = "hBYtiNxQrA8FZbtetGhCZJPi"; - - - //param+X-Timestamp+SecureKey通过MD5加密 - MessageDigest digest = DigestUtils.getMd5Digest(); - System.out.println(jsonString + xTimestamp + secureKey); - digest.update(jsonString.getBytes()); - digest.update(xTimestamp.getBytes()); - digest.update(secureKey.getBytes()); - - Map headers = new HashMap<>(5); - headers.put("X-Sign", Hex.encodeHexString(digest.digest())); - headers.put("X-Client-Id", xClientId); - headers.put("X-Timestamp", xTimestamp); - - return headers; - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/HttpRequest.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/HttpRequest.java deleted file mode 100644 index 595298df..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/HttpRequest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.central.device.util.http; - -import java.io.Closeable; -import java.io.IOException; -import java.util.Map; - -/** - * @author wang - * @see - * @since 1.0 - */ -public interface HttpRequest extends Closeable { - - Response get() throws IOException; - - Response post() throws IOException; - - Response put() throws IOException; - - Response delete() throws IOException; - - Response patch() throws IOException; - - HttpRequest encode(String encode); - - HttpRequest contentType(String type); - - HttpRequest param(String name, String value); - - HttpRequest params(Map params); - - HttpRequest header(String name, String value); - - HttpRequest headers(Map headers); - - HttpRequest requestBody(String body); - - HttpRequest resultAsJsonString(); -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/Response.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/Response.java deleted file mode 100644 index 628d7faf..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/Response.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.central.device.util.http; - -import java.io.IOException; - -/** - * @author wang - * @see - * @since 1.0 - */ -public interface Response { - - byte[] asBytes() throws IOException; -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/SimpleHttpRequest.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/SimpleHttpRequest.java deleted file mode 100644 index d48136fe..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/SimpleHttpRequest.java +++ /dev/null @@ -1,184 +0,0 @@ -package com.central.device.util.http; - -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.client.HttpClient; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.*; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.util.EntityUtils; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * @author wang - * @see - * @since 1.0 - */ -public class SimpleHttpRequest implements HttpRequest { - - private Map params = new LinkedHashMap<>(); - private Map headers = new LinkedHashMap<>(); - private String url; - private String requestBody; - private String contentType; - private String encode = "utf-8"; - protected HttpClient httpClient; - - public SimpleHttpRequest(String url) { - this.url = url; - createHttpClient(); - } - - public SimpleHttpRequest(String url, HttpClient client) { - this.url = url; - this.httpClient = client; - } - - protected void createHttpClient() { - if (httpClient == null) { - HttpClientBuilder builder = HttpClientBuilder.create(); - httpClient = builder.build(); - - } - } - - @Override - public Response get() throws IOException { - String param = EntityUtils.toString(createUrlEncodedFormEntity()); - String tmpUrl = url + (url.contains("?") ? "&" : "?") + param; - HttpGet get = new HttpGet(tmpUrl); - HttpResponse response = execute(get); - return getResultValue(response); - } - - - @Override - public Response post() throws IOException { - HttpPost post = new HttpPost(url); - if (requestBody != null) - post.setEntity(new StringEntity(requestBody, ContentType.create(contentType,encode))); - else { - post.setEntity(createUrlEncodedFormEntity()); - } - HttpResponse response = execute(post); - return getResultValue(response); - } - - @Override - public Response put() throws IOException { - HttpPut put = new HttpPut(url); - if (requestBody != null) - put.setEntity(new StringEntity(requestBody, ContentType.create(contentType, encode))); - else { - - put.setEntity(createUrlEncodedFormEntity()); - } - HttpResponse response = execute(put); - return getResultValue(response); - } - - protected UrlEncodedFormEntity createUrlEncodedFormEntity() throws UnsupportedEncodingException { - List nameValuePair = params.entrySet() - .stream().map(stringStringEntry -> - new BasicNameValuePair(stringStringEntry.getKey(), String.valueOf(stringStringEntry.getValue()))) - .collect(Collectors.toList()); - return new UrlEncodedFormEntity(nameValuePair, encode); - } - - @Override - public Response delete() throws IOException { - HttpDelete delete = new HttpDelete(url); - HttpResponse response = execute(delete); - return getResultValue(response); - } - - @Override - public Response patch() throws IOException { - HttpPatch delete = new HttpPatch(url); - if (requestBody != null) - delete.setEntity(new StringEntity(requestBody, ContentType.create(contentType))); - else { - delete.setEntity(createUrlEncodedFormEntity()); - } - return getResultValue(execute(delete)); - } - - @Override - public void close() throws IOException { - if (httpClient != null && httpClient instanceof CloseableHttpClient) { - ((CloseableHttpClient) httpClient).close(); - } - } - - @Override - public HttpRequest resultAsJsonString() { - header("Accept", "application/json"); - return this; - } - - @Override - public HttpRequest requestBody(String body) { - contentType("application/json"); - this.requestBody = body; - return this; - } - - @Override - public HttpRequest encode(String encode) { - this.encode = encode; - return this; - } - - @Override - public HttpRequest contentType(String type) { - this.contentType = type; - return this; - } - - @Override - public HttpRequest param(String name, String value) { - this.params.put(name, value); - return this; - } - - @Override - public HttpRequest params(Map params) { - this.params.putAll(params); - return this; - } - - @Override - public HttpRequest header(String name, String value) { - this.headers.put(name, value); - return this; - } - - @Override - public HttpRequest headers(Map header) { - this.headers.putAll(header); - return this; - } - - private Response getResultValue(HttpResponse res) throws IOException { - return new SimpleResponse(res); - } - - private HttpResponse execute(HttpRequestBase request) throws IOException { - putHeader(request); - return httpClient.execute(request); - } - - private void putHeader(HttpUriRequest request) { - headers.forEach(request::setHeader); - } -} diff --git a/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/SimpleResponse.java b/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/SimpleResponse.java deleted file mode 100644 index 6444f876..00000000 --- a/zlt-business/device-ops-center/src/main/java/com/central/device/util/http/SimpleResponse.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.central.device.util.http; - -import org.apache.http.HttpResponse; -import org.apache.http.util.EntityUtils; - -import java.io.IOException; - -/** - * @author wang - * @see - * @since 1.0 - */ -public class SimpleResponse implements Response { - - HttpResponse response; - - public SimpleResponse(HttpResponse response) { - this.response = response; - } - - - @Override - public byte[] asBytes() throws IOException { - return EntityUtils.toByteArray(response.getEntity()); - } -} diff --git a/zlt-business/device-ops-center/src/main/resources/application.yml b/zlt-business/device-ops-center/src/main/resources/application.yml deleted file mode 100644 index 32f0c2e5..00000000 --- a/zlt-business/device-ops-center/src/main/resources/application.yml +++ /dev/null @@ -1,59 +0,0 @@ -spring: - datasource: -# url: jdbc:mysql://${zlt.datasource.ip}:3306/device-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai - url: jdbc:mysql://${zlt.datasource.ip}/device-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai - username: ${zlt.datasource.username} - password: ${zlt.datasource.password} - driver-class-name: com.mysql.cj.jdbc.Driver - -mybatis-plus: - mapper-locations: classpath:/mapper/*Mapper.xml - #实体扫描,多个package用逗号或者分号分隔 - typeAliasesPackage: com.central.device.model - global-config: - db-config: - id-type: auto - -springdoc: - group-configs: - - group: 'default' - paths-to-match: '/**' - packages-to-scan: com.central.device.controller - -knife4j: - enable: true - setting: - swagger-model-name: 设备中心接口文档 - -jetlinks: - clientId: WFMfEGS8iHrEPRBH - secureKey: ihat3zHC6T7xPZYFAEnG3tExQiFANd2n - server: - baseUrl: http://119.45.169.13:8848/ - - #审计日志 -# audit-log: -# enabled: true -# log-type: db -# datasource: -# driver-class-name: com.mysql.cj.jdbc.Driver -# jdbc-url: jdbc:mysql://${zlt.datasource.ip}:3306/logger-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai -# username: ${zlt.datasource.username} -# password: ${zlt.datasource.password} -tencent: - live: - push-domain: 208280.push.tlivecloud.com - play-domain: goflytec.com - expire-seconds: 3600 #过期时间为1小时 - app-name: live - key: 06b20e5b7d637c1128fa1b48ea91a13e - -zlt: - #多租户配置 - tenant: - enable: false - ignoreTables: - ignoreSqls: - noIgnoreSqls: - - com.central.device.mapper.AgeDeviceMapper.findList - - com.central.device.mapper.LineFileMapper.findList diff --git a/zlt-business/device-ops-center/src/main/resources/bootstrap.yml b/zlt-business/device-ops-center/src/main/resources/bootstrap.yml deleted file mode 100644 index 1f7e34f6..00000000 --- a/zlt-business/device-ops-center/src/main/resources/bootstrap.yml +++ /dev/null @@ -1,15 +0,0 @@ -server: - port: 7003 - -spring: - application: - name: device-ops-center -# cloud: -# nacos: -# discovery: -# ip: 119.45.169.13 -# cloud: -# nacos: -# discovery: -# metadata: -# version: zlt diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceFirmwareMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceFirmwareMapper.xml deleted file mode 100644 index 33de4e1c..00000000 --- a/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceFirmwareMapper.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceHmsMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceHmsMapper.xml deleted file mode 100644 index 2bcf9d0b..00000000 --- a/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceHmsMapper.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceLogsMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceLogsMapper.xml deleted file mode 100644 index 09722eb0..00000000 --- a/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceLogsMapper.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceMapper.xml deleted file mode 100644 index efa174ba..00000000 --- a/zlt-business/device-ops-center/src/main/resources/mapper/AgeDeviceMapper.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/AgeDevicePayloadMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/AgeDevicePayloadMapper.xml deleted file mode 100644 index ea9fd213..00000000 --- a/zlt-business/device-ops-center/src/main/resources/mapper/AgeDevicePayloadMapper.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/AgeFirmwareModelMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/AgeFirmwareModelMapper.xml deleted file mode 100644 index 32e77875..00000000 --- a/zlt-business/device-ops-center/src/main/resources/mapper/AgeFirmwareModelMapper.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/AgeWorkspaceMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/AgeWorkspaceMapper.xml deleted file mode 100644 index 9ba31ce1..00000000 --- a/zlt-business/device-ops-center/src/main/resources/mapper/AgeWorkspaceMapper.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/IaFileMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/IaFileMapper.xml deleted file mode 100644 index 4e6723cd..00000000 --- a/zlt-business/device-ops-center/src/main/resources/mapper/IaFileMapper.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/LineFileMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/LineFileMapper.xml deleted file mode 100644 index b5fcb3e5..00000000 --- a/zlt-business/device-ops-center/src/main/resources/mapper/LineFileMapper.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/LineJobMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/LineJobMapper.xml deleted file mode 100644 index b498a16d..00000000 --- a/zlt-business/device-ops-center/src/main/resources/mapper/LineJobMapper.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/SFileIndexMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/SFileIndexMapper.xml deleted file mode 100644 index 38f304e6..00000000 --- a/zlt-business/device-ops-center/src/main/resources/mapper/SFileIndexMapper.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/zlt-business/device-ops-center/src/main/resources/mapper/SFileMapper.xml b/zlt-business/device-ops-center/src/main/resources/mapper/SFileMapper.xml deleted file mode 100644 index 3b2002ce..00000000 --- a/zlt-business/device-ops-center/src/main/resources/mapper/SFileMapper.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/OrderController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/OrderController.java index 99e61688..17246d3a 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/controller/OrderController.java +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/OrderController.java @@ -1,6 +1,8 @@ package com.central.order.controller; import com.alibaba.csp.sentinel.util.StringUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.central.common.constant.CommonConstant; import com.central.common.context.LoginUserContextHolder; import com.central.common.context.TenantContextHolder; @@ -10,7 +12,6 @@ import com.central.common.model.PageResult; import com.central.common.model.Result; import com.central.common.model.SysUser; import com.central.log.annotation.AuditLog; -import com.central.order.constants.OrderStatusConstants; import com.central.order.enums.CommonStatus; import com.central.order.enums.OrderStatus; import com.central.order.feign.DeviceCenterService; @@ -1515,4 +1516,99 @@ public class OrderController { return Result.failed("获取订单信息异常: " + e.getMessage()); } } + + @Operation(summary = "二维码订单统计查询") + @Parameters({ + @Parameter(name = "tenantId", description = "租户ID", in = ParameterIn.QUERY), + @Parameter(name = "includeChildren", description = "是否包含下级租户", in = ParameterIn.QUERY), + @Parameter(name = "qrcodeName", description = "二维码名称", in = ParameterIn.QUERY), + @Parameter(name = "codeId", description = "二维码Code", in = ParameterIn.QUERY), + @Parameter(name = "tourismId", description = "景区ID", in = ParameterIn.QUERY) + }) + @GetMapping("/qrcode/order/statistics") + public Result getQrcodeOrderStatistics(@RequestParam Map params) { + log.info("查询二维码订单统计,params: {}", params); + try { + Map result = orderService.getQrcodeOrderStatistics(params); + return Result.succeed(result); + } catch (Exception e) { + log.error("查询二维码订单统计异常", e); + return Result.failed("查询失败: " + e.getMessage()); + } + } + + @Operation(summary = "根据二维码ID查询订单列表") + @Parameters({ + @Parameter(name = "page", description = "分页起始位置", required = true, in = ParameterIn.QUERY), + @Parameter(name = "limit", description = "分页结束位置", required = true, in = ParameterIn.QUERY), + @Parameter(name = "codeId", description = "二维码ID", required = true, in = ParameterIn.PATH) + }) + @GetMapping("/qrcode/{codeId}/orders") + public PageResult getOrdersByCodeId( + @PathVariable("codeId") String codeId, + @RequestParam Map params) { + log.info("=== 根据二维码ID查询订单列表 ==="); + log.info("codeId: {}, params: {}", codeId, params); + + try { + // 直接用QueryWrapper查询,不走findList(避免tourismIds过滤) + Integer pageNum = Integer.parseInt(params.getOrDefault("page", "1").toString()); + Integer pageSize = Integer.parseInt(params.getOrDefault("limit", "10").toString()); + + Page page = new Page<>(pageNum, pageSize); + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("code_id", codeId); + wrapper.eq("is_del", 0); + wrapper.eq("order_status", 3); + + // 时间过滤 - 时间戳转Date + Object payTimeStartObj = params.get("payTimeStart"); + Object payTimeEndObj = params.get("payTimeEnd"); + log.info("时间参数: payTimeStart={}, payTimeEnd={}", payTimeStartObj, payTimeEndObj); + + if (payTimeStartObj != null && !payTimeStartObj.toString().isEmpty()) { + long ts = Long.parseLong(payTimeStartObj.toString()); + Date startDate = new Date(ts); + log.info("开始时间转换: timestamp={} -> date={}", ts, startDate); + wrapper.ge("pay_time", startDate); + } + if (payTimeEndObj != null && !payTimeEndObj.toString().isEmpty()) { + long ts = Long.parseLong(payTimeEndObj.toString()); + Date endDate = new Date(ts); + log.info("结束时间转换: timestamp={} -> date={}", ts, endDate); + wrapper.le("pay_time", endDate); + } + + wrapper.orderByDesc("create_time"); + + // 先查询不带时间条件的总数,用于调试 + QueryWrapper debugWrapper = new QueryWrapper<>(); + debugWrapper.eq("code_id", codeId); + debugWrapper.eq("is_del", 0); + debugWrapper.eq("order_status", 3); + long totalWithoutTime = orderService.count(debugWrapper); + log.info("不带时间条件的订单总数: {}", totalWithoutTime); + + Page result = orderService.page(page, wrapper); + + log.info("查询结果: 总数={}, 当前页数量={}", result.getTotal(), result.getRecords().size()); + + // 打印前几条订单的pay_time,用于调试 + if (!result.getRecords().isEmpty()) { + for (int i = 0; i < Math.min(3, result.getRecords().size()); i++) { + Order o = result.getRecords().get(i); + log.info("订单[{}]: orderNo={}, pay_time={}", i, o.getOrderNo(), o.getPayTime()); + } + } + + return PageResult.builder() + .data(result.getRecords()) + .resp_code(0) + .count(result.getTotal()) + .build(); + } catch (Exception e) { + log.error("根据二维码ID查询订单列表异常", e); + return new PageResult(); + } + } } diff --git a/zlt-business/order-center/src/main/java/com/central/order/feign/DeviceCenterService.java b/zlt-business/order-center/src/main/java/com/central/order/feign/DeviceCenterService.java index 13d23939..f454f9c9 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/feign/DeviceCenterService.java +++ b/zlt-business/order-center/src/main/java/com/central/order/feign/DeviceCenterService.java @@ -49,4 +49,58 @@ public interface DeviceCenterService { Result executeWayline(@RequestParam("deviceSn") String deviceSn, @RequestParam("waylineId") String waylineId, @RequestParam("missionCode") String missionCode); + + /** + * 执行无人船航线任务 + * + * @param deviceSn 设备SN + * @param boatRouteId 无人船航线ID + * @param missionCode 任务编码 + * @return 执行结果(任务ID) + */ + @Operation(summary = "执行无人船航线任务") + @PostMapping("/device/boat/command/route/execute") + Result executeBoatRoute(@RequestParam("deviceSn") String deviceSn, + @RequestParam("boatRouteId") String boatRouteId, + @RequestParam("missionCode") String missionCode); + + /** + * 暂停无人船航行 + * + * @param deviceSn 设备SN + * @return 执行结果 + */ + @Operation(summary = "暂停无人船航行") + @PostMapping("/device/boat/command/pause") + Result pauseBoatNavigation(@RequestParam("deviceSn") String deviceSn); + + /** + * 恢复无人船航行 + * + * @param deviceSn 设备SN + * @return 执行结果 + */ + @Operation(summary = "恢复无人船航行") + @PostMapping("/device/boat/command/resume") + Result resumeBoatNavigation(@RequestParam("deviceSn") String deviceSn); + + /** + * 无人船返回起点 + * + * @param deviceSn 设备SN + * @return 执行结果 + */ + @Operation(summary = "无人船返回起点") + @PostMapping("/device/boat/command/return") + Result returnBoatToStart(@RequestParam("deviceSn") String deviceSn); + + /** + * 无人船紧急停止 + * + * @param deviceSn 设备SN + * @return 执行结果 + */ + @Operation(summary = "无人船紧急停止") + @PostMapping("/device/boat/command/emergency-stop") + Result emergencyStopBoat(@RequestParam("deviceSn") String deviceSn); } diff --git a/zlt-business/order-center/src/main/java/com/central/order/feign/fallback/DeviceCenterServiceFallbackFactory.java b/zlt-business/order-center/src/main/java/com/central/order/feign/fallback/DeviceCenterServiceFallbackFactory.java index cc5c29cc..2de02f64 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/feign/fallback/DeviceCenterServiceFallbackFactory.java +++ b/zlt-business/order-center/src/main/java/com/central/order/feign/fallback/DeviceCenterServiceFallbackFactory.java @@ -46,6 +46,37 @@ public class DeviceCenterServiceFallbackFactory implements FallbackFactory executeBoatRoute(String deviceSn, String boatRouteId, String missionCode) { + log.error("调用设备中心executeBoatRoute失败: deviceSn={}, boatRouteId={}, missionCode={}, error={}", + deviceSn, boatRouteId, missionCode, cause.getMessage()); + return Result.failed("设备中心服务调用失败"); + } + + @Override + public Result pauseBoatNavigation(String deviceSn) { + log.error("调用设备中心pauseBoatNavigation失败: deviceSn={}, error={}", deviceSn, cause.getMessage()); + return Result.failed("设备中心服务调用失败"); + } + + @Override + public Result resumeBoatNavigation(String deviceSn) { + log.error("调用设备中心resumeBoatNavigation失败: deviceSn={}, error={}", deviceSn, cause.getMessage()); + return Result.failed("设备中心服务调用失败"); + } + + @Override + public Result returnBoatToStart(String deviceSn) { + log.error("调用设备中心returnBoatToStart失败: deviceSn={}, error={}", deviceSn, cause.getMessage()); + return Result.failed("设备中心服务调用失败"); + } + + @Override + public Result emergencyStopBoat(String deviceSn) { + log.error("调用设备中心emergencyStopBoat失败: deviceSn={}, error={}", deviceSn, cause.getMessage()); + return Result.failed("设备中心服务调用失败"); + } }; } } diff --git a/zlt-business/order-center/src/main/java/com/central/order/mission/enums/MissionType.java b/zlt-business/order-center/src/main/java/com/central/order/mission/enums/MissionType.java index 6de25b66..40ea8863 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/mission/enums/MissionType.java +++ b/zlt-business/order-center/src/main/java/com/central/order/mission/enums/MissionType.java @@ -12,7 +12,8 @@ import lombok.Getter; @Getter public enum MissionType implements ZltEnum { WAYLINE(1, "航线任务"), - TAKEOFF(2, "一键起飞任务"); + TAKEOFF(2, "一键起飞任务"), + BOAT_ROUTE(3, "无人船航线任务"); MissionType(Integer id, String content) { this.id = id; @@ -50,4 +51,11 @@ public enum MissionType implements ZltEnum { public static boolean isTakeoffTask(Integer type) { return type != null && type.equals(TAKEOFF.getId()); } + + /** + * 判断是否为无人船航线任务 + */ + public static boolean isBoatRouteTask(Integer type) { + return type != null && type.equals(BOAT_ROUTE.getId()); + } } diff --git a/zlt-business/order-center/src/main/java/com/central/order/mission/model/Mission.java b/zlt-business/order-center/src/main/java/com/central/order/mission/model/Mission.java index 26e5e4ac..3dae4ccf 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/mission/model/Mission.java +++ b/zlt-business/order-center/src/main/java/com/central/order/mission/model/Mission.java @@ -40,6 +40,12 @@ public class Mission extends SuperEntity { @Schema(description = "航线名称") private String waylineName; + @Schema(description = "无人船航线ID(无人船任务必填)") + private String boatRouteId; + + @Schema(description = "无人船航线名称") + private String boatRouteName; + @Schema(description = "工作区ID") private String workspaceId; diff --git a/zlt-business/order-center/src/main/java/com/central/order/mission/service/impl/MissionServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/mission/service/impl/MissionServiceImpl.java index 719a890d..fd26e3df 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/mission/service/impl/MissionServiceImpl.java +++ b/zlt-business/order-center/src/main/java/com/central/order/mission/service/impl/MissionServiceImpl.java @@ -251,6 +251,26 @@ public class MissionServiceImpl extends ServiceImpl impl updateMissionStatus(mission.getMissionCode(), MissionStatus.DOING.getId()); return true; } + } else if (MissionType.isBoatRouteTask(missionType)) { + // 无人船航线任务:调用无人船航线执行接口 + log.info("下发无人船航线任务到设备: missionCode={}, deviceSn={}, boatRouteId={}", + mission.getMissionCode(), mission.getDeviceSn(), mission.getBoatRouteId()); + // 调用设备中心的无人船航线执行接口 + Result result = deviceCenterService.executeBoatRoute( + mission.getDeviceSn(), + mission.getBoatRouteId(), + mission.getMissionCode() + ); + if (result != null && result.getResp_code() == 0) { + // 更新任务状态为执行中 + updateMissionStatus(mission.getMissionCode(), MissionStatus.DOING.getId()); + log.info("无人船航线任务下发成功: missionCode={}, taskId={}", mission.getMissionCode(), result.getData()); + return true; + } else { + String errorMsg = result != null ? result.getResp_msg() : "设备中心服务调用失败"; + log.error("无人船航线任务下发失败: missionCode={}, error={}", mission.getMissionCode(), errorMsg); + return false; + } } else { log.error("未知的任务类型: {}", missionType); return false; diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IOrderService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IOrderService.java index e130b370..48be2a6d 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/service/IOrderService.java +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IOrderService.java @@ -96,5 +96,12 @@ public interface IOrderService extends ISuperService { Long getUnCompleteOrderCount(String deviceSn); Order getNextQueueOrder(Long tourismId, Long currentOrderId); + + /** + * 二维码订单统计查询 + * @param params 查询参数(tenantId, includeChildren, qrcodeName, codeId, tourismId) + * @return 统计结果(tourismList: 景区列表,每个景区包含qrcodeList: 二维码统计列表) + */ + Map getQrcodeOrderStatistics(Map params); } diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java index a5403520..9be1a485 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java @@ -28,10 +28,7 @@ import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Objects; +import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @@ -425,4 +422,283 @@ public class OrderServiceImpl extends SuperServiceImpl imple return baseMapper.selectOne(wrapper); } + @Override + public Map getQrcodeOrderStatistics(Map params) { + + String qrcodeName = MapUtils.getString(params, "qrcodeName"); + String codeId = MapUtils.getString(params, "codeId"); + Long tourismId = MapUtils.getLong(params, "tourismId"); + + // 分页参数 + Integer page = MapUtils.getInteger(params, "page", 1); + Integer limit = MapUtils.getInteger(params, "limit", 10); + + // 支付时间查询条件 - 处理可能是字符串的情况 + Date payTimeStart = null; + Date payTimeEnd = null; + + Object payTimeStartObj = params.get("payTimeStart"); + Object payTimeEndObj = params.get("payTimeEnd"); + + try { + if (payTimeStartObj instanceof Date) { + payTimeStart = (Date) payTimeStartObj; + } else if (payTimeStartObj instanceof Long) { + payTimeStart = new Date((Long) payTimeStartObj); + } else if (payTimeStartObj instanceof Integer) { + payTimeStart = new Date(((Integer) payTimeStartObj).longValue()); + } else if (payTimeStartObj instanceof String) { + String timeStr = (String) payTimeStartObj; + // 尝试解析为时间戳 + try { + long timestamp = Long.parseLong(timeStr); + payTimeStart = new Date(timestamp); + } catch (NumberFormatException e) { + // 如果不是时间戳,尝试按日期格式解析 + payTimeStart = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(timeStr); + } + } + + if (payTimeEndObj instanceof Date) { + payTimeEnd = (Date) payTimeEndObj; + } else if (payTimeEndObj instanceof Long) { + payTimeEnd = new Date((Long) payTimeEndObj); + } else if (payTimeEndObj instanceof Integer) { + payTimeEnd = new Date(((Integer) payTimeEndObj).longValue()); + } else if (payTimeEndObj instanceof String) { + String timeStr = (String) payTimeEndObj; + // 尝试解析为时间戳 + try { + long timestamp = Long.parseLong(timeStr); + payTimeEnd = new Date(timestamp); + } catch (NumberFormatException e) { + // 如果不是时间戳,尝试按日期格式解析 + payTimeEnd = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(timeStr); + } + } + } catch (Exception e) { + log.error("解析支付时间失败", e); + } + + // 如果没有传支付时间,默认查询当天 + if (payTimeStart == null) { + payTimeStart = DateUtils.getStartOfDay(new Date()); + } + if (payTimeEnd == null) { + payTimeEnd = DateUtils.getEndOfDay(new Date()); + } + + // 1. 获取租户ID(参考景区管理的查询逻辑) + String anchor = MapUtils.getString(params, "tenantId"); + try { + if (anchor == null || anchor.isEmpty()) { + anchor = com.central.common.context.TenantQueryOverrideContext.getTenantId(); + if (anchor == null || anchor.isEmpty()) { + anchor = com.central.common.context.LoginUserContextHolder.getCurrentTenantId(); + } + } + } catch (Exception ignored) { + log.error("获取当前登录用户租户失败"); + } + + // 2. 获取当前租户及所有子租户ID列表 + List tenantIds = userCenterService.getSonTenantIds(anchor); + + // 3. 统计总数(不受时间和其他筛选条件影响) + Date startOfToday = DateUtils.getStartOfDay(new Date()); + Date endOfToday = DateUtils.getEndOfDay(new Date()); + + // 3.1 统计景区总数(不受tourismId等筛选条件影响) + QueryWrapper totalTourismWrapper = new QueryWrapper<>(); + if (tenantIds != null && !tenantIds.isEmpty()) { + totalTourismWrapper.in("tenant_id", tenantIds); + } + totalTourismWrapper.eq("is_del", 0); + long totalTourismCount = tourismMapper.selectCount(totalTourismWrapper); + + // 3.2 查询该租户下所有景区ID + List allTourismIds = tourismMapper.selectList(totalTourismWrapper) + .stream().map(Tourism::getId).collect(java.util.stream.Collectors.toList()); + + // 3.3 统计二维码总数(不受qrcodeName、codeId筛选条件影响) + int totalQrcodeCount = 0; + if (!allTourismIds.isEmpty()) { + QueryWrapper totalQrcodeWrapper = new QueryWrapper<>(); + totalQrcodeWrapper.in("tourism_id", allTourismIds); + totalQrcodeWrapper.eq("is_del", 0); + totalQrcodeCount = qrCodeMapper.selectCount(totalQrcodeWrapper).intValue(); + } + + // 3.4 统计订单总数(不受时间限制,只统计完成状态的订单) + long totalOrderCount = 0; + long todayOrderCount = 0; + if (!allTourismIds.isEmpty()) { + // 查询该租户下所有二维码的codeId + QueryWrapper allQrcodeWrapper = new QueryWrapper<>(); + allQrcodeWrapper.in("tourism_id", allTourismIds); + allQrcodeWrapper.eq("is_del", 0); + List allCodeIds = qrCodeMapper.selectList(allQrcodeWrapper) + .stream().map(QrCode::getCodeId).collect(java.util.stream.Collectors.toList()); + log.info("二维码codeId列表: {}", allCodeIds); + + if (!allCodeIds.isEmpty()) { + // 统计所有完成订单数(状态3,不受时间限制) + QueryWrapper totalOrderWrapper = new QueryWrapper<>(); + totalOrderWrapper.in("code_id", allCodeIds); + totalOrderWrapper.eq("is_del", 0); + totalOrderWrapper.eq("order_status", 3); + totalOrderCount = baseMapper.selectCount(totalOrderWrapper); + + // 统计今日完成订单数(状态3,按pay_time统计) + QueryWrapper todayOrderWrapper = new QueryWrapper<>(); + todayOrderWrapper.in("code_id", allCodeIds); + todayOrderWrapper.eq("is_del", 0); + todayOrderWrapper.eq("order_status", 3); + todayOrderWrapper.between("pay_time", startOfToday, endOfToday); + todayOrderCount = baseMapper.selectCount(todayOrderWrapper); + } else { + log.warn("二维码codeId列表为空,无法统计订单"); + } + } else { + log.warn("景区ID列表为空,无法统计二维码和订单"); + } + + // 4. 如果有二维码筛选条件,先找到匹配的二维码所属的景区ID + Set filteredTourismIds = null; + if ((codeId != null && !codeId.isEmpty()) || (qrcodeName != null && !qrcodeName.isEmpty())) { + QueryWrapper filterQrCodeWrapper = new QueryWrapper<>(); + filterQrCodeWrapper.in("tourism_id", allTourismIds); + filterQrCodeWrapper.eq("is_del", 0); + if (qrcodeName != null && !qrcodeName.isEmpty()) { + filterQrCodeWrapper.like("name", qrcodeName); + } + if (codeId != null && !codeId.isEmpty()) { + filterQrCodeWrapper.like("code_id", codeId); + } + List filteredQrCodes = qrCodeMapper.selectList(filterQrCodeWrapper); + filteredTourismIds = filteredQrCodes.stream() + .map(QrCode::getTourismId) + .collect(java.util.stream.Collectors.toSet()); + } + + // 5. 根据租户ID列表查询景区列表(带分页,用于展示) + Page tourismPage = new Page<>(page, limit); + QueryWrapper tourismWrapper = new QueryWrapper<>(); + if (tenantIds != null && !tenantIds.isEmpty()) { + tourismWrapper.in("tenant_id", tenantIds); + } + if (tourismId != null) { + tourismWrapper.eq("id", tourismId); + } + // 如果有二维码筛选条件,只查这些景区 + if (filteredTourismIds != null) { + if (filteredTourismIds.isEmpty()) { + // 没有匹配的二维码,直接返回空结果 + Map result = new java.util.HashMap<>(); + result.put("tourismList", new java.util.ArrayList<>()); + result.put("totalTourismCount", totalTourismCount); + result.put("totalQrcodeCount", totalQrcodeCount); + result.put("totalOrderCount", totalOrderCount); + result.put("todayOrderCount", todayOrderCount); + result.put("payTimeStart", payTimeStart); + result.put("payTimeEnd", payTimeEnd); + result.put("page", page); + result.put("limit", limit); + result.put("hasMore", false); + return result; + } + tourismWrapper.in("id", filteredTourismIds); + } + tourismWrapper.eq("is_del", 0); + // 景区倒序排列 + tourismWrapper.orderByDesc("id"); + tourismPage = tourismMapper.selectPage(tourismPage, tourismWrapper); + + List tourismList = tourismPage.getRecords(); + + // 6. 遍历景区,查询二维码和订单统计(用于展示详细列表) + List> tourismDataList = new java.util.ArrayList<>(); + for (Tourism tourism : tourismList) { + // 查询该景区的二维码列表 + QueryWrapper qrCodeWrapper = new QueryWrapper<>(); + qrCodeWrapper.eq("tourism_id", tourism.getId()); + qrCodeWrapper.eq("is_del", 0); + + // 根据条件筛选二维码 + if (qrcodeName != null && !qrcodeName.isEmpty()) { + qrCodeWrapper.like("name", qrcodeName); + } + if (codeId != null && !codeId.isEmpty()) { + qrCodeWrapper.like("code_id", codeId); + } + + List qrCodeList = qrCodeMapper.selectList(qrCodeWrapper); + + if (qrCodeList.isEmpty()) { + continue; // 如果该景区没有符合条件的二维码,跳过 + } + + List> qrcodeDataList = new java.util.ArrayList<>(); + long tourismOrderCount = 0; + + for (QrCode qrCode : qrCodeList) { + // 统计该二维码的订单数量(状态为3,pay_time在时间范围内) + QueryWrapper orderWrapper = new QueryWrapper<>(); + orderWrapper.eq("code_id", qrCode.getCodeId()); + orderWrapper.eq("is_del", 0); + orderWrapper.eq("order_status", 3); + orderWrapper.between("pay_time", payTimeStart, payTimeEnd); + Long orderCount = baseMapper.selectCount(orderWrapper); + + // 统计该二维码今日订单数量(状态为3) + QueryWrapper todayOrderWrapper = new QueryWrapper<>(); + todayOrderWrapper.eq("code_id", qrCode.getCodeId()); + todayOrderWrapper.eq("is_del", 0); + todayOrderWrapper.eq("order_status", 3); + todayOrderWrapper.between("pay_time", startOfToday, endOfToday); + Long todayCount = baseMapper.selectCount(todayOrderWrapper); + + Map qrcodeData = new java.util.HashMap<>(); + qrcodeData.put("id", qrCode.getId()); + qrcodeData.put("qrcodeId", qrCode.getCodeId()); + qrcodeData.put("qrcodeName", qrCode.getName()); + qrcodeData.put("qrcodeCode", qrCode.getCodeId()); + qrcodeData.put("orderCount", orderCount); + qrcodeData.put("todayOrderCount", todayCount); + qrcodeData.put("viewUrl", fileCenterService.getViewUrlByPath(qrCode.getFilePath())); + qrcodeData.put("status", qrCode.getStatus()); + qrcodeData.put("price", qrCode.getPrice()); + qrcodeData.put("deviceSn", qrCode.getDeviceSn()); + + qrcodeDataList.add(qrcodeData); + tourismOrderCount += orderCount; + } + + Map tourismData = new java.util.HashMap<>(); + tourismData.put("tourismId", tourism.getId()); + tourismData.put("tourismName", tourism.getTourismName()); + tourismData.put("tourismAddress", tourism.getTourismAddress()); + tourismData.put("orderCount", tourismOrderCount); + tourismData.put("qrcodeCount", qrCodeList.size()); + tourismData.put("qrcodeList", qrcodeDataList); + + tourismDataList.add(tourismData); + } + + // 6. 组装返回结果 + Map result = new java.util.HashMap<>(); + result.put("tourismList", tourismDataList); + result.put("totalTourismCount", totalTourismCount); + result.put("totalQrcodeCount", totalQrcodeCount); + result.put("totalOrderCount", totalOrderCount); + result.put("todayOrderCount", todayOrderCount); + result.put("payTimeStart", payTimeStart); + result.put("payTimeEnd", payTimeEnd); + result.put("page", page); + result.put("limit", limit); + result.put("hasMore", tourismPage.getCurrent() < tourismPage.getPages()); // 是否还有更多数据 + + return result; + } + } diff --git a/zlt-business/order-center/src/main/resources/mapper/MissionMapper.xml b/zlt-business/order-center/src/main/resources/mapper/MissionMapper.xml index e2a28d16..5fa5bca6 100644 --- a/zlt-business/order-center/src/main/resources/mapper/MissionMapper.xml +++ b/zlt-business/order-center/src/main/resources/mapper/MissionMapper.xml @@ -11,6 +11,8 @@ + + @@ -34,7 +36,8 @@ m.id, m.mission_code, m.mission_name, m.mission_type, m.device_sn, - m.wayline_id, m.wayline_name, m.workspace_id, m.tourism_id, m.mission_status, + m.wayline_id, m.wayline_name, m.boat_route_id, m.boat_route_name, + m.workspace_id, m.tourism_id, m.mission_status, m.target_latitude, m.target_longitude, m.target_height, m.start_time, m.end_time, m.creator_id, m.creator_name, m.remark, m.tenant_id, m.is_del, m.create_time, m.update_time diff --git a/zlt-business/order-center/src/main/resources/mapper/OrderMapper.xml b/zlt-business/order-center/src/main/resources/mapper/OrderMapper.xml index d85e9035..6479d329 100644 --- a/zlt-business/order-center/src/main/resources/mapper/OrderMapper.xml +++ b/zlt-business/order-center/src/main/resources/mapper/OrderMapper.xml @@ -38,12 +38,12 @@ AND o.mobile LIKE CONCAT('%', #{p.mobile}, '%') - + - AND o.create_time >= #{p.startTime} + AND o.pay_time >= #{p.startTime} - AND o.create_time <= #{p.endTime} + AND o.pay_time <= #{p.endTime} diff --git a/zlt-business/pom.xml b/zlt-business/pom.xml index 08ac214e..06ea010c 100644 --- a/zlt-business/pom.xml +++ b/zlt-business/pom.xml @@ -20,8 +20,6 @@ device-center order-center - - device-ops-center coupon-center diff --git a/zlt-web/react-web-next/config/routes.ts b/zlt-web/react-web-next/config/routes.ts index 665f1b5c..f9f445eb 100644 --- a/zlt-web/react-web-next/config/routes.ts +++ b/zlt-web/react-web-next/config/routes.ts @@ -34,6 +34,8 @@ export default [ { path: '/orders/coupon.html', component: '@/pages/orders/Coupon' }, // 导游管理模块(包含导游列表、佣金明细、提现审核) { path: '/orders/guide.html', component: '@/pages/orders/Guide' }, + // 二维码订单管理 + { path: '/orders/qrcodeOrder.html', component: '@/pages/orders/QrcodeOrder' }, ], }, { diff --git a/zlt-web/react-web-next/dist.zip b/zlt-web/react-web-next/dist.zip index c8f67843..a2b41bd0 100644 Binary files a/zlt-web/react-web-next/dist.zip and b/zlt-web/react-web-next/dist.zip differ diff --git a/zlt-web/react-web-next/src/pages/device/Device/components/DeviceForm.tsx b/zlt-web/react-web-next/src/pages/device/Device/components/DeviceForm.tsx index 8f12b7ce..d5e99fd3 100644 --- a/zlt-web/react-web-next/src/pages/device/Device/components/DeviceForm.tsx +++ b/zlt-web/react-web-next/src/pages/device/Device/components/DeviceForm.tsx @@ -30,6 +30,7 @@ const DEVICE_TYPE_OPTIONS = [ { label: '机场', value: 1 }, { label: '无人机', value: 2 }, { label: '遥控器', value: 3 }, + { label: 'boat', value: 4 }, ]; const DeviceForm: React.FC = ({ title, visible, onVisibleChange, onFinish, initialValues }) => { diff --git a/zlt-web/react-web-next/src/pages/device/Device/components/DeviceTable.tsx b/zlt-web/react-web-next/src/pages/device/Device/components/DeviceTable.tsx index 17c747fc..e167d7b0 100644 --- a/zlt-web/react-web-next/src/pages/device/Device/components/DeviceTable.tsx +++ b/zlt-web/react-web-next/src/pages/device/Device/components/DeviceTable.tsx @@ -31,6 +31,7 @@ const DeviceTable = forwardRef(({ params, onEd 1: '机场', 2: '无人机', 3: '遥控器', + 4: 'boat', }; const columns: ProColumns[] = [ diff --git a/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/components/OrderListDrawer.tsx b/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/components/OrderListDrawer.tsx new file mode 100644 index 00000000..cea900f7 --- /dev/null +++ b/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/components/OrderListDrawer.tsx @@ -0,0 +1,166 @@ +import React, { useRef } from 'react'; +import { Drawer, Tag } from 'antd'; +import { ProTable, type ActionType } from '@ant-design/pro-components'; +import { ordersApi, type OrderItem } from '@/services/orders'; + +interface QrcodeData { + id: number; + qrcodeId: string; + qrcodeName: string; + qrcodeCode: string; + orderCount: number; + todayOrderCount: number; + viewUrl: string; + status: number; + price: string; + deviceSn: string; +} + +interface OrderListDrawerProps { + open: boolean; + onClose: () => void; + qrcode: QrcodeData | null; + queryParams?: Record; +} + +const OrderListDrawer: React.FC = ({ open, onClose, qrcode, queryParams }) => { + const actionRef = useRef(); + + const columns: any[] = [ + { dataIndex: 'index', valueType: 'indexBorder', width: 48, fixed: 'left' }, + { + title: '订单号', + dataIndex: 'orderNo', + width: 180, + fixed: 'left', + ellipsis: true, + }, + { + title: '用户手机', + dataIndex: 'userPhone', + width: 120, + render: (phone: string) => phone || '-', + }, + { + title: '金额', + dataIndex: 'orderAmount', + width: 100, + render: (amount: string | number) => { + if (!amount && amount !== 0) return '-'; + const amountNum = typeof amount === 'string' ? parseFloat(amount) : amount; + if (Number.isNaN(amountNum)) return '-'; + return `¥${(amountNum / 100).toFixed(2)}`; + }, + }, + { + title: '支付方式', + dataIndex: 'payType', + width: 100, + render: (type: number) => { + const typeMap: Record = { + 1: { text: '微信支付', color: 'green' }, + 2: { text: '优惠券', color: 'blue' }, + 3: { text: '第三方', color: 'orange' }, + }; + const info = typeMap[type] || { text: '未知', color: 'default' }; + return {info.text}; + }, + }, + { + title: '订单状态', + dataIndex: 'orderStatus', + width: 120, + render: (status: number) => { + const statusMap: Record = { + 0: { text: '未支付', color: 'default' }, + 1: { text: '已支付', color: 'blue' }, + 2: { text: '已取消', color: 'red' }, + 3: { text: '任务完成', color: 'success' }, + 4: { text: '执行中', color: 'processing' }, + 5: { text: '素材上传中', color: 'cyan' }, + 6: { text: '素材上传完成', color: 'success' }, + 7: { text: '退款中', color: 'orange' }, + 8: { text: '已退款', color: 'orange' }, + 9: { text: '退款失败', color: 'red' }, + 10: { text: '部分退款', color: 'orange' }, + }; + const info = statusMap[status] || { text: '未知', color: 'default' }; + return {info.text}; + }, + }, + { + title: '支付时间', + dataIndex: 'payTime', + width: 160, + valueType: 'dateTime', + render: (time: string) => time || '-', + }, + { + title: '创建时间', + dataIndex: 'createTime', + width: 160, + valueType: 'dateTime', + }, + ]; + + return ( + + {qrcode && ( + <> +
+
+ 二维码名称: + {qrcode.qrcodeName || '未命名'} +
+
+ 二维码Code: + + {qrcode.qrcodeCode} + +
+
+ 订单总数: + {qrcode.orderCount} +
+
+ 今日订单: + + {qrcode.todayOrderCount} + +
+
+ + + rowKey="id" + actionRef={actionRef} + request={(p) => ordersApi.ordersByCodeId({ + ...(p as any), + codeId: qrcode.qrcodeId, + payTimeStart: queryParams?.payTimeStart, + payTimeEnd: queryParams?.payTimeEnd, + })} + columns={columns} + search={false} + pagination={{ + showSizeChanger: true, + showQuickJumper: true, + defaultPageSize: 10, + }} + toolBarRender={false} + scroll={{ x: 1200 }} + /> + + )} +
+ ); +}; + +export default OrderListDrawer; diff --git a/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/components/TourismSection.tsx b/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/components/TourismSection.tsx new file mode 100644 index 00000000..1c5b5dd0 --- /dev/null +++ b/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/components/TourismSection.tsx @@ -0,0 +1,110 @@ +import React from 'react'; +import { Card, Row, Col, Tag } from 'antd'; +import { ShoppingOutlined, QrcodeOutlined } from '@ant-design/icons'; + +interface QrcodeData { + id: number; + qrcodeId: string; + qrcodeName: string; + qrcodeCode: string; + orderCount: number; + todayOrderCount: number; + viewUrl: string; + status: number; + price: string; + deviceSn: string; +} + +interface TourismData { + tourismId: number; + tourismName: string; + tourismAddress: string; + orderCount: number; + qrcodeCount: number; + qrcodeList: QrcodeData[]; +} + +interface TourismSectionProps { + tourism: TourismData; + onQrcodeClick: (qrcode: QrcodeData) => void; +} + +const TourismSection: React.FC = ({ tourism, onQrcodeClick }) => { + return ( +
+
+

+ {tourism.tourismName} + {tourism.tourismAddress && ( + + {tourism.tourismAddress} + + )} +

+
+
+ + 二维码: + {tourism.qrcodeCount} +
+
+ + 订单总数: + {tourism.orderCount} +
+
+
+ +
+ + {tourism.qrcodeList.map((qrcode) => ( + + onQrcodeClick(qrcode)} + hoverable + bodyStyle={{ padding: 0 }} + > +
+ {qrcode.qrcodeName} +
+ {qrcode.status === 0 ? '启用' : '禁用'} +
+
+ +
+
+ {qrcode.qrcodeName || '未命名'} +
+ +
+
+
{qrcode.orderCount}
+
总订单
+
+
+
+ {qrcode.todayOrderCount} +
+
今日
+
+
+ +
+ Code: {qrcode.qrcodeCode} +
+
+
+ + ))} +
+
+
+ ); +}; + +export default TourismSection; diff --git a/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/index.less b/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/index.less new file mode 100644 index 00000000..006d61e2 --- /dev/null +++ b/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/index.less @@ -0,0 +1,247 @@ +.qrcode-order-page { + .stat-card { + border-radius: 12px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); + transition: all 0.3s ease; + border: none; + background: linear-gradient(135deg, #ffffff 0%, #f5f5f5 100%); + + &:hover { + transform: translateY(-4px); + box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12); + } + + &.stat-card-blue { + background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%); + } + + &.stat-card-purple { + background: linear-gradient(135deg, #f9f0ff 0%, #efdbff 100%); + } + + &.stat-card-green { + background: linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%); + } + + &.stat-card-orange { + background: linear-gradient(135deg, #fff7e6 0%, #ffd591 100%); + } + + .ant-statistic-title { + font-size: 14px; + font-weight: 500; + color: rgba(0, 0, 0, 0.65); + } + + .ant-statistic-content { + font-size: 28px; + font-weight: 600; + font-family: 'Roboto Mono', monospace; + } + } +} + +.tourism-section { + margin-bottom: 24px; + + .tourism-header { + display: flex; + justify-content: space-between; + align-items: center; + padding: 16px 24px; + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + border-radius: 12px 12px 0 0; + color: white; + + .tourism-title { + font-size: 18px; + font-weight: 600; + margin: 0; + } + + .tourism-stats { + display: flex; + gap: 24px; + font-size: 14px; + + .stat-item { + display: flex; + align-items: center; + gap: 6px; + + .stat-label { + opacity: 0.9; + } + + .stat-value { + font-weight: 600; + font-size: 16px; + } + } + } + } + + .qrcode-grid { + padding: 24px; + background: white; + border-radius: 0 0 12px 12px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); + } +} + +.qrcode-card { + border-radius: 12px; + overflow: hidden; + transition: all 0.3s ease; + cursor: pointer; + border: 2px solid transparent; + background: white; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); + + &:hover { + transform: translateY(-8px) scale(1.02); + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15); + border-color: #1890ff; + } + + .qrcode-image-wrapper { + position: relative; + padding: 16px; + background: linear-gradient(135deg, #f5f5f5 0%, #e8e8e8 100%); + display: flex; + justify-content: center; + align-items: center; + height: 180px; + + .qrcode-image { + width: 140px; + height: 140px; + object-fit: contain; + border-radius: 8px; + background: white; + padding: 8px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); + } + + .status-badge { + position: absolute; + top: 12px; + right: 12px; + padding: 4px 12px; + border-radius: 12px; + font-size: 12px; + font-weight: 500; + background: rgba(255, 255, 255, 0.9); + backdrop-filter: blur(4px); + + &.status-active { + color: #52c41a; + border: 1px solid #52c41a; + } + + &.status-inactive { + color: #ff4d4f; + border: 1px solid #ff4d4f; + } + } + } + + .qrcode-info { + padding: 16px; + + .qrcode-name { + font-size: 16px; + font-weight: 600; + color: #262626; + margin-bottom: 12px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .qrcode-stats { + display: flex; + justify-content: space-between; + margin-bottom: 12px; + + .stat-item { + text-align: center; + + .stat-value { + font-size: 20px; + font-weight: 600; + color: #1890ff; + font-family: 'Roboto Mono', monospace; + } + + .stat-label { + font-size: 12px; + color: #8c8c8c; + margin-top: 4px; + } + } + } + + .qrcode-code { + font-size: 12px; + color: #8c8c8c; + padding: 8px; + background: #f5f5f5; + border-radius: 6px; + font-family: 'Courier New', monospace; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + } +} + +.order-list-drawer { + .ant-drawer-header { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + border-bottom: none; + + .ant-drawer-title { + color: white; + font-size: 18px; + font-weight: 600; + } + + .ant-drawer-close { + color: white; + + &:hover { + color: rgba(255, 255, 255, 0.8); + } + } + } + + .drawer-summary { + padding: 16px; + background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%); + border-radius: 8px; + margin-bottom: 16px; + + .summary-item { + display: flex; + justify-content: space-between; + margin-bottom: 8px; + + &:last-child { + margin-bottom: 0; + } + + .label { + color: #595959; + font-size: 14px; + } + + .value { + font-weight: 600; + font-size: 16px; + color: #1890ff; + font-family: 'Roboto Mono', monospace; + } + } + } +} diff --git a/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/index.tsx b/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/index.tsx new file mode 100644 index 00000000..d879f86b --- /dev/null +++ b/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/index.tsx @@ -0,0 +1,285 @@ +import React, { useEffect, useState } from 'react'; +import { PageContainer } from '@ant-design/pro-components'; +import { Card, Row, Col, Statistic, Empty, Spin, Drawer, message } from 'antd'; +import { QrcodeOutlined, ShopOutlined, ShoppingOutlined, ClockCircleOutlined } from '@ant-design/icons'; +import { ordersApi } from '@/services/orders'; +import { tenantApi } from '@/services/tenant'; +import { SearchBarPlus, GradientButton } from '@/components/ui'; +import { ProFormText, ProFormDateRangePicker } from '@ant-design/pro-components'; +import TourismSection from './components/TourismSection'; +import OrderListDrawer from './components/OrderListDrawer'; +import './index.less'; +import moment from 'moment'; + +interface QrcodeData { + id: number; + qrcodeId: string; + qrcodeName: string; + qrcodeCode: string; + orderCount: number; + todayOrderCount: number; + viewUrl: string; + status: number; + price: string; + deviceSn: string; +} + +interface TourismData { + tourismId: number; + tourismName: string; + tourismAddress: string; + orderCount: number; + qrcodeCount: number; + qrcodeList: QrcodeData[]; +} + +interface StatisticsData { + tourismList: TourismData[]; + totalTourismCount: number; + totalQrcodeCount: number; + totalOrderCount: number; + todayOrderCount: number; +} + +const QrcodeOrderPage: React.FC = () => { + const [loading, setLoading] = useState(false); + const [loadingMore, setLoadingMore] = useState(false); + const [statistics, setStatistics] = useState(null); + const [params, setParams] = useState>({}); + const [drawerOpen, setDrawerOpen] = useState(false); + const [selectedQrcode, setSelectedQrcode] = useState(null); + const [page, setPage] = useState(1); + const [hasMore, setHasMore] = useState(false); + + // 首次进入时,默认按"当前租户 + 包含下级租户 + 当天支付时间"查询 + useEffect(() => { + (async () => { + try { + let tenantId: string | undefined; + const cur: any = await tenantApi.getCurrentTenant(); + tenantId = cur?.data?.tenantId ?? cur?.tenantId; + if (!tenantId) { + const stats: any = await tenantApi.getScopeStats(); + tenantId = stats?.data?.currentTenantId ?? stats?.currentTenantId; + } + if (tenantId) { + // 默认查询当天 + const initialParams = { + tenantId, + includeChildren: true, + payTimeStart: moment().startOf('day').valueOf(), // 传时间戳 + payTimeEnd: moment().endOf('day').valueOf(), // 传时间戳 + }; + setParams(initialParams); + setPage(1); + fetchStatistics(initialParams, 1, false); + } + } catch { + // 忽略错误,保留手动查询能力 + } + })(); + }, []); + + const fetchStatistics = async (queryParams: Record, currentPage: number, isLoadMore: boolean) => { + if (isLoadMore) { + setLoadingMore(true); + } else { + setLoading(true); + } + + try { + const res = await ordersApi.qrcodeOrderStatistics({ ...queryParams, page: currentPage, limit: 10 }); + console.log('二维码订单统计返回数据:', res); + + // 确保返回的数据结构正确 + const safeRes = { + ...res, + tourismList: res?.tourismList || [], + totalTourismCount: res?.totalTourismCount || 0, + totalQrcodeCount: res?.totalQrcodeCount || 0, + totalOrderCount: res?.totalOrderCount || 0, + todayOrderCount: res?.todayOrderCount || 0, + hasMore: res?.hasMore || false, + }; + + if (isLoadMore) { + // 加载更多:追加数据 + setStatistics((prev) => { + if (!prev) return safeRes; + return { + ...safeRes, + tourismList: [...(prev.tourismList || []), ...(safeRes.tourismList || [])], + }; + }); + } else { + // 首次查询或重新查询:替换数据 + setStatistics(safeRes); + } + + setHasMore(safeRes.hasMore); + setPage(currentPage); + } catch (error) { + console.error('二维码订单统计查询失败:', error); + message.error('查询失败'); + // 出错时设置空数据 + setStatistics({ + tourismList: [], + totalTourismCount: 0, + totalQrcodeCount: 0, + totalOrderCount: 0, + todayOrderCount: 0, + }); + } finally { + if (isLoadMore) { + setLoadingMore(false); + } else { + setLoading(false); + } + } + }; + + const handleQrcodeClick = (qrcode: QrcodeData) => { + setSelectedQrcode(qrcode); + setDrawerOpen(true); + }; + + const handleLoadMore = () => { + const nextPage = page + 1; + fetchStatistics(params, nextPage, true); + }; + + return ( + + {/* 顶部筛选栏 */} + { + const newParams = { ...(params || {}), tenantId, includeChildren }; + setParams(newParams); + setPage(1); + fetchStatistics(newParams, 1, false); + }} + onFinish={async (values) => { + // 处理支付时间范围 - 保留用户选择的具体时间点 + let processedValues = { ...values }; + if (values.payTimeRange && values.payTimeRange.length === 2) { + processedValues.payTimeStart = moment(values.payTimeRange[0]).valueOf(); + processedValues.payTimeEnd = moment(values.payTimeRange[1]).valueOf(); + delete processedValues.payTimeRange; + } + const newParams = { ...(params || {}), ...processedValues }; + setParams(newParams); + setPage(1); + fetchStatistics(newParams, 1, false); + }} + > + + + + + + {/* 统计概览卡片 */} + {statistics && ( + + + + } + valueStyle={{ color: '#1890ff' }} + /> + + + + + } + valueStyle={{ color: '#722ed1' }} + /> + + + + + } + valueStyle={{ color: '#52c41a' }} + /> + + + + + } + valueStyle={{ color: '#fa8c16' }} + /> + + + + )} + + {/* 景区二维码卡片网格 */} + + {statistics && statistics.tourismList.length > 0 ? ( + <> + {statistics.tourismList.map((tourism) => ( + + ))} + {/* 加载更多按钮 */} + {hasMore && ( +
+ + {loadingMore ? '加载中...' : '加载更多'} + +
+ )} + + ) : ( + + + + )} +
+ + {/* 订单列表抽屉 */} + setDrawerOpen(false)} + qrcode={selectedQrcode} + queryParams={params} + /> +
+ ); +}; + +export default QrcodeOrderPage; diff --git a/zlt-web/react-web-next/src/services/orders.ts b/zlt-web/react-web-next/src/services/orders.ts index a978e6a0..486294de 100644 --- a/zlt-web/react-web-next/src/services/orders.ts +++ b/zlt-web/react-web-next/src/services/orders.ts @@ -456,4 +456,17 @@ export const ordersApi = { throw error; } }, + + // 二维码订单统计查询 + qrcodeOrderStatistics: async (params?: { tenantId?: string; includeChildren?: boolean; qrcodeName?: string; codeId?: string; tourismId?: number; page?: number; limit?: number; payTimeStart?: number; payTimeEnd?: number }) => { + const res = await request('/api-order/qrcode/order/statistics', { method: 'GET', params }); + return (res as any).data || res; + }, + + // 根据二维码ID查询订单列表 + ordersByCodeId: async (params: { current?: number; pageSize?: number; codeId: string; [k: string]: any }) => { + const { current, pageSize, codeId, ...rest } = params || {}; + const res = await request(`/api-order/qrcode/${codeId}/orders`, { method: 'GET', params: { page: current, limit: pageSize, ...rest } }); + return { data: (res as any).data, total: (res as any).count } as { data: OrderItem[]; total: number }; + }, }; diff --git a/zlt-web/yingyan/dist.zip b/zlt-web/yingyan/dist.zip new file mode 100644 index 00000000..31458609 Binary files /dev/null and b/zlt-web/yingyan/dist.zip differ diff --git a/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/BoundaryPreview.tsx b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/BoundaryPreview.tsx new file mode 100644 index 00000000..cd8be404 --- /dev/null +++ b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/BoundaryPreview.tsx @@ -0,0 +1,151 @@ +/** + * 边界预览面板组件 + * 显示边界的统计信息 + * @author dzc + * @date 2026-01-06 + */ +import React, { useMemo } from 'react'; +import { Card, Descriptions, Tag } from 'antd'; +import type { BoundaryPreviewProps, BoundaryType } from './types'; + +/** + * 计算多边形面积(使用Shoelace公式) + * @param vertices 顶点数组 + * @returns 面积(平方米) + */ +function calculatePolygonArea(vertices: { longitude: number; latitude: number }[]): number { + if (vertices.length < 3) return 0; + + // 将经纬度转换为米(简化计算,适用于小范围区域) + const R = 6371000; // 地球半径(米) + const toRadians = (deg: number) => deg * Math.PI / 180; + + // 计算中心点 + const centerLat = vertices.reduce((sum, v) => sum + v.latitude, 0) / vertices.length; + const centerLon = vertices.reduce((sum, v) => sum + v.longitude, 0) / vertices.length; + + // 转换为平面坐标(局部投影) + const points = vertices.map(v => ({ + x: R * toRadians(v.longitude - centerLon) * Math.cos(toRadians(centerLat)), + y: R * toRadians(v.latitude - centerLat), + })); + + // Shoelace公式计算面积 + let area = 0; + for (let i = 0; i < points.length; i++) { + const j = (i + 1) % points.length; + area += points[i].x * points[j].y; + area -= points[j].x * points[i].y; + } + area = Math.abs(area) / 2; + + return area; +} + +/** + * 获取边界类型显示信息 + */ +function getBoundaryTypeInfo(type: BoundaryType): { label: string; color: string } { + switch (type) { + case 'navigable': + return { label: '可航行区域', color: 'green' }; + case 'obstacle': + return { label: '障碍物', color: 'orange' }; + case 'restricted': + return { label: '禁行区', color: 'red' }; + default: + return { label: '未知', color: 'default' }; + } +} + +const BoundaryPreview: React.FC = ({ + vertices, + boundaryType, + area: providedArea, +}) => { + // 计算面积 + const calculatedArea = useMemo(() => { + return providedArea ?? calculatePolygonArea(vertices); + }, [vertices, providedArea]); + + // 格式化面积显示 + const areaText = useMemo(() => { + if (calculatedArea === 0) return '-'; + if (calculatedArea < 1000) { + return `${calculatedArea.toFixed(2)} m²`; + } else if (calculatedArea < 1000000) { + return `${(calculatedArea / 1000).toFixed(2)} 千m²`; + } else { + return `${(calculatedArea / 1000000).toFixed(2)} km²`; + } + }, [calculatedArea]); + + const typeInfo = getBoundaryTypeInfo(boundaryType); + + return ( + + + + {typeInfo.label} + + + {vertices.length} + + + {areaText} + + + + {vertices.length > 0 && vertices.length < 3 && ( +
+ 提示:至少需要3个顶点才能形成边界 +
+ )} + + {vertices.length >= 3 && ( +
+ 边界已形成,可以保存 +
+ )} +
+ ); +}; + +export default BoundaryPreview; diff --git a/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/BoundaryToolbar.tsx b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/BoundaryToolbar.tsx new file mode 100644 index 00000000..eee1b098 --- /dev/null +++ b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/BoundaryToolbar.tsx @@ -0,0 +1,187 @@ +/** + * 边界编辑器工具栏组件 + * @author dzc + * @date 2026-01-06 + */ +import React from 'react'; +import { Button, Space, Tooltip } from 'antd'; +import { + PlusOutlined, + CheckOutlined, + EditOutlined, + EyeOutlined, + DeleteOutlined, + UndoOutlined, + SaveOutlined, + CloseOutlined, +} from '@ant-design/icons'; +import type { BoundaryToolbarProps } from './types'; + +const BoundaryToolbar: React.FC = ({ + mode, + hasVertices, + hasUnsavedChanges, + isDrawing, + canUndo, + onModeChange, + onStartDraw, + onFinishDraw, + onUndo, + onClear, + onSave, + onCancel, +}) => { + return ( +
+ + {/* 绘制按钮 */} + {!isDrawing && ( + + + + )} + + {/* 完成绘制按钮 */} + {isDrawing && ( + + + + )} + + {/* 模式切换按钮 */} + {hasVertices && !isDrawing && ( + <> + + + + + + + + + )} + + {/* 清空按钮 */} + {hasVertices && ( + + + + )} + + {/* 撤销按钮 */} + {onUndo && ( + + + + )} + + {/* 分隔线 */} + {hasVertices && ( +
+ )} + + {/* 保存按钮 */} + {hasVertices && !isDrawing && ( + + + + )} + + {/* 取消按钮 */} + + + + + + {/* 当前状态提示 */} +
+ {isDrawing && '点击地图添加顶点,完成后点击"完成绘制"'} + {!isDrawing && mode === 'view' && hasVertices && '查看模式 - 切换到编辑模式可调整顶点'} + {!isDrawing && mode === 'edit' && hasVertices && '编辑模式 - 拖动顶点调整边界'} + {!isDrawing && !hasVertices && '点击"开始绘制"标绘水域边界'} +
+
+ ); +}; + +export default BoundaryToolbar; diff --git a/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/hooks/useBoundaryDrawing.ts b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/hooks/useBoundaryDrawing.ts new file mode 100644 index 00000000..5a91e409 --- /dev/null +++ b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/hooks/useBoundaryDrawing.ts @@ -0,0 +1,267 @@ +/** + * 边界绘制状态管理Hook + * 负责管理边界绘制的所有状态和操作逻辑 + * @author Claude + * @date 2026-01-06 + */ +import { useState, useCallback, useRef } from 'react'; +import { message } from 'antd'; +import type { BoundaryVertex, EditorMode, EditorState } from '../types'; + +interface UseBoundaryDrawingOptions { + /** 初始顶点 */ + initialVertices?: BoundaryVertex[]; +} + +interface UseBoundaryDrawingReturn { + /** 所有顶点 */ + vertices: BoundaryVertex[]; + /** 编辑器状态 */ + editorState: EditorState; + /** 是否正在绘制 */ + isDrawing: boolean; + /** 设置编辑模式 */ + setMode: (mode: EditorMode) => void; + /** 开始绘制 */ + startDrawing: () => void; + /** 结束绘制 */ + finishDrawing: () => void; + /** 添加顶点 */ + addVertex: (point: { longitude: number; latitude: number; height?: number }) => void; + /** 更新顶点 */ + updateVertex: (index: number, point: { longitude: number; latitude: number; height?: number }) => void; + /** 删除顶点 */ + deleteVertex: (index: number) => void; + /** 移动顶点 */ + moveVertex: (index: number, point: { longitude: number; latitude: number; height?: number }) => void; + /** 选择顶点 */ + selectVertex: (index: number | null) => void; + /** 清空所有顶点 */ + clearVertices: () => void; + /** 设置顶点列表 */ + setVertices: (vertices: BoundaryVertex[]) => void; + /** 标记已保存 */ + markSaved: () => void; + /** 撤销上一步操作 */ + undo: () => void; + /** 是否可以撤销 */ + canUndo: boolean; +} + +/** + * 边界绘制Hook + * + * 功能: + * 1. 管理顶点数组 + * 2. 管理编辑器模式(view/draw/edit) + * 3. 提供顶点增删改操作 + * 4. 历史记录管理(撤销功能) + * 5. 未保存变更追踪 + */ +export function useBoundaryDrawing(options: UseBoundaryDrawingOptions = {}): UseBoundaryDrawingReturn { + const { initialVertices = [] } = options; + + // 顶点列表 + const [vertices, setVerticesState] = useState(initialVertices); + + // 编辑器状态 + const [editorState, setEditorState] = useState({ + mode: 'view', + selectedVertexIndex: null, + hasUnsavedChanges: false, + }); + + // 是否正在绘制 + const [isDrawing, setIsDrawing] = useState(false); + + // 历史记录栈(用于撤销) + const historyRef = useRef([]); + const maxHistorySize = 50; + + /** + * 保存历史记录 + */ + const saveHistory = useCallback(() => { + historyRef.current.push([...vertices]); + if (historyRef.current.length > maxHistorySize) { + historyRef.current.shift(); + } + }, [vertices]); + + /** + * 更新顶点并标记未保存 + */ + const updateVertices = useCallback((newVertices: BoundaryVertex[]) => { + saveHistory(); + setVerticesState(newVertices); + setEditorState(prev => ({ ...prev, hasUnsavedChanges: true })); + }, [saveHistory]); + + /** + * 设置编辑模式 + */ + const setMode = useCallback((mode: EditorMode) => { + setEditorState(prev => ({ ...prev, mode })); + }, []); + + /** + * 开始绘制 + */ + const startDrawing = useCallback(() => { + console.log('[BoundaryDrawing] 开始绘制模式'); + setIsDrawing(true); + setMode('draw'); + setVerticesState([]); + setEditorState(prev => ({ + ...prev, + mode: 'draw', + selectedVertexIndex: null, + hasUnsavedChanges: false, + })); + historyRef.current = []; + console.log('[BoundaryDrawing] 绘制模式已激活,mode=draw'); + }, [setMode]); + + /** + * 结束绘制 + */ + const finishDrawing = useCallback(() => { + if (vertices.length < 3) { + message.warning('至少需要3个顶点才能形成边界'); + return; + } + setIsDrawing(false); + setMode('view'); + setEditorState(prev => ({ ...prev, hasUnsavedChanges: true })); + message.success(`边界绘制完成,共${vertices.length}个顶点`); + }, [vertices.length, setMode]); + + /** + * 添加顶点 + */ + const addVertex = useCallback((point: { longitude: number; latitude: number }) => { + const newVertex: BoundaryVertex = { + longitude: point.longitude, + latitude: point.latitude, + height: point.height, + }; + updateVertices([...vertices, newVertex]); + }, [vertices, updateVertices]); + + /** + * 更新顶点 + */ + const updateVertex = useCallback((index: number, point: { longitude: number; latitude: number; height?: number }) => { + if (index < 0 || index >= vertices.length) { + console.warn(`Invalid vertex index: ${index}`); + return; + } + const newVertices = [...vertices]; + newVertices[index] = { + longitude: point.longitude, + latitude: point.latitude, + height: point.height, + }; + updateVertices(newVertices); + }, [vertices, updateVertices]); + + /** + * 删除顶点 + */ + const deleteVertex = useCallback((index: number) => { + if (index < 0 || index >= vertices.length) { + console.warn(`Invalid vertex index: ${index}`); + return; + } + if (vertices.length <= 3) { + message.warning('边界至少需要3个顶点'); + return; + } + const newVertices = vertices.filter((_, i) => i !== index); + updateVertices(newVertices); + setEditorState(prev => ({ ...prev, selectedVertexIndex: null })); + }, [vertices, updateVertices]); + + /** + * 移动顶点(别名) + */ + const moveVertex = useCallback((index: number, point: { longitude: number; latitude: number }) => { + updateVertex(index, point); + }, [updateVertex]); + + /** + * 选择顶点 + */ + const selectVertex = useCallback((index: number | null) => { + setEditorState(prev => ({ ...prev, selectedVertexIndex: index })); + }, []); + + /** + * 清空所有顶点 + */ + const clearVertices = useCallback(() => { + if (vertices.length === 0) return; + + saveHistory(); + setVerticesState([]); + setIsDrawing(false); + setEditorState({ + mode: 'view', + selectedVertexIndex: null, + hasUnsavedChanges: false, + }); + historyRef.current = []; + }, [vertices.length, saveHistory]); + + /** + * 设置顶点列表(加载已有边界) + */ + const setVertices = useCallback((newVertices: BoundaryVertex[]) => { + setVerticesState(newVertices); + historyRef.current = []; + setEditorState(prev => ({ ...prev, hasUnsavedChanges: false })); + }, []); + + /** + * 标记已保存 + */ + const markSaved = useCallback(() => { + setEditorState(prev => ({ ...prev, hasUnsavedChanges: false })); + }, []); + + /** + * 撤销上一步操作 + */ + const undo = useCallback(() => { + if (historyRef.current.length === 0) { + message.info('没有可撤销的操作'); + return; + } + const lastState = historyRef.current.pop(); + if (lastState) { + setVerticesState(lastState); + setEditorState(prev => ({ ...prev, hasUnsavedChanges: true })); + } + }, []); + + const canUndo = historyRef.current.length > 0; + + return { + vertices, + editorState, + isDrawing, + setMode, + startDrawing, + finishDrawing, + addVertex, + updateVertex, + deleteVertex, + moveVertex, + selectVertex, + clearVertices, + setVertices, + markSaved, + undo, + canUndo, + }; +} diff --git a/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/hooks/useCesiumBoundaryRenderer.ts b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/hooks/useCesiumBoundaryRenderer.ts new file mode 100644 index 00000000..191fadce --- /dev/null +++ b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/hooks/useCesiumBoundaryRenderer.ts @@ -0,0 +1,629 @@ +/** + * Cesium边界渲染Hook + * 负责在Cesium地图上渲染和管理水域边界的可视化 + * @author Claude + * @date 2026-01-06 + */ +import { useEffect, useRef, useCallback } from 'react'; +import type { BoundaryVertex, BoundaryType, EditorMode } from '../types'; + +interface UseCesiumBoundaryRendererOptions { + viewerRef: React.RefObject; + vertices: BoundaryVertex[]; + selectedIndex: number | null; + mode: EditorMode; + boundaryType: BoundaryType; + onVertexAdd: (point: { longitude: number; latitude: number; height?: number }) => void; + onVertexMove: (index: number, point: { longitude: number; latitude: number; height?: number }) => void; + onVertexSelect: (index: number) => void; +} + +/** + * 获取边界类型对应的颜色 + */ +function getBoundaryColor(type: BoundaryType, Cesium: any) { + switch (type) { + case 'navigable': // 可航行 - 绿色 + return Cesium.Color.fromCssColorString('#00ff00'); + case 'restricted': // 禁行 - 红色 + return Cesium.Color.fromCssColorString('#ff0000'); + case 'obstacle': // 障碍物 - 黄色 + return Cesium.Color.fromCssColorString('#ffff00'); + default: + return Cesium.Color.fromCssColorString('#00ff00'); + } +} + +/** + * 获取边界类型对应的透明度 + */ +function getBoundaryAlpha(type: BoundaryType): number { + switch (type) { + case 'navigable': + return 0.2; + case 'restricted': + return 0.3; + case 'obstacle': + return 0.2; + default: + return 0.2; + } +} + +/** + * Cesium边界渲染Hook + * + * 功能: + * 1. 渲染边界多边形(polygon) + * 2. 渲染顶点marker(可拖动) + * 3. 处理地图点击事件(添加顶点) + * 4. 处理顶点拖动交互 + * 5. 相机聚焦到边界 + * 6. 内存泄漏防范 + */ +export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOptions) { + const { + viewerRef, + vertices, + selectedIndex, + mode, + boundaryType, + onVertexAdd, + onVertexMove, + onVertexSelect, + } = options; + + // Entity ID集合,用于清理 + const entityIdsRef = useRef>(new Set()); + + // 事件处理器引用 + const handlerRef = useRef(null); + + // 拖动状态 + const draggingEntityRef = useRef(null); + const rafIdRef = useRef(null); + const previousSceneOptionsRef = useRef<{ + depthTestAgainstTerrain?: boolean; + pickTranslucentDepth?: boolean; + requestRenderMode?: boolean; + maximumRenderTimeChange?: number; + } | null>(null); + + /** + * 获取Cesium对象 + */ + const getCesium = useCallback(() => { + return (window as any).Cesium; + }, []); + + /** + * 安全触发一次渲染(requestRenderMode=true 时,实体变化不一定会立刻刷新) + */ + const requestRender = useCallback(() => { + const viewer = viewerRef.current; + if (!viewer || viewer.isDestroyed?.()) return; + try { + viewer.scene?.requestRender?.(); + } catch { + // 忽略 + } + }, [viewerRef]); + + /** + * 从屏幕坐标拾取地理位置:优先 pickPosition(支持 3D Tiles/模型),失败再回退 globe.pick / pickEllipsoid + */ + const pickCartesianFromScreen = useCallback((screenPosition: any) => { + const viewer = viewerRef.current; + const Cesium = getCesium(); + if (!viewer || !Cesium || viewer.isDestroyed?.() || !screenPosition) return null; + + // 1) 优先 pickPosition(依赖深度缓冲) + try { + if (viewer.scene?.pickPositionSupported) { + const cartesian = viewer.scene.pickPosition(screenPosition); + if (Cesium.defined(cartesian)) return cartesian; + } + } catch { + // pickPosition 可能在少数环境抛错,继续回退 + } + + // 2) 回退:globe.pick(地形/椭球) + try { + const ray = viewer.camera.getPickRay(screenPosition); + const cartesian = viewer.scene?.globe?.pick?.(ray, viewer.scene); + if (Cesium.defined(cartesian)) return cartesian; + } catch { + // 忽略 + } + + // 3) 最后回退:pickEllipsoid(即便没加载地形也能拿到) + try { + const cartesian = viewer.camera.pickEllipsoid(screenPosition, viewer.scene.globe.ellipsoid); + if (Cesium.defined(cartesian)) return cartesian; + } catch { + // 忽略 + } + + return null; + }, [viewerRef, getCesium]); + + /** + * 清理所有Entity + */ + const cleanup = useCallback(() => { + const viewer = viewerRef.current; + if (!viewer || viewer.isDestroyed?.()) return; + + entityIdsRef.current.forEach(id => { + try { + viewer.entities.removeById(id); + } catch (e) { + // 忽略删除失败 + } + }); + entityIdsRef.current.clear(); + requestRender(); + }, [viewerRef, requestRender]); + + /** + * 渲染边界多边形 + */ + const renderPolygon = useCallback(() => { + const viewer = viewerRef.current; + const Cesium = getCesium(); + if (!viewer || !Cesium || viewer.isDestroyed?.()) return; + if (vertices.length < 3) return; // 至少3个顶点才能形成多边形 + + // 注意:模型表面高度通常不共面,如果用 perPositionHeight 直接拉三角面,容易出现“面被模型遮挡/割裂”的视觉问题。 + // 这里改为使用 Classification(投影到 3D Tiles/地形),保证填充连续;顶点依然按 height 在模型表面显示。 + const positions = vertices.map(v => + Cesium.Cartesian3.fromDegrees(v.longitude, v.latitude, 0) + ); + + const baseColor = getBoundaryColor(boundaryType, Cesium); + const alpha = getBoundaryAlpha(boundaryType); + + const entityId = 'boundary-polygon'; + + try { + viewer.entities.add({ + id: entityId, + polygon: { + hierarchy: new Cesium.PolygonHierarchy(positions), + material: baseColor.withAlpha(alpha), + outline: true, + outlineColor: baseColor, + outlineWidth: 3, + classificationType: Cesium.ClassificationType.CESIUM_3D_TILE, + } + }); + + entityIdsRef.current.add(entityId); + } catch (e) { + console.error('添加边界多边形失败:', e); + } + + requestRender(); + }, [viewerRef, vertices, boundaryType, getCesium, requestRender]); + + /** + * 渲染顶点Marker + */ + const renderVertices = useCallback(() => { + const viewer = viewerRef.current; + const Cesium = getCesium(); + if (!viewer || !Cesium || viewer.isDestroyed?.()) return; + + vertices.forEach((v, index) => { + const isSelected = index === selectedIndex; + + const entityId = `boundary-vertex-${index}`; + + try { + const entity = viewer.entities.add({ + id: entityId, + position: Cesium.Cartesian3.fromDegrees(v.longitude, v.latitude, v.height ?? 0), + point: { + pixelSize: isSelected ? 16 : 12, + // 需求:点击的点用红色标记;选中点用黄色高亮 + color: isSelected ? Cesium.Color.YELLOW : Cesium.Color.RED, + outlineColor: Cesium.Color.BLACK, + outlineWidth: 2, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + label: { + text: `${index + 1}`, + font: isSelected ? '13px sans-serif' : '11px sans-serif', + fillColor: Cesium.Color.WHITE, + style: Cesium.LabelStyle.FILL_AND_OUTLINE, + outlineWidth: 2, + outlineColor: Cesium.Color.BLACK, + verticalOrigin: Cesium.VerticalOrigin.BOTTOM, + pixelOffset: new Cesium.Cartesian2(0, -15), + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + properties: { + type: 'boundary-vertex', + vertexIndex: index, + draggable: true, + } + }); + + entityIdsRef.current.add(entityId); + } catch (e) { + console.error('添加顶点entity失败:', e); + } + }); + + requestRender(); + }, [viewerRef, vertices, selectedIndex, getCesium, requestRender]); + + /** + * 设置事件处理器 + */ + const setupEventHandlers = useCallback(() => { + const viewer = viewerRef.current; + const Cesium = getCesium(); + + console.log('[BoundaryRenderer] setupEventHandlers 调试信息:', { + hasViewer: !!viewer, + hasCesium: !!Cesium, + viewerType: typeof viewer, + cesiumType: typeof Cesium, + isDestroyed: viewer?.isDestroyed?.(), + }); + + if (!viewer || !Cesium || viewer.isDestroyed?.()) { + console.error('[BoundaryRenderer] ❌ 初始化失败:', { + viewer: !!viewer, + Cesium: !!Cesium, + isDestroyed: viewer?.isDestroyed?.(), + }); + return; + } + + // 说明:Cesium 标准相机交互控制器是 screenSpaceCameraController + // 某些场景下该对象不可用,但不应阻断绘制(只影响“禁用旋转”等体验) + if (!viewer.scene?.screenSpaceCameraController) { + console.warn('[BoundaryRenderer] screenSpaceCameraController 不可用,将跳过相机交互锁定'); + } + + console.log('[BoundaryRenderer] ✓ 事件处理器初始化, mode=', mode); + + // 启用深度测试,确保可以正确拾取3D模型上的点 + try { + if (!previousSceneOptionsRef.current) { + previousSceneOptionsRef.current = { + depthTestAgainstTerrain: viewer.scene?.globe?.depthTestAgainstTerrain, + pickTranslucentDepth: viewer.scene?.pickTranslucentDepth, + requestRenderMode: viewer.scene?.requestRenderMode, + maximumRenderTimeChange: viewer.scene?.maximumRenderTimeChange, + }; + } + viewer.scene.globe.depthTestAgainstTerrain = true; + viewer.scene.pickTranslucentDepth = true; + + // 绘制/编辑时关闭 requestRenderMode,提升 pickPosition 稳定性(尤其是 3D Tiles 按需渲染场景) + viewer.scene.requestRenderMode = false; + viewer.scene.maximumRenderTimeChange = 0; + console.log('[BoundaryEditor] 已启用深度测试,支持在3D模型上绘制'); + } catch (e) { + console.warn('[BoundaryEditor] 启用深度测试失败:', e); + } + + // 清理旧的handler + if (handlerRef.current) { + try { + handlerRef.current.destroy(); + } catch (e) {} + handlerRef.current = null; + } + + const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas); + handlerRef.current = handler; + + // 根据模式设置不同的交互 + if (mode === 'draw') { + console.log('[BoundaryRenderer] ✓ 进入绘制模式,设置十字光标'); + // 绘制模式:点击地图添加顶点 + try { + if (viewer.scene?.screenSpaceCameraController) { + viewer.scene.screenSpaceCameraController.enableRotate = false; + } + } catch (e) { + console.warn('禁用旋转失败:', e); + } + + // 设置绘制模式光标 - 使用setProperty强制覆盖 + viewer.scene.canvas.style.setProperty('cursor', 'crosshair', 'important'); + console.log('[BoundaryRenderer] 光标已设置为 crosshair, 当前值=', viewer.scene.canvas.style.cursor); + + handler.setInputAction((movement: any) => { + // 统一拾取:优先 pickPosition(支持模型/3D Tiles),失败回退 globe.pick / pickEllipsoid + const cartesian = pickCartesianFromScreen(movement.position); + + if (cartesian) { + const cartographic = Cesium.Cartographic.fromCartesian(cartesian as any); + const longitude = Cesium.Math.toDegrees(cartographic.longitude); + const latitude = Cesium.Math.toDegrees(cartographic.latitude); + const height = cartographic.height; + + console.log('[BoundaryEditor] ✓ 添加顶点:', { + longitude: longitude.toFixed(6), + latitude: latitude.toFixed(6), + height: height.toFixed(2) + 'm' + }); + onVertexAdd({ longitude, latitude, height }); + requestRender(); + } else { + console.warn('[BoundaryEditor] ✗ 未能获取点击位置,请确保点击在地图或模型上'); + } + }, Cesium.ScreenSpaceEventType.LEFT_CLICK); + + // 双击结束绘制(由组件层处理) + // handler.setInputAction(() => { + // // 触发结束绘制 + // }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK); + + } else if (mode === 'edit') { + // 编辑模式:支持拖动和选择 + try { + if (viewer.scene?.screenSpaceCameraController) { + viewer.scene.screenSpaceCameraController.enableRotate = true; + } + } catch (e) { + console.warn('启用旋转失败:', e); + } + + // 设置编辑模式光标 + viewer.scene.canvas.style.setProperty('cursor', 'pointer', 'important'); + + // LEFT_DOWN: 开始拖拽或选择 + handler.setInputAction((movement: any) => { + const pickedObject = viewer.scene.pick(movement.position); + + if (Cesium.defined(pickedObject) && pickedObject.id) { + const entity = pickedObject.id; + const properties = entity.properties; + + if (properties?.type?.getValue() === 'boundary-vertex') { + const vertexIndex = properties.vertexIndex?.getValue(); + + if (typeof vertexIndex === 'number') { + // 选择顶点 + onVertexSelect(vertexIndex); + + // 准备拖动 + if (properties.draggable?.getValue()) { + draggingEntityRef.current = entity; + viewer.scene.canvas.style.setProperty('cursor', 'grabbing', 'important'); // 拖动光标 + try { + if (viewer.scene?.screenSpaceCameraController) { + viewer.scene.screenSpaceCameraController.enableRotate = false; + } + } catch (e) { + console.warn('禁用旋转失败:', e); + } + } + } + } + } + }, Cesium.ScreenSpaceEventType.LEFT_DOWN); + + // MOUSE_MOVE: 拖拽中(使用requestAnimationFrame节流) + handler.setInputAction((movement: any) => { + if (draggingEntityRef.current && !rafIdRef.current) { + rafIdRef.current = requestAnimationFrame(() => { + const entity = draggingEntityRef.current; + if (!entity) { + rafIdRef.current = null; + return; + } + + const cartesian = pickCartesianFromScreen(movement.endPosition); + + if (cartesian) { + // 更新entity位置 + entity.position = cartesian as any; + + // 通知外部更新vertex数据 + const cartographic = Cesium.Cartographic.fromCartesian(cartesian as any); + const vertexIndex = entity.properties?.vertexIndex?.getValue(); + + if (typeof vertexIndex === 'number') { + onVertexMove(vertexIndex, { + longitude: Cesium.Math.toDegrees(cartographic.longitude), + latitude: Cesium.Math.toDegrees(cartographic.latitude), + height: cartographic.height, + }); + } + requestRender(); + } + + rafIdRef.current = null; + }); + } + }, Cesium.ScreenSpaceEventType.MOUSE_MOVE); + + // LEFT_UP: 结束拖拽 + handler.setInputAction(() => { + if (draggingEntityRef.current) { + viewer.scene.canvas.style.setProperty('cursor', 'pointer', 'important'); // 恢复指针光标 + try { + if (viewer.scene?.screenSpaceCameraController) { + viewer.scene.screenSpaceCameraController.enableRotate = true; + } + } catch (e) { + console.warn('启用旋转失败:', e); + } + draggingEntityRef.current = null; + requestRender(); + } + }, Cesium.ScreenSpaceEventType.LEFT_UP); + + } else { + // view模式:恢复默认交互 + try { + if (viewer.scene?.screenSpaceCameraController) { + viewer.scene.screenSpaceCameraController.enableRotate = true; + } + } catch (e) { + console.warn('启用旋转失败:', e); + } + + // 恢复默认光标 + viewer.scene.canvas.style.setProperty('cursor', 'default', 'important'); + } + }, [viewerRef, mode, getCesium, onVertexAdd, onVertexMove, onVertexSelect, pickCartesianFromScreen, requestRender]); + + /** + * 计算边界范围 + */ + const calculateBounds = useCallback((points: BoundaryVertex[]) => { + if (points.length === 0) { + return { west: 0, south: 0, east: 0, north: 0 }; + } + + let west = points[0].longitude; + let east = points[0].longitude; + let south = points[0].latitude; + let north = points[0].latitude; + + points.forEach(p => { + west = Math.min(west, p.longitude); + east = Math.max(east, p.longitude); + south = Math.min(south, p.latitude); + north = Math.max(north, p.latitude); + }); + + // 添加一些padding + const paddingLon = (east - west) * 0.1 || 0.01; + const paddingLat = (north - south) * 0.1 || 0.01; + + return { + west: west - paddingLon, + south: south - paddingLat, + east: east + paddingLon, + north: north + paddingLat, + }; + }, []); + + /** + * 相机飞到边界 + */ + const flyToBoundary = useCallback(() => { + const viewer = viewerRef.current; + const Cesium = getCesium(); + if (!viewer || !Cesium || viewer.isDestroyed?.() || vertices.length === 0) return; + + const bounds = calculateBounds(vertices); + + try { + viewer.camera.flyTo({ + destination: Cesium.Rectangle.fromDegrees( + bounds.west, + bounds.south, + bounds.east, + bounds.north + ), + duration: 1.0, + }); + } catch (e) { + console.error('飞到边界失败:', e); + } + }, [viewerRef, vertices, getCesium, calculateBounds]); + + /** + * 渲染所有内容 + */ + const render = useCallback(() => { + cleanup(); + renderPolygon(); + renderVertices(); + }, [cleanup, renderPolygon, renderVertices]); + + // vertices或selectedIndex变化时重新渲染 + useEffect(() => { + render(); + }, [vertices, selectedIndex, boundaryType, render]); + + // mode变化时重新设置事件处理器 + useEffect(() => { + setupEventHandlers(); + }, [mode, setupEventHandlers]); + + // 组件挂载时飞到边界(仅执行一次) + useEffect(() => { + if (vertices.length > 0) { + // 延迟执行,确保viewer已准备好 + setTimeout(() => { + flyToBoundary(); + }, 300); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); // 空依赖数组,只在挂载时执行 + + // 组件卸载时清理 + useEffect(() => { + return () => { + cleanup(); + + // 清理事件处理器 + if (handlerRef.current) { + try { + handlerRef.current.destroy(); + } catch (e) {} + handlerRef.current = null; + } + + // 取消pending的RAF + if (rafIdRef.current) { + cancelAnimationFrame(rafIdRef.current); + rafIdRef.current = null; + } + + // 恢复地图旋转(增加完整检查) + const viewer = viewerRef.current; + if (viewer && !viewer.isDestroyed?.() && viewer.scene?.screenSpaceCameraController) { + try { + viewer.scene.screenSpaceCameraController.enableRotate = true; + // 恢复默认光标 + if (viewer.scene.canvas) { + viewer.scene.canvas.style.setProperty('cursor', 'default', 'important'); + } + } catch (e) { + // 忽略清理失败 + console.warn('恢复地图旋转失败:', e); + } + } + + // 恢复场景拾取相关选项 + if (viewer && !viewer.isDestroyed?.() && previousSceneOptionsRef.current) { + try { + if (viewer.scene?.globe && typeof previousSceneOptionsRef.current.depthTestAgainstTerrain === 'boolean') { + viewer.scene.globe.depthTestAgainstTerrain = previousSceneOptionsRef.current.depthTestAgainstTerrain; + } + if (typeof previousSceneOptionsRef.current.pickTranslucentDepth === 'boolean') { + viewer.scene.pickTranslucentDepth = previousSceneOptionsRef.current.pickTranslucentDepth; + } + if (typeof previousSceneOptionsRef.current.requestRenderMode === 'boolean') { + viewer.scene.requestRenderMode = previousSceneOptionsRef.current.requestRenderMode; + } + if (typeof previousSceneOptionsRef.current.maximumRenderTimeChange === 'number') { + viewer.scene.maximumRenderTimeChange = previousSceneOptionsRef.current.maximumRenderTimeChange; + } + } catch { + // 忽略 + } + } + previousSceneOptionsRef.current = null; + requestRender(); + }; + }, [cleanup, viewerRef, requestRender]); + + return { + cleanup, + render, + flyToBoundary, + }; +} diff --git a/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/index.less b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/index.less new file mode 100644 index 00000000..45eff9f3 --- /dev/null +++ b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/index.less @@ -0,0 +1,102 @@ +.editor { + position: absolute; + inset: 0; + pointer-events: none; // 允许点击穿透到地图 + z-index: 900; + + // 子元素需要恢复点击事件 + > * { + pointer-events: auto; + } +} + +.toolbar { + display: flex; + align-items: center; + padding: 8px 12px; + background: rgba(255, 255, 255, 0.95); + border-radius: 4px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15); +} + +.divider { + width: 1px; + height: 24px; + background: #e8e8e8; + margin: 0 8px; +} + +.preview { + width: 280px; + max-height: 400px; + overflow-y: auto; +} + +.saveModal { + :global { + .ant-modal-body { + padding: 24px; + } + } +} + +.boundaryInfo { + color: rgba(255, 255, 255, 0.72); + font-size: 12px; + line-height: 20px; +} + +.vertexMarker { + width: 20px; + height: 20px; + border-radius: 50%; + background: #fff; + border: 2px solid #000; + display: flex; + align-items: center; + justify-content: center; + color: #000; + font-size: 11px; + font-weight: bold; + cursor: pointer; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3); + transition: transform 0.2s; + + &:hover { + transform: scale(1.2); + } + + &.selected { + background: #faad14; + transform: scale(1.3); + } +} + +.boundaryPolygon { + &.navigable { + fill: rgba(0, 255, 0, 0.2); + stroke: #00ff00; + stroke-width: 3; + } + + &.forbidden { + fill: rgba(255, 0, 0, 0.3); + stroke: #ff0000; + stroke-width: 3; + } + + &.warning { + fill: rgba(255, 255, 0, 0.2); + stroke: #ffff00; + stroke-width: 3; + } +} + +.tip { + padding: 8px 12px; + background: rgba(0, 0, 0, 0.7); + color: #fff; + border-radius: 4px; + font-size: 12px; + margin-top: 8px; +} diff --git a/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/index.tsx b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/index.tsx new file mode 100644 index 00000000..d70473b9 --- /dev/null +++ b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/index.tsx @@ -0,0 +1,399 @@ +/** + * 水域边界编辑器主组件 + * @author dzc + * @date 2026-01-06 + */ +import React, { useState, useEffect, useCallback, useMemo } from 'react'; +import { Modal, Form, Input, Select, message, Spin } from 'antd'; +import type { BoundaryEditorProps, BoundaryType, BoundaryVertex } from './types'; +import { useBoundaryDrawing } from './hooks/useBoundaryDrawing'; +import { useCesiumBoundaryRenderer } from './hooks/useCesiumBoundaryRenderer'; +import BoundaryToolbar from './BoundaryToolbar'; +import BoundaryPreview from './BoundaryPreview'; +import { + createWaterBoundary, + getWaterBoundaryDetail, +} from '@/services/waterBoundary'; +import styles from './index.less'; + +const { Option } = Select; + +/** + * 计算多边形面积(使用Shoelace公式,简化局部投影,适用于小范围区域) + */ +function calculatePolygonArea(vertices: { longitude: number; latitude: number }[]): number { + if (vertices.length < 3) return 0; + + const R = 6371000; // 地球半径(米) + const toRadians = (deg: number) => deg * Math.PI / 180; + + const centerLat = vertices.reduce((sum, v) => sum + v.latitude, 0) / vertices.length; + const centerLon = vertices.reduce((sum, v) => sum + v.longitude, 0) / vertices.length; + + const points = vertices.map(v => ({ + x: R * toRadians(v.longitude - centerLon) * Math.cos(toRadians(centerLat)), + y: R * toRadians(v.latitude - centerLat), + })); + + let area = 0; + for (let i = 0; i < points.length; i++) { + const j = (i + 1) % points.length; + area += points[i].x * points[j].y; + area -= points[j].x * points[i].y; + } + return Math.abs(area) / 2; +} + +const BoundaryEditor: React.FC = ({ + deviceSn, + boundaryId, + initialVertices, + onSaveSuccess, + onCancel, + viewerRef, +}) => { + const [loading, setLoading] = useState(false); + const [saveModalVisible, setSaveModalVisible] = useState(false); + const [boundaryType, setBoundaryType] = useState('navigable'); + const [form] = Form.useForm(); + + // 边界绘制Hook + const { + vertices, + editorState, + isDrawing, + setMode, + startDrawing, + finishDrawing, + addVertex, + moveVertex, + selectVertex, + clearVertices, + setVertices, + markSaved, + undo, + canUndo, + } = useBoundaryDrawing({ initialVertices }); + + const boundaryArea = useMemo(() => calculatePolygonArea(vertices), [vertices]); + const areaText = useMemo(() => { + if (!boundaryArea) return '-'; + if (boundaryArea < 1000) return `${boundaryArea.toFixed(2)} m2`; + if (boundaryArea < 1000000) return `${(boundaryArea / 1000).toFixed(2)} 千m2`; + return `${(boundaryArea / 1000000).toFixed(2)} km2`; + }, [boundaryArea]); + + const centerPointText = useMemo(() => { + if (vertices.length === 0) return '-'; + const centerLon = vertices.reduce((sum, v) => sum + v.longitude, 0) / vertices.length; + const centerLat = vertices.reduce((sum, v) => sum + v.latitude, 0) / vertices.length; + return `${centerLon.toFixed(6)}, ${centerLat.toFixed(6)}`; + }, [vertices]); + + // Cesium边界渲染Hook + useCesiumBoundaryRenderer({ + viewerRef, + vertices, + selectedIndex: editorState.selectedVertexIndex, + mode: editorState.mode, + boundaryType, + onVertexAdd: handleMapClick, + onVertexMove: moveVertex, + onVertexSelect: selectVertex, + }); + + // 加载现有边界 + useEffect(() => { + if (boundaryId) { + loadBoundary(boundaryId); + } + }, [boundaryId]); + + const loadBoundary = async (id: string) => { + setLoading(true); + try { + const response = await getWaterBoundaryDetail(id); + const boundary = (response as any)?.data ?? (response as any)?.datas; + if (response.resp_code === 0 && boundary) { + // 设置表单值 + form.setFieldsValue({ + boundaryName: boundary.boundaryName, + boundaryType: boundary.boundaryType, + }); + setBoundaryType(boundary.boundaryType as BoundaryType); + + // 解析GeoJSON并设置顶点 + try { + const geoJson = JSON.parse(boundary.polygonData); + if (geoJson.type === 'Polygon' && geoJson.coordinates && geoJson.coordinates[0]) { + const coords = geoJson.coordinates[0]; + const verts: BoundaryVertex[] = coords.map((coord: number[]) => ({ + longitude: coord[0], + latitude: coord[1], + })); + // 移除最后一个点(GeoJSON的闭合点) + if (verts.length > 1) { + verts.pop(); + } + setVertices(verts); + } + } catch (e) { + console.error('解析边界GeoJSON失败:', e); + message.error('加载边界数据失败'); + } + } + } catch (error) { + message.error('加载边界失败'); + } finally { + setLoading(false); + } + }; + + // 处理地图点击 + function handleMapClick(event: { longitude: number; latitude: number; height?: number }) { + if (editorState.mode === 'draw') { + addVertex(event); + } + } + + // 处理模式切换 + const handleModeChange = useCallback((mode: 'view' | 'draw' | 'edit') => { + setMode(mode); + if (mode !== 'edit') { + selectVertex(null); + } + }, [setMode, selectVertex]); + + // 打开保存对话框 + const handleOpenSaveModal = useCallback(() => { + if (vertices.length < 3) { + message.warning('边界至少需要3个顶点'); + return; + } + setSaveModalVisible(true); + }, [vertices]); + + // 处理保存 + const handleSave = useCallback(async () => { + try { + const values = await form.validateFields(); + + if (vertices.length < 3) { + message.warning('边界至少需要3个顶点'); + return; + } + + setLoading(true); + + // 构造GeoJSON + // GeoJSON Polygon格式要求第一个点和最后一个点相同(闭合) + const coordinates = [ + ...vertices.map(v => [v.longitude, v.latitude]), + [vertices[0].longitude, vertices[0].latitude], // 闭合多边形 + ]; + + const polygonData = JSON.stringify({ + type: 'Polygon', + coordinates: [coordinates], + }); + + if (boundaryId) { + message.error('当前后端暂不支持更新边界,请删除后重新创建'); + return; + } else { + // 创建边界 + const sn = String(deviceSn || '').trim(); + if (!sn) { + message.error('设备SN无效,请先选择设备'); + return; + } + + // 计算中心点(经纬度平均值) + const centerLongitude = vertices.reduce((sum, v) => sum + v.longitude, 0) / vertices.length; + const centerLatitude = vertices.reduce((sum, v) => sum + v.latitude, 0) / vertices.length; + const centerPoint = `${centerLongitude.toFixed(6)},${centerLatitude.toFixed(6)}`; + + const createData = { + deviceSn: sn, + boundaryName: values.boundaryName, + boundaryType: values.boundaryType, + polygonData, + centerPoint, + sourceType: 'manual' as const, + showInModel: 1 as const, + }; + const response = await createWaterBoundary(createData); + const createdId = (response as any)?.data ?? (response as any)?.datas; + if (response.resp_code === 0 && createdId) { + message.success(response.resp_msg || '边界创建成功'); + markSaved(); + setSaveModalVisible(false); + setMode('view'); + selectVertex(null); + onSaveSuccess?.(createdId); + } else { + message.error(response.resp_msg || '创建失败'); + } + } + } catch (error) { + console.error('保存边界失败:', error); + const anyErr = error as any; + const serverMsg = + anyErr?.data?.resp_msg || + anyErr?.data?.message || + anyErr?.response?.data?.resp_msg || + anyErr?.response?.data?.message; + message.error(serverMsg || '保存失败:后端参数校验未通过(请检查控制台 Network 响应内容)'); + } finally { + setLoading(false); + } + }, [form, vertices, boundaryId, deviceSn, markSaved, onSaveSuccess, setMode, selectVertex]); + + // 处理取消 + const handleCancel = useCallback(() => { + if (editorState.hasUnsavedChanges) { + Modal.confirm({ + title: '确认关闭?', + content: '有未保存的更改,确定要关闭编辑器吗?', + onOk: () => { + onCancel?.(); + }, + }); + } else { + onCancel?.(); + } + }, [editorState.hasUnsavedChanges, onCancel]); + + // ESC键监听 + useEffect(() => { + const handleEsc = (e: KeyboardEvent) => { + if (e.key === 'Escape') { + if (isDrawing) { + finishDrawing(); + } + } + }; + window.addEventListener('keydown', handleEsc); + return () => { + window.removeEventListener('keydown', handleEsc); + }; + }, [isDrawing, finishDrawing]); + + // 快捷键:Ctrl+Z 撤销(输入框内不拦截) + useEffect(() => { + const handleKeyDown = (e: KeyboardEvent) => { + const target = e.target as HTMLElement | null; + const tagName = target?.tagName?.toLowerCase?.(); + const isTypingTarget = tagName === 'input' || tagName === 'textarea' || !!target?.isContentEditable; + if (isTypingTarget) return; + + const key = e.key?.toLowerCase?.(); + const isUndo = (e.ctrlKey || e.metaKey) && key === 'z'; + if (!isUndo) return; + if (!canUndo) return; + + e.preventDefault(); + undo(); + }; + window.addEventListener('keydown', handleKeyDown); + return () => window.removeEventListener('keydown', handleKeyDown); + }, [canUndo, undo]); + + return ( +
+ {/* 工具栏 - 独立渲染,不受Spin影响 */} + 0} + hasUnsavedChanges={editorState.hasUnsavedChanges} + isDrawing={isDrawing} + canUndo={canUndo} + onModeChange={handleModeChange} + onStartDraw={startDrawing} + onFinishDraw={finishDrawing} + onUndo={undo} + onClear={clearVertices} + onSave={handleOpenSaveModal} + onCancel={handleCancel} + /> + + {/* 预览面板 - 独立渲染,不受Spin影响 */} + {vertices.length > 0 && ( + + )} + + {/* 保存对话框 - 带Loading */} + setSaveModalVisible(false)} + confirmLoading={loading} + width={480} + className={styles.saveModal} + > +
+ + + + + + + + + +
+
顶点数量:{vertices.length}
+
中心点:{centerPointText}
+
估算面积:{areaText}
+
+
+
+
+ + {/* 全局Loading遮罩 - 仅在加载时显示 */} + {loading && ( +
+ +
+ )} +
+ ); +}; + +export default BoundaryEditor; diff --git a/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/types.ts b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/types.ts new file mode 100644 index 00000000..ee56bd58 --- /dev/null +++ b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/types.ts @@ -0,0 +1,132 @@ +/** + * 水域边界编辑器类型定义 + * @author dzc + * @date 2026-01-06 + */ + +/** + * 边界类型 + */ +export type BoundaryType = 'navigable' | 'obstacle' | 'restricted'; + +/** + * 边界顶点 + */ +export interface BoundaryVertex { + longitude: number; + latitude: number; + /** 点击 3D 模型/地形时的高度(米),用于在模型表面正确显示顶点) */ + height?: number; +} + +/** + * 编辑器模式 + */ +export type EditorMode = 'view' | 'draw' | 'edit'; + +/** + * 边界编辑器状态 + */ +export interface EditorState { + mode: EditorMode; + selectedVertexIndex: number | null; + hasUnsavedChanges: boolean; +} + +/** + * 边界创建DTO(对应后端) + */ +export interface WaterBoundaryCreateDTO { + /** 绑定设备SN(用于与设备关联) */ + deviceSn: string; + /** 所属景区ID(可选,当前前端不依赖) */ + scenicId?: number; + boundaryName: string; + boundaryType: BoundaryType; + polygonData: string; + centerPoint?: string; + area?: number; + sourceType?: 'manual' | 'model' | 'import'; + modelId?: string; + /** 是否在模型中显示标绘:0-否,1-是(可选,默认1) */ + showInModel?: 0 | 1; +} + +/** + * 边界更新DTO(对应后端) + */ +export interface WaterBoundaryUpdateDTO { + boundaryName?: string; + boundaryType?: BoundaryType; + polygonData?: string; + centerPoint?: string; + area?: number; + sourceType?: 'manual' | 'model' | 'import'; + modelId?: string; +} + +/** + * 边界详情VO(对应后端) + */ +export interface WaterBoundaryVO { + boundaryId: string; + deviceSn?: string; + scenicId?: number; + boundaryName: string; + boundaryType: BoundaryType; + boundaryTypeDesc?: string; + polygonData: string; + centerPoint?: string; + area?: number; + sourceType?: string; + /** 是否在模型中显示标绘:0-否,1-是 */ + showInModel?: 0 | 1; + status?: number; + statusDesc?: string; + createTime?: string; +} + +/** + * BoundaryEditor组件Props + */ +export interface BoundaryEditorProps { + /** 绑定设备SN */ + deviceSn: string; + /** 编辑已有边界的ID(可选) */ + boundaryId?: string; + /** 初始顶点(可选) */ + initialVertices?: BoundaryVertex[]; + /** 保存成功回调 */ + onSaveSuccess?: (boundaryId: string) => void; + /** 取消回调 */ + onCancel?: () => void; + /** Cesium Viewer引用 */ + viewerRef: React.RefObject; +} + +/** + * 边界工具栏Props + */ +export interface BoundaryToolbarProps { + mode: EditorMode; + hasVertices: boolean; + hasUnsavedChanges: boolean; + isDrawing: boolean; + canUndo?: boolean; + onModeChange: (mode: EditorMode) => void; + onStartDraw: () => void; + onFinishDraw: () => void; + onUndo?: () => void; + onClear: () => void; + onSave: () => void; + onCancel: () => void; +} + +/** + * 边界预览Props + */ +export interface BoundaryPreviewProps { + vertices: BoundaryVertex[]; + boundaryType: BoundaryType; + area?: number; +} diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/BoatRouteTab.less b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/BoatRouteTab.less new file mode 100644 index 00000000..eccc3ae7 --- /dev/null +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/BoatRouteTab.less @@ -0,0 +1,98 @@ +.boatRouteTab { + padding: 0 4px; +} + +.section { + margin-bottom: 16px; +} + +.sectionHeader { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 8px; +} + +.sectionTitle { + font-size: 13px; + font-weight: 500; + color: #333; + margin-bottom: 8px; +} + +.routeOption { + display: flex; + align-items: center; + justify-content: space-between; + width: 100%; +} + +.routeDetail { + background: #f5f5f5; + border-radius: 4px; + padding: 12px; + margin-bottom: 8px; +} + +.detailRow { + display: flex; + justify-content: space-between; + align-items: center; + font-size: 12px; + color: #666; + + & + & { + margin-top: 6px; + } + + span:first-child { + color: #999; + } + + span:last-child { + color: #333; + font-weight: 500; + } +} + +.routeActions { + display: flex; + gap: 8px; +} + +.deviceStatus { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 8px; +} + +.battery { + display: flex; + align-items: center; + gap: 8px; + font-size: 12px; + color: #666; +} + +.position { + display: flex; + align-items: center; + gap: 6px; + font-size: 12px; + color: #666; + + :global(.anticon) { + color: #1890ff; + } +} + +.controlButtons { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.emptyState { + padding: 24px 0; +} diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/BoatRouteTab.tsx b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/BoatRouteTab.tsx new file mode 100644 index 00000000..a1803368 --- /dev/null +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/BoatRouteTab.tsx @@ -0,0 +1,524 @@ +/** + * 无人船航线Tab组件 + * 用于在TaskPanel中显示无人船航线列表和操作 + * @author dzc + * @date 2026-01-05 + */ +import React, { useState, useEffect, useCallback, useMemo } from 'react'; +import { + Button, + Select, + Tag, + Tooltip, + Empty, + Spin, + Modal, + message, + Progress, + Switch, + Space, +} from 'antd'; +import { + PlusOutlined, + EditOutlined, + DeleteOutlined, + PlayCircleOutlined, + PauseCircleOutlined, + StopOutlined, + RollbackOutlined, + EnvironmentOutlined, + AimOutlined, + ReloadOutlined, + EyeOutlined, +} from '@ant-design/icons'; +import { useCesiumBoatTrack } from '../hooks/useCesiumBoatTrack'; +import type { + BoatRouteListVO, + BoatTelemetryData, + MissionType, +} from '@/types/boatRoute'; +import { + getBoatRoutesByScenicId, + getBoatRoutesByDevice, + deleteBoatRoute, +} from '@/services/boatRoute'; +import { + pauseBoatNavigation, + resumeBoatNavigation, + emergencyStopBoat, + returnBoatToStart, +} from '@/services/boatControl'; +import { saveMission, executeMission } from '@/services/mission'; +import styles from './BoatRouteTab.less'; + +interface BoatRouteTabProps { + deviceSn: string; + scenicId: number; + boatData?: BoatTelemetryData | null; + onEditRoute?: (routeId: string) => void; + onCreateRoute?: () => void; + viewerRef?: React.RefObject; // Cesium viewer引用,用于实时轨迹渲染 +} + +const BoatRouteTab: React.FC = ({ + deviceSn, + scenicId, + boatData, + onEditRoute, + onCreateRoute, + viewerRef, +}) => { + const [routeList, setRouteList] = useState([]); + const [loading, setLoading] = useState(false); + const [selectedRouteId, setSelectedRouteId] = useState(null); + const [executing, setExecuting] = useState(false); + + // 实时跟踪状态 + const [trackingEnabled, setTrackingEnabled] = useState(false); + + // 使用无人船实时跟踪Hook + const { boatData: realtimeBoatData, clearTrack, flyToBoat } = useCesiumBoatTrack({ + viewerRef: viewerRef || { current: null }, + enabled: trackingEnabled, + deviceSn: trackingEnabled ? deviceSn : null, + }); + + // 加载航线列表 + const loadRoutes = useCallback(async () => { + setLoading(true); + try { + const res = await getBoatRoutesByScenicId(scenicId, { page: 1, size: 50 }); + if (res.resp_code === 0 && res.datas) { + // datas 可能直接是数组,也可能是分页对象 + const routes = Array.isArray(res.datas) ? res.datas : (res.datas as any).records || []; + setRouteList(routes); + } + } catch (error) { + message.error('加载航线列表失败'); + } finally { + setLoading(false); + } + }, [scenicId]); + + useEffect(() => { + if (scenicId) { + loadRoutes(); + } + }, [scenicId, loadRoutes]); + + // 选中的航线 + const selectedRoute = useMemo(() => { + return routeList.find((r) => r.routeId === selectedRouteId); + }, [routeList, selectedRouteId]); + + // 设备状态 + const deviceStatus = useMemo(() => { + return boatData?.status || 'unknown'; + }, [boatData]); + + const isExecuting = deviceStatus === 'executing'; + const isPaused = deviceStatus === 'paused'; + const isIdle = deviceStatus === 'idle' || deviceStatus === 'unknown'; + + // 创建并执行任务 + const handleExecuteRoute = useCallback(async () => { + if (!selectedRouteId || !selectedRoute) { + message.warning('请先选择航线'); + return; + } + + Modal.confirm({ + title: '确认执行航线', + content: ( +
+

确定要执行航线 {selectedRoute.routeName} 吗?

+

+ 航点数: {selectedRoute.waypointCount} | 预计时长: {selectedRoute.totalDurationStr} +

+
+ ), + onOk: async () => { + setExecuting(true); + try { + // 1. 创建任务 + const createRes = await saveMission({ + deviceSn, + missionType: 3, // BOAT_ROUTE + boatRouteId: selectedRouteId, + boatRouteName: selectedRoute.routeName, + tourismId: scenicId, + }); + + if (createRes.resp_code !== 0) { + message.error(createRes.resp_msg || '创建任务失败'); + return; + } + + const missionCode = createRes.datas?.missionCode; + if (!missionCode) { + message.error('获取任务编码失败'); + return; + } + + // 2. 执行任务 + const execRes = await executeMission(missionCode); + if (execRes.resp_code === 0) { + message.success('航线任务已下发执行'); + } else { + message.error(execRes.resp_msg || '执行失败'); + } + } catch (error) { + message.error('执行航线失败'); + } finally { + setExecuting(false); + } + }, + }); + }, [selectedRouteId, selectedRoute, deviceSn, scenicId]); + + // 暂停 + const handlePause = useCallback(async () => { + try { + const res = await pauseBoatNavigation(deviceSn); + if (res.resp_code === 0) { + message.success('已暂停航行'); + } else { + message.error(res.resp_msg || '操作失败'); + } + } catch (error) { + message.error('操作失败'); + } + }, [deviceSn]); + + // 恢复 + const handleResume = useCallback(async () => { + try { + const res = await resumeBoatNavigation(deviceSn); + if (res.resp_code === 0) { + message.success('已恢复航行'); + } else { + message.error(res.resp_msg || '操作失败'); + } + } catch (error) { + message.error('操作失败'); + } + }, [deviceSn]); + + // 返航 + const handleReturn = useCallback(async () => { + Modal.confirm({ + title: '确认返航', + content: '确定要让无人船返回起点吗?', + onOk: async () => { + try { + const res = await returnBoatToStart(deviceSn); + if (res.resp_code === 0) { + message.success('返航指令已下发'); + } else { + message.error(res.resp_msg || '操作失败'); + } + } catch (error) { + message.error('操作失败'); + } + }, + }); + }, [deviceSn]); + + // 紧急停止 + const handleEmergencyStop = useCallback(async () => { + Modal.confirm({ + title: '紧急停止', + content: '确定要紧急停止无人船吗?', + okType: 'danger', + okText: '紧急停止', + onOk: async () => { + try { + const res = await emergencyStopBoat(deviceSn); + if (res.resp_code === 0) { + message.warning('已紧急停止'); + } else { + message.error(res.resp_msg || '操作失败'); + } + } catch (error) { + message.error('操作失败'); + } + }, + }); + }, [deviceSn]); + + // 删除航线 + const handleDeleteRoute = useCallback( + async (routeId: string) => { + const route = routeList.find((r) => r.routeId === routeId); + Modal.confirm({ + title: '删除航线', + content: `确定要删除航线 "${route?.routeName}" 吗?`, + okType: 'danger', + onOk: async () => { + try { + const res = await deleteBoatRoute(routeId); + if (res.resp_code === 0) { + message.success('删除成功'); + loadRoutes(); + if (selectedRouteId === routeId) { + setSelectedRouteId(null); + } + } else { + message.error(res.resp_msg || '删除失败'); + } + } catch (error) { + message.error('删除失败'); + } + }, + }); + }, + [routeList, selectedRouteId, loadRoutes] + ); + + return ( +
+ {/* 航线选择 */} +
+
+ 选择航线 + +
+ +
+ + {/* 航线详情 */} + {selectedRoute && ( +
+
航线详情
+
+
+ 航点数: + {selectedRoute.waypointCount} +
+
+ 总距离: + {(selectedRoute.totalDistance / 1000).toFixed(2)} km +
+
+ 预计时长: + {selectedRoute.totalDurationStr} +
+
+ 状态: + + {selectedRoute.statusDesc} + +
+
+
+ +
+
+ )} + + {/* 设备状态 */} + {boatData && ( +
+
无人船状态
+
+ + {isExecuting ? '执行中' : isPaused ? '已暂停' : '空闲'} + + {boatData.battery !== undefined && ( +
+ 电量: + +
+ )} +
+ {boatData.longitude && boatData.latitude && ( +
+ + + {boatData.longitude.toFixed(6)}, {boatData.latitude.toFixed(6)} + +
+ )} +
+ )} + + {/* 实时跟踪 */} + {viewerRef && ( +
+
+ 实时跟踪 + + { + setTrackingEnabled(checked); + if (!checked) { + clearTrack(); + } + }} + checkedChildren="已开启" + unCheckedChildren="已关闭" + /> + +
+ {trackingEnabled && realtimeBoatData && ( +
+
+ 航向: + {realtimeBoatData.heading?.toFixed(0) || '--'}° +
+
+ 速度: + {realtimeBoatData.speed?.toFixed(1) || '--'} m/s +
+
+ 电量: + {realtimeBoatData.battery || '--'}% +
+ + + +
+ )} + {trackingEnabled && !realtimeBoatData && ( +
+ 等待接收遥测数据... +
+ )} +
+ )} + + {/* 控制按钮 */} +
+
操作
+
+ {isIdle && ( + + )} + + {isExecuting && ( + <> + + + + )} + + {isPaused && ( + <> + + + + )} + + {(isExecuting || isPaused) && ( + + )} +
+
+ + {/* 新建航线按钮 */} +
+ +
+
+ ); +}; + +export default BoatRouteTab; diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.less b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.less new file mode 100644 index 00000000..8da25f41 --- /dev/null +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.less @@ -0,0 +1,183 @@ +.layerPanel { + position: absolute; + left: 20px; + top: 20px; + width: 320px; + max-height: 600px; + z-index: 100; +} + +.cardTitle { + cursor: move; + user-select: none; +} + +.card { + background: rgba(10, 20, 40, 0.95) !important; + border-radius: 8px; + box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3); + border: 1px solid rgba(0, 240, 255, 0.3); + + :global { + .ant-card-head { + color: #fff; + border-bottom: 1px solid rgba(255, 255, 255, 0.1); + min-height: 40px; + padding: 0 12px; + } + + .ant-card-head-title { + padding: 8px 0; + font-size: 14px; + font-weight: 500; + } + + .ant-card-extra { + padding: 8px 0; + } + + .ant-card-body { + padding: 12px; + max-height: 520px; + overflow-y: auto; + color: rgba(255, 255, 255, 0.85); + + /* 自定义滚动条 */ + &::-webkit-scrollbar { + width: 6px; + } + + &::-webkit-scrollbar-track { + background: rgba(255, 255, 255, 0.05); + border-radius: 3px; + } + + &::-webkit-scrollbar-thumb { + background: rgba(0, 240, 255, 0.3); + border-radius: 3px; + + &:hover { + background: rgba(0, 240, 255, 0.5); + } + } + } + } +} + +.section { + margin-bottom: 16px; + + &:last-child { + margin-bottom: 0; + } +} + +.sectionHeader { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 8px; + padding-bottom: 6px; + border-bottom: 1px solid rgba(255, 255, 255, 0.1); +} + +.sectionTitle { + font-size: 13px; + font-weight: 500; + color: #fff; +} + +.listItem { + display: flex; + align-items: center; + justify-content: space-between; + padding: 6px 0 !important; + border-bottom: 1px solid rgba(255, 255, 255, 0.05) !important; + + &:last-child { + border-bottom: none !important; + } + + :global { + .ant-checkbox-wrapper { + flex: 1; + color: rgba(255, 255, 255, 0.85); + + &:hover { + color: #00f0ff; + } + } + + .ant-checkbox-inner { + background-color: rgba(255, 255, 255, 0.1); + border-color: rgba(0, 240, 255, 0.5); + } + + .ant-checkbox-checked .ant-checkbox-inner { + background-color: #00f0ff; + border-color: #00f0ff; + } + + .ant-tag { + margin: 0; + font-size: 11px; + line-height: 18px; + padding: 0 6px; + } + } +} + +.itemName { + font-size: 12px; + margin-left: 6px; +} + +.loading { + text-align: center; + padding: 20px 0; + color: rgba(255, 255, 255, 0.5); + font-size: 12px; +} + +.footer { + margin-top: 12px; + padding-top: 8px; + border-top: 1px solid rgba(255, 255, 255, 0.1); + font-size: 11px; + color: rgba(255, 255, 255, 0.5); + text-align: center; +} + +/* 按钮样式覆盖 */ +:global { + .layerPanel { + .ant-btn-link { + color: rgba(0, 240, 255, 0.8); + font-size: 12px; + padding: 0 4px; + height: auto; + + &:hover { + color: #00f0ff; + } + + &:disabled { + color: rgba(255, 255, 255, 0.3); + } + } + + .ant-btn-text { + color: rgba(255, 255, 255, 0.7); + + &:hover { + color: #00f0ff; + background: rgba(0, 240, 255, 0.1); + } + } + + .ant-empty-description { + color: rgba(255, 255, 255, 0.4); + font-size: 12px; + } + } +} diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.tsx b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.tsx new file mode 100644 index 00000000..4744450e --- /dev/null +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.tsx @@ -0,0 +1,909 @@ +/** + * 图层管理面板组件 + * 用于管理边界图层的显示/隐藏 + * @author dzc + * @date 2026-01-06 + */ +import React, { useState, useEffect, useLayoutEffect, useRef, useCallback } from 'react'; +import { Card, Checkbox, List, Tag, Button, message, Empty, Tooltip, Space, Popconfirm } from 'antd'; +import { + CloseOutlined, + ReloadOutlined, + EyeOutlined, + EyeInvisibleOutlined, + PlusOutlined, + DeleteOutlined, +} from '@ant-design/icons'; +import { + getWaterBoundariesByDeviceSn, + getWaterBoundaryDetail, + updateWaterBoundaryShowInModelByDeviceSn, + deleteWaterBoundary, +} from '@/services/waterBoundary'; +import type { WaterBoundaryVO } from '@/pages/map3d/components/BoundaryEditor/types'; +import styles from './LayerPanel.less'; + +export interface LayerPanelProps { + visible: boolean; + onClose: () => void; + viewer: any; + Cesium: any; + deviceSn?: string; + scenicId?: number; + onBoundaryEditorOpen?: () => void; // 新增:打开边界编辑器的回调 + onRoutePlanningOpen?: (boundary: WaterBoundaryVO) => void; + autoShowBoundaryId?: string; + onAutoShowBoundaryHandled?: () => void; +} + +function normalizeId(value: any): string { + return String(value ?? '').trim(); +} + +type NormalizedPoint = { longitude: number; latitude: number }; + +function normalizePoint(coord: any): NormalizedPoint | null { + if (!Array.isArray(coord) || coord.length < 2) return null; + const longitude = Number(coord[0]); + const latitude = Number(coord[1]); + if (Number.isNaN(longitude) || Number.isNaN(latitude)) return null; + return { longitude, latitude }; +} + +function stripClosedRing(points: NormalizedPoint[]): NormalizedPoint[] { + if (points.length < 2) return points; + const first = points[0]; + const last = points[points.length - 1]; + if (first.longitude === last.longitude && first.latitude === last.latitude) { + return points.slice(0, -1); + } + return points; +} + +function parseBoundaryGeoJson(polygonData: string): Array<{ outer: NormalizedPoint[]; holes: NormalizedPoint[][] }> { + const result: Array<{ outer: NormalizedPoint[]; holes: NormalizedPoint[][] }> = []; + if (!polygonData) return result; + + let raw: any; + try { + raw = JSON.parse(polygonData); + } catch { + return result; + } + + // 兼容:Feature / FeatureCollection / Geometry + const geometry = (() => { + if (!raw) return null; + if (raw.type === 'Feature') return raw.geometry ?? null; + if (raw.type === 'FeatureCollection') return raw.features?.[0]?.geometry ?? null; + return raw; + })(); + + if (!geometry?.type) return result; + + const pushPolygon = (polygonCoords: any) => { + if (!Array.isArray(polygonCoords) || polygonCoords.length === 0) return; + const rings = polygonCoords.filter((r: any) => Array.isArray(r)); + if (rings.length === 0) return; + + const normalizeRing = (ring: any): NormalizedPoint[] => { + if (!Array.isArray(ring)) return []; + const pts = ring.map(normalizePoint).filter(Boolean) as NormalizedPoint[]; + return stripClosedRing(pts); + }; + + const outer = normalizeRing(rings[0]); + const holes = rings.slice(1).map(normalizeRing).filter(h => h.length >= 3); + if (outer.length >= 3) { + result.push({ outer, holes }); + } + }; + + if (geometry.type === 'Polygon') { + pushPolygon(geometry.coordinates); + } else if (geometry.type === 'MultiPolygon') { + const polys = Array.isArray(geometry.coordinates) ? geometry.coordinates : []; + polys.forEach(pushPolygon); + } + + return result; +} + +function getBoundaryVertexCount(boundary: WaterBoundaryVO): number { + const polys = parseBoundaryGeoJson(boundary.polygonData); + if (!polys.length) return 0; + return polys.reduce((sum, p) => sum + (p.outer?.length || 0), 0); +} + +/** + * 获取边界类型颜色 + */ +function getBoundaryColor(type: string, Cesium: any) { + switch (type) { + case 'navigable': + return Cesium.Color.fromCssColorString('#00ff00'); + case 'restricted': + return Cesium.Color.fromCssColorString('#ff0000'); + case 'obstacle': + return Cesium.Color.fromCssColorString('#ffff00'); + default: + return Cesium.Color.fromCssColorString('#00ff00'); + } +} + +/** + * 获取边界类型透明度 + */ +function getBoundaryAlpha(type: string): number { + switch (type) { + case 'navigable': + return 0.2; + case 'restricted': + return 0.3; + case 'obstacle': + return 0.2; + default: + return 0.2; + } +} + +const LayerPanel: React.FC = ({ + visible, + onClose, + viewer, + Cesium, + deviceSn, + onBoundaryEditorOpen, // 新增 + onRoutePlanningOpen, + autoShowBoundaryId, + onAutoShowBoundaryHandled, +}) => { + // 边界列表 + const [boundaries, setBoundaries] = useState([]); + const [loadingBoundaries, setLoadingBoundaries] = useState(false); + const [visibleBoundaries, setVisibleBoundaries] = useState>(new Set()); + + // 用于卸载时清理(避免依赖变化触发 cleanup 误删) + const visibleBoundariesRef = useRef>(new Set()); + + useEffect(() => { + visibleBoundariesRef.current = visibleBoundaries; + }, [visibleBoundaries]); + + // Entity引用管理 + const boundaryEntitiesRef = useRef>(new Map()); + const currentDeviceSnRef = useRef(''); + const loadBoundariesSeqRef = useRef(0); + const selectionVersionRef = useRef(0); + const pendingApplyShowInModelRef = useRef<{ requestSeq: number; selectionVersionAtStart: number } | null>(null); + + const normalizedDeviceSn = normalizeId(deviceSn); + + const clearAllBoundaryEntities = useCallback(() => { + if (!viewer || viewer.isDestroyed?.()) return; + boundaryEntitiesRef.current.forEach((entityIds) => { + entityIds.forEach((id) => { + try { + viewer.entities.removeById(id); + } catch { + // 忽略 + } + }); + }); + boundaryEntitiesRef.current.clear(); + try { + viewer.scene?.requestRender?.(); + } catch { + // 忽略 + } + }, [viewer]); + + const persistShowInModel = useCallback(async (deviceSnToSave: string, boundaryIds: string[]) => { + const sn = normalizeId(deviceSnToSave); + if (!sn) { + message.warning('请先选择设备'); + return false; + } + + try { + const res = await updateWaterBoundaryShowInModelByDeviceSn(sn, boundaryIds); + if ((res as any)?.resp_code === 0) return true; + message.error((res as any)?.resp_msg || '标绘显示状态保存失败'); + return false; + } catch (e) { + console.error('标绘显示状态保存失败:', e); + message.error('标绘显示状态保存失败'); + return false; + } + }, []); + + // 面板拖动 + const panelRef = useRef(null); + const dragStateRef = useRef<{ + startX: number; + startY: number; + startLeft: number; + startTop: number; + panelWidth: number; + panelHeight: number; + } | null>(null); + const [panelPos, setPanelPos] = useState<{ left: number; top: number } | null>(null); + const panelPosRef = useRef<{ left: number; top: number } | null>(null); + const PANEL_POS_KEY = 'yingyan_layer_panel_position_v1'; + + useEffect(() => { + panelPosRef.current = panelPos; + }, [panelPos]); + + const clampPanelPos = useCallback((pos: { left: number; top: number }, panelWidth: number, panelHeight: number) => { + const margin = 12; + const maxLeft = Math.max(margin, window.innerWidth - panelWidth - margin); + const maxTop = Math.max(margin, window.innerHeight - panelHeight - margin); + return { + left: Math.min(Math.max(pos.left, margin), maxLeft), + top: Math.min(Math.max(pos.top, margin), maxTop), + }; + }, []); + + // 初始化拖动位置(优先本地缓存,否则默认左下角) + useLayoutEffect(() => { + if (!visible) return; + if (panelPos) return; + const el = panelRef.current; + if (!el) return; + + const rect = el.getBoundingClientRect(); + const width = rect.width || 320; + const height = rect.height || 300; + + try { + const raw = localStorage.getItem(PANEL_POS_KEY); + if (raw) { + const parsed = JSON.parse(raw) as { left?: number; top?: number }; + if (typeof parsed.left === 'number' && typeof parsed.top === 'number') { + setPanelPos(clampPanelPos({ left: parsed.left, top: parsed.top }, width, height)); + return; + } + } + } catch { + // 忽略 + } + + setPanelPos( + clampPanelPos( + { + left: 20, + top: Math.max(20, window.innerHeight - height - 20), + }, + width, + height, + ), + ); + }, [visible, panelPos, clampPanelPos]); + + // 窗口尺寸变化时,自动把面板“夹”回可视区域 + useEffect(() => { + if (!visible) return; + if (!panelPos) return; + const el = panelRef.current; + if (!el) return; + + const handleResize = () => { + const rect = el.getBoundingClientRect(); + setPanelPos(prev => { + if (!prev) return prev; + return clampPanelPos(prev, rect.width || 320, rect.height || 300); + }); + }; + window.addEventListener('resize', handleResize); + return () => window.removeEventListener('resize', handleResize); + }, [visible, panelPos, clampPanelPos]); + + const handleDragStart = useCallback((e: React.PointerEvent) => { + // 仅左键拖动 + if (e.button !== 0) return; + + const target = e.target as HTMLElement | null; + if (target?.closest('button,a,input,textarea,.ant-btn,.ant-checkbox-wrapper,.ant-select,.ant-dropdown')) { + return; + } + + const el = panelRef.current; + if (!el) return; + const rect = el.getBoundingClientRect(); + + const current = panelPos ?? { left: rect.left, top: rect.top }; + const next = clampPanelPos(current, rect.width || 320, rect.height || 300); + setPanelPos(next); + + dragStateRef.current = { + startX: e.clientX, + startY: e.clientY, + startLeft: next.left, + startTop: next.top, + panelWidth: rect.width || 320, + panelHeight: rect.height || 300, + }; + + try { + (e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId); + } catch { + // 忽略 + } + e.preventDefault(); + }, [panelPos, clampPanelPos]); + + const handleDragMove = useCallback((e: React.PointerEvent) => { + const state = dragStateRef.current; + if (!state) return; + const { startX, startY, startLeft, startTop, panelWidth, panelHeight } = state; + + const next = clampPanelPos( + { + left: startLeft + (e.clientX - startX), + top: startTop + (e.clientY - startY), + }, + panelWidth, + panelHeight, + ); + setPanelPos(next); + e.preventDefault(); + }, [clampPanelPos]); + + const handleDragEnd = useCallback(() => { + if (!dragStateRef.current) return; + dragStateRef.current = null; + const latest = panelPosRef.current; + if (!latest) return; + try { + localStorage.setItem(PANEL_POS_KEY, JSON.stringify(latest)); + } catch { + // 忽略 + } + }, []); + + /** + * 加载边界列表 + */ + const loadBoundaries = useCallback(async (deviceSnOverride?: string) => { + const targetDeviceSn = normalizeId(deviceSnOverride ?? deviceSn); + if (!targetDeviceSn) return; + + const requestSeq = ++loadBoundariesSeqRef.current; + const selectionVersionAtStart = selectionVersionRef.current; + + setLoadingBoundaries(true); + try { + const response = await getWaterBoundariesByDeviceSn(targetDeviceSn); + if (requestSeq !== loadBoundariesSeqRef.current) { + return; + } + const list = (response as any)?.data ?? (response as any)?.datas; + if (response.resp_code === 0 && list) { + pendingApplyShowInModelRef.current = { requestSeq, selectionVersionAtStart }; + setBoundaries(Array.isArray(list) ? list : []); + } + } catch (error) { + console.error('加载边界列表失败:', error); + message.error('加载边界列表失败'); + } finally { + setLoadingBoundaries(false); + } + }, [deviceSn]); + + /** + * 移除边界 + */ + const removeBoundary = useCallback((boundaryId: string) => { + if (!viewer || viewer.isDestroyed?.()) return; + + const entityIds = boundaryEntitiesRef.current.get(boundaryId); + if (entityIds) { + entityIds.forEach(id => { + try { + viewer.entities.removeById(id); + } catch (e) { + console.warn(`移除entity ${id} 失败:`, e); + } + }); + boundaryEntitiesRef.current.delete(boundaryId); + } + + try { + viewer.scene?.requestRender?.(); + } catch { + // 忽略 + } + }, [viewer]); + + /** + * 渲染边界 + */ + const renderBoundary = useCallback((boundary: WaterBoundaryVO) => { + if (!viewer || !Cesium || viewer.isDestroyed?.()) return; + + const entityIds: string[] = []; + + try { + const normalizedBoundaryId = normalizeId((boundary as any)?.boundaryId); + if (!normalizedBoundaryId) { + message.warning('边界ID无效,无法渲染'); + return; + } + + // 清理旧记录(以 ref 为准) + removeBoundary(normalizedBoundaryId); + + // 解析 GeoJSON(兼容 Polygon / MultiPolygon / Feature / FeatureCollection) + const polygons = parseBoundaryGeoJson(boundary.polygonData); + if (!polygons.length) { + message.warning(`边界 [${boundary.boundaryName}] 数据格式错误,无法解析为多边形`); + return; + } + + // 渲染多边形 + const baseColor = getBoundaryColor(boundary.boundaryType, Cesium); + const alpha = getBoundaryAlpha(boundary.boundaryType); + + polygons.forEach((poly, index) => { + const polygonId = `layer-boundary-${normalizedBoundaryId}-polygon-${index}`; + + // 先清理同 ID 的旧实体(避免“already exists”报错) + try { + if (viewer.entities.getById?.(polygonId)) { + viewer.entities.removeById(polygonId); + } + } catch { + // 忽略 + } + + const positions = poly.outer.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)); + if (positions.length < 3) return; + + const holes = poly.holes + .map((ring) => ring.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0))) + .filter((ring) => ring.length >= 3) + .map((ring) => new Cesium.PolygonHierarchy(ring)); + + viewer.entities.add({ + id: polygonId, + polygon: { + hierarchy: new Cesium.PolygonHierarchy(positions, holes), + material: baseColor.withAlpha(alpha), + outline: true, + outlineColor: baseColor, + outlineWidth: 2, + // 为了确保在“地形”和“3D Tiles 模型”上都能显示,统一使用 BOTH + classificationType: Cesium.ClassificationType?.BOTH, + }, + properties: { + type: 'layer-boundary', + boundaryId: normalizedBoundaryId, + }, + }); + entityIds.push(polygonId); + }); + + if (!entityIds.length) { + message.warning(`边界 [${boundary.boundaryName}] 顶点不足`); + return; + } + + boundaryEntitiesRef.current.set(normalizedBoundaryId, entityIds); + console.log(`边界 [${boundary.boundaryName}] 渲染成功`); + viewer.scene?.requestRender?.(); + } catch (error) { + console.error(`渲染边界 [${boundary.boundaryName}] 失败:`, error); + message.error(`渲染边界失败`); + } + }, [viewer, Cesium, removeBoundary]); + + const applyShowInModelFromList = useCallback((list: WaterBoundaryVO[]) => { + if (!viewer || !Cesium || viewer.isDestroyed?.()) return; + clearAllBoundaryEntities(); + + const toShow = new Set(); + list.forEach((b) => { + const id = normalizeId((b as any)?.boundaryId); + if (!id) return; + if (Number((b as any)?.showInModel) === 1) { + toShow.add(id); + renderBoundary(b); + } + }); + setVisibleBoundaries(toShow); + }, [viewer, Cesium, clearAllBoundaryEntities, renderBoundary]); + + // 从后端列表应用 showInModel(仅在 loadBoundaries 成功后触发) + useEffect(() => { + const pending = pendingApplyShowInModelRef.current; + if (!pending) return; + + // 只处理最新一次请求的回写 + if (pending.requestSeq !== loadBoundariesSeqRef.current) { + pendingApplyShowInModelRef.current = null; + return; + } + + // 如果用户在请求期间已经修改过选择,则不要用这次返回覆盖当前显示 + if (pending.selectionVersionAtStart !== selectionVersionRef.current) { + pendingApplyShowInModelRef.current = null; + return; + } + + pendingApplyShowInModelRef.current = null; + applyShowInModelFromList(boundaries); + }, [boundaries, applyShowInModelFromList]); + + // 设备切换:清理上一设备边界,并加载后端持久化的 showInModel 状态 + useEffect(() => { + if (!viewer || viewer.isDestroyed?.()) return; + + const sn = normalizedDeviceSn; + if (!sn) { + currentDeviceSnRef.current = ''; + loadBoundariesSeqRef.current += 1; + pendingApplyShowInModelRef.current = null; + clearAllBoundaryEntities(); + setVisibleBoundaries(new Set()); + setBoundaries([]); + return; + } + + if (currentDeviceSnRef.current && currentDeviceSnRef.current !== sn) { + clearAllBoundaryEntities(); + setVisibleBoundaries(new Set()); + } + currentDeviceSnRef.current = sn; + + // 拉取当前设备边界列表(面板不打开也要渲染已选标绘) + loadBoundaries(sn); + }, [viewer, normalizedDeviceSn, clearAllBoundaryEntities, loadBoundaries]); + + // 保存成功后:自动显示刚创建的边界(避免编辑器关闭后边界消失) + useEffect(() => { + if (!autoShowBoundaryId) return; + if (!viewer || !Cesium || viewer.isDestroyed?.()) return; + + (async () => { + try { + const res = await getWaterBoundaryDetail(autoShowBoundaryId); + const boundary = (res as any)?.data ?? (res as any)?.datas; + if (res.resp_code !== 0 || !boundary) { + message.warning(res.resp_msg || '获取边界详情失败'); + return; + } + + // 先用边界详情里的 deviceSn 刷新列表(避免当前选择设备不一致导致列表不更新) + const boundaryDeviceSn = normalizeId(boundary.deviceSn); + await loadBoundaries(boundaryDeviceSn || undefined); + + // 若已显示则不重复渲染 + setVisibleBoundaries(prev => { + const next = new Set(prev); + next.add(autoShowBoundaryId); + return next; + }); + + renderBoundary(boundary); + viewer.scene?.requestRender?.(); + } catch (e) { + console.error('自动显示新边界失败:', e); + } finally { + onAutoShowBoundaryHandled?.(); + } + })(); + }, [autoShowBoundaryId, viewer, Cesium, loadBoundaries, renderBoundary, onAutoShowBoundaryHandled]); + + /** + * 处理边界勾选变化 + */ + const handleBoundaryCheckChange = useCallback((boundaryId: string, checked: boolean) => { + const sn = normalizedDeviceSn; + if (!sn) { + message.warning('请先选择设备'); + return; + } + + selectionVersionRef.current += 1; + + const normalizedBoundaryId = normalizeId(boundaryId); + if (!normalizedBoundaryId) return; + + const prevSet = new Set(visibleBoundaries); + const nextSet = new Set(prevSet); + + if (checked) { + const boundary = boundaries.find(b => String((b as any)?.boundaryId ?? '').trim() === normalizedBoundaryId); + if (boundary) { + // 勾选即确保渲染(renderBoundary 内部会先清理旧实体,避免重复) + renderBoundary(boundary); + nextSet.add(normalizedBoundaryId); + setVisibleBoundaries(nextSet); + } + } else { + removeBoundary(normalizedBoundaryId); + nextSet.delete(normalizedBoundaryId); + setVisibleBoundaries(nextSet); + } + + (async () => { + const ok = await persistShowInModel(sn, Array.from(nextSet)); + if (!ok) { + // 失败后以服务端为准回滚(避免本地状态与后端不一致) + await loadBoundaries(sn); + return; + } + + // 本地同步 showInModel,确保后续刷新前 UI 与后端一致 + setBoundaries((prev) => prev.map((b) => { + const id = normalizeId((b as any)?.boundaryId); + if (!id) return b; + return { ...b, showInModel: nextSet.has(id) ? 1 : 0 }; + })); + })(); + }, [normalizedDeviceSn, visibleBoundaries, boundaries, renderBoundary, removeBoundary, persistShowInModel, loadBoundaries]); + + /** + * 处理删除边界 + */ + const handleDeleteBoundary = useCallback(async (boundaryId: string, boundaryName: string) => { + try { + const res = await deleteWaterBoundary(boundaryId); + if (res.resp_code === 0) { + message.success(`边界 [${boundaryName}] 已删除`); + // 从地图移除 + removeBoundary(boundaryId); + // 从列表移除 + setBoundaries(prev => prev.filter(b => String((b as any)?.boundaryId ?? '').trim() !== boundaryId)); + // 从可见集合移除 + setVisibleBoundaries(prev => { + const next = new Set(prev); + next.delete(boundaryId); + return next; + }); + } else { + message.error(res.resp_msg || '删除失败'); + } + } catch (error) { + console.error('删除边界失败:', error); + message.error('删除边界失败'); + } + }, [removeBoundary]); + + /** + * 刷新数据 + */ + const handleRefresh = useCallback(() => { + loadBoundaries(); + }, [loadBoundaries]); + + /** + * 全部显示/隐藏边界 + */ + const handleToggleAllBoundaries = useCallback((show: boolean) => { + const sn = normalizedDeviceSn; + if (!sn) { + message.warning('请先选择设备'); + return; + } + + selectionVersionRef.current += 1; + + if (show) { + clearAllBoundaryEntities(); + boundaries.forEach(boundary => { + const normalizedBoundaryId = String((boundary as any)?.boundaryId ?? '').trim(); + if (!normalizedBoundaryId) return; + renderBoundary(boundary); + }); + const nextSet = new Set(boundaries.map(b => String((b as any)?.boundaryId ?? '').trim()).filter(Boolean)); + setVisibleBoundaries(nextSet); + try { + viewer?.scene?.requestRender?.(); + } catch { + // 忽略 + } + + (async () => { + const ok = await persistShowInModel(sn, Array.from(nextSet)); + if (!ok) { + await loadBoundaries(sn); + return; + } + setBoundaries((prev) => prev.map((b) => ({ ...b, showInModel: 1 }))); + })(); + } else { + clearAllBoundaryEntities(); + setVisibleBoundaries(new Set()); + (async () => { + const ok = await persistShowInModel(sn, []); + if (!ok) { + await loadBoundaries(sn); + return; + } + setBoundaries((prev) => prev.map((b) => ({ ...b, showInModel: 0 }))); + })(); + } + }, [normalizedDeviceSn, boundaries, renderBoundary, viewer, clearAllBoundaryEntities, persistShowInModel, loadBoundaries]); + + // 初始加载 + useEffect(() => { + if (!visible) return; + if (deviceSn) { + loadBoundaries(); + } + }, [visible, deviceSn, loadBoundaries]); + + // 组件卸载时清理所有图层(注意:不要把 visibleBoundaries 放依赖里,否则每次勾选都会触发 cleanup 误删) + useEffect(() => { + return () => { + visibleBoundariesRef.current.forEach(boundaryId => removeBoundary(boundaryId)); + }; + }, [removeBoundary]); + + if (!visible) return null; + + return ( +
+ + + 图层管理 + +
+ } + size="small" + extra={ + + {boundaries.length > 0 && ( + <> + + + + )} +
+
+ + {loadingBoundaries ? ( +
加载中...
+ ) : boundaries.length === 0 ? ( + + ) : ( + ( + + handleBoundaryCheckChange(String((boundary as any)?.boundaryId ?? '').trim(), e.target.checked)} + > + {boundary.boundaryName} + + + {boundary.boundaryType === 'navigable' && ( + 可航行 + )} + {boundary.boundaryType === 'restricted' && ( + 禁行区 + )} + {boundary.boundaryType === 'obstacle' && ( + 障碍物 + )} + {getBoundaryVertexCount(boundary)}点 + {boundary.boundaryType === 'navigable' && ( + + )} + { + e?.stopPropagation(); + handleDeleteBoundary( + String((boundary as any)?.boundaryId ?? '').trim(), + boundary.boundaryName + ); + }} + okText="确定" + cancelText="取消" + > + + + + + {/* 左侧航行数据 */} +
+
+
+ 航向角 + {boatData?.heading?.toFixed(1) ?? '--'}° +
+
+ 航行速度 + {boatData?.speed?.toFixed(1) ?? '--'}m/s +
+
+
+ + {/* 右侧位置数据 */} +
+
+
+ 经度 + {boatData?.longitude?.toFixed(6) ?? '--'} +
+
+ 纬度 + {boatData?.latitude?.toFixed(6) ?? '--'} +
+
+
+ + {/* 底部控制栏 - 简化版 */} +
+
+ + + + + + + + + + + + +
+
+ + ) : ( + /* ========== 无人机/机库界面 ========== */ + <> {/* 顶部栏 */}
@@ -858,6 +1086,8 @@ const LeftControlPanel: React.FC = ({
+ + )} ); diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/RightPanel.less b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/RightPanel.less index 336e2dff..75bb0da0 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/RightPanel.less +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/RightPanel.less @@ -64,6 +64,13 @@ } } + .headerActions { + display: flex; + align-items: center; + gap: 8px; + } + + .minimizeBtn, .closeBtn { width: 32px; height: 32px; @@ -75,12 +82,18 @@ color: rgba(255, 255, 255, 0.6); cursor: pointer; transition: all 0.3s; - - &:hover { - background: rgba(255, 50, 50, 0.2); - border-color: rgba(255, 50, 50, 0.5); - color: @neon-red; - } + } + + .minimizeBtn:hover { + background: rgba(0, 240, 255, 0.12); + border-color: rgba(0, 240, 255, 0.5); + color: @cyan; + } + + .closeBtn:hover { + background: rgba(255, 50, 50, 0.2); + border-color: rgba(255, 50, 50, 0.5); + color: @neon-red; } } } @@ -365,4 +378,4 @@ } } } -} \ No newline at end of file +} diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/RightPanel.tsx b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/RightPanel.tsx index af080a12..61e0fb2a 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/RightPanel.tsx +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/RightPanel.tsx @@ -3,6 +3,7 @@ import { Spin, Empty, message, Tooltip, Tabs, Progress, Modal } from 'antd'; import type { TabsProps } from 'antd'; import { CloseOutlined, + RightOutlined, HomeOutlined, RocketOutlined, VideoCameraOutlined, @@ -12,18 +13,26 @@ import { LoadingOutlined, AimOutlined, UnorderedListOutlined, + CompassOutlined, + EnvironmentOutlined, } from '@ant-design/icons'; import { deviceApi } from '@/services/device'; import { saveMission, MissionType } from '@/services/mission'; import useDeviceSSE from '../hooks/useDeviceSSE'; +import { useBoatSSE } from '../hooks/useBoatSSE'; +import type { BoatTelemetryData } from '@/types/boatRoute'; import styles from './RightPanel.less'; interface RightPanelProps { visible: boolean; device: any; // 直接接收选中的设备 + /** 收起到“设备面板”按钮(不清空选中设备) */ + onMinimize: () => void; + /** 关闭面板(退出设备:会清空选中设备等) */ onClose: () => void; onControlClick: (device: any, realtimeData: any) => void; onTaskPanelOpen?: (device: any, dockData: any) => void; // 打开任务管理面板回调 + onRoutePlanningOpen?: (device: any) => void; // 打开航线规划面板回调(无人船) viewer?: any; // Cesium Viewer 实例 Cesium?: any; // Cesium 库 } @@ -31,42 +40,77 @@ interface RightPanelProps { const RightPanel: React.FC = ({ visible, device, + onMinimize, onClose, onControlClick, onTaskPanelOpen, + onRoutePlanningOpen, viewer, Cesium }) => { const [takeoffLoading, setTakeoffLoading] = useState(false); + // 判断是否为无人船设备 (deviceType === 4) + const isBoatDevice = useMemo(() => device?.deviceType === 4, [device?.deviceType]); + + // 无人机/机库 SSE const { realtimeData, sseConnected, connectSSE, disconnectSSE } = useDeviceSSE(); + // 无人船 SSE + const { + boatData, + sseConnected: boatSseConnected, + connectBoatSSE, + disconnectBoatSSE, + } = useBoatSSE(); + // 当设备变化时,连接SSE useEffect(() => { if (device?.deviceSn && visible) { - connectSSE(device.deviceSn); + if (isBoatDevice) { + connectBoatSSE(device.deviceSn); + } else { + connectSSE(device.deviceSn); + } } return () => { if (device?.deviceSn) { - disconnectSSE(device.deviceSn); + if (isBoatDevice) { + disconnectBoatSSE(device.deviceSn); + } else { + disconnectSSE(device.deviceSn); + } } }; - }, [device?.deviceSn, visible]); + }, [device?.deviceSn, visible, isBoatDevice]); useEffect(() => { if (!visible && device?.deviceSn) { - disconnectSSE(device.deviceSn); + if (isBoatDevice) { + disconnectBoatSSE(device.deviceSn); + } else { + disconnectSSE(device.deviceSn); + } } - }, [visible]); + }, [visible, isBoatDevice]); // 关闭面板时,主动断开SSE连接 const handleClose = () => { if (device?.deviceSn) { - disconnectSSE(device.deviceSn); + if (isBoatDevice) { + disconnectBoatSSE(device.deviceSn); + } else { + disconnectSSE(device.deviceSn); + } } onClose(); }; + // 收起到“设备面板” + const handleMinimize = () => { + onMinimize(); + }; + const dockData = realtimeData?.rawData?.dockData; const battery = realtimeData?.battery ?? 0; @@ -173,21 +217,94 @@ const RightPanel: React.FC = ({
- + {isBoatDevice ? : } {device?.deviceName || device?.deviceSn || '设备详情'}
- {realtimeData?.online ? 'ONLINE' : 'OFFLINE'} + {isBoatDevice + ? (boatSseConnected ? 'ONLINE' : 'OFFLINE') + : (realtimeData?.online ? 'ONLINE' : 'OFFLINE') + }
- +
+ + + + + + +
{!device ? ( + ) : isBoatDevice ? ( + /* ========== 无人船设备界面 ========== */ +
+ {/* 无人船基本信息 */} +
+
+ 无人船信息 / BOAT INFO +
+ +
+
+ {device?.deviceName || device?.deviceSn} + + {boatSseConnected ? '在线' : '离线'} + +
+
+ {renderItem('设备SN', device?.deviceSn)} + {renderItem('航行状态', boatData?.status === 'executing' ? '航行中' : boatData?.status === 'paused' ? '已暂停' : '空闲', '', boatData?.status === 'executing' ? 'warning' : 'success')} + {renderItem('电池电量', boatData?.battery, '%', (boatData?.battery ?? 100) < 20 ? 'error' : 'success')} + {renderItem('信号强度', boatData?.signalStrength, '%')} + {renderItem('当前速度', boatData?.speed?.toFixed(1), 'm/s')} + {renderItem('航向角', boatData?.heading?.toFixed(1), '°')} +
+
+
+ + {/* 位置信息 */} +
+
位置信息 / POSITION
+
+ {renderItem('经度', boatData?.longitude?.toFixed(6))} + {renderItem('纬度', boatData?.latitude?.toFixed(6))} + {renderItem('当前任务', boatData?.taskId || '无')} + {renderItem('当前航点', boatData?.currentWaypointIndex !== undefined ? `第${boatData.currentWaypointIndex + 1}个` : '-')} +
+
+ + {/* 电池状态大图标 */} +
+
+
+
BATTERY
+
{boatData?.battery ?? 0}%
+
+
+ +
+
+
+ + {/* 操作区 */} +
+ +
+
) : ( + /* ========== 无人机/机库设备界面 ========== */ { switch (status) { @@ -104,10 +129,13 @@ const TaskPanel: React.FC = ({ }) => { const deviceSn = device?.deviceSn; - // 航线相关状态 - const [routeList, setRouteList] = useState([]); + // 判断是否为无人船设备 (deviceType === 4) + const isBoatDevice = useMemo(() => device?.deviceType === 4, [device?.deviceType]); + + // 航线相关状态 - 使用统一的数据类型 + const [routeList, setRouteList] = useState([]); const [selectedRouteId, setSelectedRouteId] = useState(null); - const [waypoints, setWaypoints] = useState([]); + const [waypoints, setWaypoints] = useState([]); const [routeLoading, setRouteLoading] = useState(false); // 任务相关状态 @@ -171,17 +199,6 @@ const TaskPanel: React.FC = ({ } }, [visible, deviceSn]); - // 调试:监测 props 变化 - useEffect(() => { - console.log('[TaskPanel] props变化:', { - visible, - hasViewer: !!viewer, - hasCesium: !!Cesium, - deviceSn, - hasDroneData: !!droneData, - }); - }, [visible, viewer, Cesium, deviceSn, droneData]); - // 飞到无人机位置 const flyToDrone = useCallback(() => { if (!viewer || !Cesium || !realtimePosition) { @@ -211,20 +228,76 @@ const TaskPanel: React.FC = ({ message.success('已飞到无人机位置'); }, [viewer, Cesium, realtimePosition]); - // 加载航线列表 + // 加载航线列表 - 根据设备类型调用不同的API const loadRoutesByDevice = useCallback(async (sn: string) => { try { setRouteLoading(true); - const res = await waylineRouteApi.getRouteListByDevice(sn); - if (res.resp_code === 0) { - setRouteList(res.data || []); + + if (isBoatDevice) { + // 无人船航线 + const res = await getBoatRoutesByDevice(sn); + const list = (res as any)?.datas ?? (res as any)?.data; + if (res.resp_code === 0 && Array.isArray(list)) { + // 转换为统一格式 + const unifiedRoutes: UnifiedRouteItem[] = list.map((route: BoatRouteListVO) => ({ + routeId: route.routeId, + routeName: route.routeName, + waypointCount: route.waypointCount, + totalDistance: route.totalDistance, + totalDuration: route.totalDuration, + totalDurationStr: route.totalDurationStr, + deviceSn: route.deviceSn, + deviceName: route.deviceName, + routeType: 'boat' as const, + })); + setRouteList(unifiedRoutes); + + // 默认选中第一条,并绘制到模型上(仅首次进入或未选中时) + if (!selectedRouteId && unifiedRoutes.length > 0) { + const first = unifiedRoutes[0]; + setSelectedRouteId(first.routeId); + loadWaypoints(first.routeId, first.routeType); + } + } else { + console.warn('[TaskPanel] 加载无人船航线失败:', res); + setRouteList([]); + } + } else { + // 无人机航线 + const res = await waylineRouteApi.getRouteListByDevice(sn); + const list = (res as any)?.datas ?? (res as any)?.data; + if (res.resp_code === 0 && Array.isArray(list)) { + // 转换为统一格式 + const unifiedRoutes: UnifiedRouteItem[] = list.map((route: WaylineRouteListItemVO) => ({ + routeId: route.routeId, + routeName: route.routeName, + waypointCount: route.waypointCount, + totalDistance: route.totalDistance, + totalDuration: route.totalDuration, + deviceSn: route.deviceSn, + deviceName: route.deviceName, + routeType: 'drone' as const, + })); + setRouteList(unifiedRoutes); + + if (!selectedRouteId && unifiedRoutes.length > 0) { + const first = unifiedRoutes[0]; + setSelectedRouteId(first.routeId); + loadWaypoints(first.routeId, first.routeType); + } + } else { + console.warn('[TaskPanel] 加载无人机航线失败:', res); + setRouteList([]); + } } } catch (e) { + console.error('[TaskPanel] 加载航线列表失败:', e); message.error('加载航线列表失败'); + setRouteList([]); } finally { setRouteLoading(false); } - }, []); + }, [isBoatDevice, selectedRouteId, loadWaypoints]); // 加载任务列表 const loadMissionsByDevice = useCallback(async (sn: string) => { @@ -248,54 +321,177 @@ const TaskPanel: React.FC = ({ } }, []); - // 加载航点并绘制 - const loadWaypoints = useCallback(async (routeId: string) => { + // 加载航点并绘制 - 根据航线类型调用不同的API + const loadWaypoints = useCallback(async (routeId: string, routeTypeOverride?: UnifiedRouteItem['routeType']) => { try { - const res = await waylineRouteApi.getRouteWaypoints(routeId); - if (res.resp_code === 0 && res.data?.length) { - setWaypoints(res.data); - if (viewer && Cesium) { - drawWaylineOnMap(res.data); + const selectedRoute = routeList.find(r => r.routeId === routeId); + const routeType = routeTypeOverride || selectedRoute?.routeType || (isBoatDevice ? 'boat' : 'drone'); + + if (routeType === 'boat') { + // 加载无人船航点 + const res = await getBoatRouteDetail(routeId); + const payload = (res as any)?.datas ?? (res as any)?.data; + if (res.resp_code === 0 && payload?.waypoints?.length) { + // 转换为统一格式 + const unifiedWaypoints: UnifiedWaypoint[] = payload.waypoints.map((wp: BoatWaypointVO) => ({ + index: wp.waypointIndex, + longitude: wp.longitude, + latitude: wp.latitude, + height: 0, // 无人船航线高度为0 + speed: wp.speed, + waypointType: 'boat' as const, + })); + setWaypoints(unifiedWaypoints); + if (viewer && Cesium) { + await drawWaylineOnMap(unifiedWaypoints); + } + } else { + console.warn('[TaskPanel] 加载无人船航点失败:', res); + } + } else { + // 加载无人机航点 + const res = await waylineRouteApi.getRouteWaypoints(routeId); + const list = (res as any)?.datas ?? (res as any)?.data; + if (res.resp_code === 0 && Array.isArray(list) && list.length) { + // 转换为统一格式 + const unifiedWaypoints: UnifiedWaypoint[] = list.map((wp: WaypointVO) => ({ + index: wp.index, + longitude: wp.longitude, + latitude: wp.latitude, + height: wp.height, + speed: wp.speed, + waypointType: 'drone' as const, + })); + setWaypoints(unifiedWaypoints); + if (viewer && Cesium) { + await drawWaylineOnMap(unifiedWaypoints); + } + } else { + console.warn('[TaskPanel] 加载无人机航点失败:', res); } } } catch (e) { + console.error('[TaskPanel] 加载航点失败:', e); message.error('加载航点失败'); } - }, [viewer, Cesium]); + }, [viewer, Cesium, routeList, drawWaylineOnMap, isBoatDevice]); - // 绘制航线 - const drawWaylineOnMap = useCallback((waypoints: WaypointVO[]) => { + // 绘制航线 - 支持无人机和无人船航线,使用clampToHeightMostDetailed贴模型 + const drawWaylineOnMap = useCallback(async (waypoints: UnifiedWaypoint[]) => { if (!viewer || !Cesium || !waypoints.length) return; clearWaylineEntities(); - // 调试:打印航点高度信息 - console.log('[航线绘制] 航点数量:', waypoints.length); - console.log('[航线绘制] 前3个航点:', waypoints.slice(0, 3).map(wp => ({ - index: wp.index, - lng: wp.longitude, - lat: wp.latitude, - height: wp.height, - ellipsoidHeight: wp.ellipsoidHeight, - }))); + const isBoatRoute = waypoints[0].waypointType === 'boat'; - // 使用 height(相对高度) - const positions = waypoints.map(wp => - Cesium.Cartesian3.fromDegrees( - wp.longitude, - wp.latitude, - wp.height ?? 100 - ) + // 检查航点数据有效性 + const validWaypoints = waypoints.filter(wp => + Number.isFinite(wp.longitude) && + Number.isFinite(wp.latitude) && + Math.abs(wp.longitude) <= 180 && + Math.abs(wp.latitude) <= 90 ); - // 计划航线(蓝色)- 使用简单的实线,加粗 + if (validWaypoints.length !== waypoints.length) { + console.error('[航线绘制] 发现无效航点!有效:', validWaypoints.length, '总数:', waypoints.length); + message.error('航线数据异常,部分航点无效'); + return; + } + + if (validWaypoints.length < 2) { + message.warning('航点数量不足,无法绘制航线'); + return; + } + + // 准备航点位置(空中300米,用于clamp) + const waypointPositionsAbove = waypoints.map(wp => + Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 300) + ); + + // 准备航线密集化点(用于更平滑的航线) + const densifiedPoints: any[] = []; + for (let i = 0; i < waypoints.length - 1; i++) { + const a = waypoints[i]; + const b = waypoints[i + 1]; + const ca = Cesium.Cartographic.fromDegrees(a.longitude, a.latitude, 300); + const cb = Cesium.Cartographic.fromDegrees(b.longitude, b.latitude, 300); + const geodesic = new Cesium.EllipsoidGeodesic(ca, cb); + const dist = Number(geodesic.surfaceDistance) || 0; + + // 每段采样点数 + const segments = Math.max(2, Math.min(60, Math.ceil(dist / 8))); + for (let s = 0; s <= segments; s++) { + if (i > 0 && s === 0) continue; // 避免重复点 + const frac = segments === 0 ? 0 : s / segments; + const c = geodesic.interpolateUsingFraction(frac); + c.height = 300; + densifiedPoints.push(Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, c.height)); + } + } + + let waypointPositions = waypointPositionsAbove; + let polylinePositions = densifiedPoints.length >= 2 ? densifiedPoints : waypointPositionsAbove; + + // 如果是无人船航线,尝试贴模型表面 + if (isBoatRoute && viewer.scene?.clampToHeightMostDetailed) { + try { + // 贴航点 + const clampedWaypoints = await viewer.scene.clampToHeightMostDetailed(waypointPositionsAbove); + if (clampedWaypoints && clampedWaypoints.length === waypoints.length) { + waypointPositions = clampedWaypoints.map((p: any) => { + if (!p) return null; + const carto = Cesium.Cartographic.fromCartesian(p); + carto.height = (Number(carto.height) || 0) + 0.05; // 抬高5cm,避免Z-fighting + return Cesium.Cartesian3.fromRadians(carto.longitude, carto.latitude, carto.height); + }).filter(Boolean); + } + + // 贴航线 + if (densifiedPoints.length >= 2) { + const clampedLine = await viewer.scene.clampToHeightMostDetailed(densifiedPoints); + if (clampedLine && clampedLine.length >= 2) { + polylinePositions = clampedLine.map((p: any) => { + if (!p) return null; + const carto = Cesium.Cartographic.fromCartesian(p); + carto.height = (Number(carto.height) || 0) + 0.05; // 抬高5cm,避免Z-fighting + return Cesium.Cartesian3.fromRadians(carto.longitude, carto.latitude, carto.height); + }).filter(Boolean); + } + } + } catch (e) { + console.warn('[航线绘制] 贴模型表面失败,使用默认高度:', e); + // 失败则使用地面高度 + waypointPositions = waypoints.map(wp => + Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0.05) + ); + polylinePositions = waypoints.map(wp => + Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0.05) + ); + } + } else if (!isBoatRoute) { + // 无人机航线,使用指定高度 + waypointPositions = waypoints.map(wp => + Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, wp.height ?? 100) + ); + polylinePositions = waypoints.map(wp => + Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, wp.height ?? 100) + ); + } + + // 根据航线类型选择颜色 + const routeColor = isBoatRoute + ? Cesium.Color.fromCssColorString('#52c41a').withAlpha(0.9) // 绿色 - 无人船 + : Cesium.Color.fromCssColorString('#1890ff').withAlpha(0.9); // 蓝色 - 无人机 + + // 绘制航线 waylineEntityRef.current = viewer.entities.add({ - name: '计划航线', + name: isBoatRoute ? '无人船航线' : '无人机航线', polyline: { - positions: positions, + positions: polylinePositions, width: 6, - material: Cesium.Color.fromCssColorString('#1890ff').withAlpha(0.9), - clampToGround: false, + material: routeColor, + clampToGround: false, // 已经手动贴地,不需要clampToGround + arcType: Cesium.ArcType?.NONE, }, }); @@ -307,12 +503,16 @@ const TaskPanel: React.FC = ({ const isFirst = index === 0; const isLast = index === totalPoints - 1; const isKeyPoint = isFirst || isLast || (index % labelInterval === 0); - const pointColor = isFirst ? '#0050b3' : isLast ? '#722ed1' : '#1890ff'; - const altitude = wp.height ?? 100; + const pointColor = isBoatRoute + ? (isFirst ? '#389e0d' : isLast ? '#237804' : '#52c41a') // 绿色系 - 无人船 + : (isFirst ? '#0050b3' : isLast ? '#722ed1' : '#1890ff'); // 蓝色系 - 无人机 + + const position = waypointPositions[index]; + if (!position) return; const entity = viewer.entities.add({ name: `航点${index + 1}`, - position: Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, altitude), + position: position, point: { pixelSize: isKeyPoint ? 12 : 8, color: Cesium.Color.fromCssColorString(pointColor), @@ -335,51 +535,70 @@ const TaskPanel: React.FC = ({ waypointEntitiesRef.current.push(entity); }); - // 飞到航线 - flyToWayline(waypoints); - }, [viewer, Cesium]); + // 飞到航线,传递渲染后的positions用于精确计算视角 + flyToWayline(waypoints, polylinePositions.length >= 2 ? polylinePositions : waypointPositions); + }, [viewer, Cesium, flyToWayline, clearWaylineEntities]); - // 飞到航线位置 - 垂直俯视整条航线 - const flyToWayline = useCallback((waypoints: WaypointVO[]) => { + // 飞到航线位置 - 参考航线规划页面的实现 + const flyToWayline = useCallback((waypoints: UnifiedWaypoint[], positions?: any[]) => { if (!viewer || !Cesium || !waypoints.length) return; - let minLon = Infinity, maxLon = -Infinity; - let minLat = Infinity, maxLat = -Infinity; - let maxHeight = 0; + try { + // 优先使用实际渲染的positions(已经贴模型表面的点) + const points = positions && positions.length >= 2 ? positions : null; - waypoints.forEach(wp => { - minLon = Math.min(minLon, wp.longitude); - maxLon = Math.max(maxLon, wp.longitude); - minLat = Math.min(minLat, wp.latitude); - maxLat = Math.max(maxLat, wp.latitude); - maxHeight = Math.max(maxHeight, wp.height || 100); - }); + if (points && Cesium.BoundingSphere?.fromPoints) { + // 使用边界球方式(与航线规划页面一致) + const bs = Cesium.BoundingSphere.fromPoints(points); + const radius = Number(bs.radius) || 0; - const centerLon = (minLon + maxLon) / 2; - const centerLat = (minLat + maxLat) / 2; + // 调整视距:半径的1.5倍,最小100米(更近的视角) + const range = Math.max(100, radius * 1.5); - // 计算航线范围的对角线距离(经纬度转换为大约的米数) - const lonSpan = maxLon - minLon; - const latSpan = maxLat - minLat; - // 1度经度约111km(在赤道),纬度方向约111km - const spanMeters = Math.sqrt( - Math.pow(lonSpan * 111000 * Math.cos(centerLat * Math.PI / 180), 2) + - Math.pow(latSpan * 111000, 2) - ); + viewer.camera.flyToBoundingSphere(bs, { + duration: 1.2, + offset: new Cesium.HeadingPitchRange( + 0, // 重置heading为正北 + Cesium.Math.toRadians(-45), + range + ), + }); + } else { + // 回退:使用矩形范围 + let minLon = Infinity, maxLon = -Infinity; + let minLat = Infinity, maxLat = -Infinity; - // 视角高度:航线范围的0.2倍 + 最高航点高度 - // 更贴近航线 - const viewHeight = Math.max(spanMeters * 0.2, 30) + maxHeight; + waypoints.forEach(wp => { + minLon = Math.min(minLon, wp.longitude); + maxLon = Math.max(maxLon, wp.longitude); + minLat = Math.min(minLat, wp.latitude); + maxLat = Math.max(maxLat, wp.latitude); + }); - viewer.camera.flyTo({ - destination: Cesium.Cartesian3.fromDegrees(centerLon, centerLat, viewHeight), - orientation: { - heading: 0, - pitch: Cesium.Math.toRadians(-90), // 垂直俯视,确保航迹在正下方 - roll: 0, - }, - duration: 1.5, - }); + // 添加20%的padding,确保能看到整条航线 + const lonSpan = maxLon - minLon; + const latSpan = maxLat - minLat; + const paddingLon = Math.max(lonSpan * 0.2, 0.001); // 至少0.001度 + const paddingLat = Math.max(latSpan * 0.2, 0.001); + + viewer.camera.flyTo({ + destination: Cesium.Rectangle.fromDegrees( + minLon - paddingLon, + minLat - paddingLat, + maxLon + paddingLon, + maxLat + paddingLat + ), + orientation: { + heading: 0, + pitch: Cesium.Math.toRadians(-45), + roll: 0, + }, + duration: 1.0, + }); + } + } catch (e) { + console.error('[航线视角] 飞到航线失败:', e); + } }, [viewer, Cesium]); // 检查 viewer 是否有效 @@ -785,7 +1004,13 @@ const TaskPanel: React.FC = ({
预计时长 - {Math.ceil(selectedRoute.totalDuration / 60)} 分钟 + + {selectedRoute.totalDurationStr + ? selectedRoute.totalDurationStr + : (selectedRoute.totalDuration && Number.isFinite(selectedRoute.totalDuration) && selectedRoute.totalDuration > 0 + ? `${Math.ceil(selectedRoute.totalDuration / 60)} 分钟` + : '--')} +
@@ -827,15 +1052,15 @@ const TaskPanel: React.FC = ({
- 计划航线 + 无人机航线
- 飞行轨迹 + 无人船航线
- 无人机 + 实时位置
diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useBoatSSE.ts b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useBoatSSE.ts new file mode 100644 index 00000000..a1ab578e --- /dev/null +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useBoatSSE.ts @@ -0,0 +1,318 @@ +/** + * 无人船遥测数据SSE Hook + * @author dzc + * @date 2026-01-05 + */ +import { useState, useRef, useEffect, useCallback } from 'react'; +import { notification } from 'antd'; +import type { BoatTelemetryData } from '@/types/boatRoute'; + +const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30分钟无操作断开 + +export interface UseBoatSSEReturn { + boatData: BoatTelemetryData | null; + sseConnected: boolean; + loading: boolean; + hasData: boolean; + isIdleDisconnected: boolean; + connectBoatSSE: (deviceSn: string) => Promise; + disconnectBoatSSE: (deviceSn?: string) => Promise; + resetBoatData: () => void; +} + +export const useBoatSSE = (): UseBoatSSEReturn => { + const [boatData, setBoatData] = useState(null); + const [sseConnected, setSSEConnected] = useState(false); + const [loading, setLoading] = useState(false); + const [hasData, setHasData] = useState(false); + const [isIdleDisconnected, setIsIdleDisconnected] = useState(false); + + const abortControllerRef = useRef(null); + const currentDeviceSnRef = useRef(''); + const clientSessionIdRef = useRef( + `boat_client_${Date.now()}_${Math.random().toString(36).substring(2, 9)}` + ); + const dataReceivedRef = useRef(false); + const reconnectTimerRef = useRef(null); + const reconnectAttemptsRef = useRef(0); + const maxReconnectAttempts = 10; + const shouldReconnectRef = useRef(true); + const idleTimerRef = useRef(null); + + const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => { + if (!deviceSn || !token) return; + const deleteUrl = `/api-device/sse/boat/telemetry/${deviceSn}`; + fetch(deleteUrl, { + method: 'DELETE', + headers: { + 'Authorization': `Bearer ${token}`, + 'X-Client-Session-Id': sessionId, + }, + keepalive: true, + }).catch(() => {}); + }; + + const performBeaconDisconnect = (deviceSn: string, sessionId: string) => { + if (!deviceSn) return; + const beaconUrl = `/api-device/sse/boat/telemetry/${deviceSn}/disconnect`; + if (navigator.sendBeacon) { + const blob = new Blob([JSON.stringify({ sessionId })], { type: 'application/json' }); + navigator.sendBeacon(beaconUrl, blob); + } + }; + + const disconnectBoatSSE = useCallback(async (deviceSn?: string) => { + const snToDisconnect = deviceSn || currentDeviceSnRef.current; + shouldReconnectRef.current = false; + + if (reconnectTimerRef.current) { + clearTimeout(reconnectTimerRef.current); + reconnectTimerRef.current = null; + } + + if (abortControllerRef.current) { + abortControllerRef.current.abort(); + abortControllerRef.current = null; + } + + if (snToDisconnect) { + const token = sessionStorage.getItem('access_token'); + performDisconnect(snToDisconnect, clientSessionIdRef.current, token); + } + + setSSEConnected(false); + setLoading(false); + setHasData(false); + dataReceivedRef.current = false; + currentDeviceSnRef.current = ''; + reconnectAttemptsRef.current = 0; + }, []); + + const disconnectDueToIdle = useCallback(() => { + setIsIdleDisconnected(true); + shouldReconnectRef.current = false; + disconnectBoatSSE(); + notification.warning({ + message: '页面长时间未操作', + description: '已断开无人船实时数据连接,请刷新页面重新连接', + duration: 0, + key: 'boat-page-idle-warning', + }); + }, [disconnectBoatSSE]); + + const resetIdleTimer = useCallback(() => { + if (isIdleDisconnected) return; + if (idleTimerRef.current) { + clearTimeout(idleTimerRef.current); + } + if (currentDeviceSnRef.current) { + idleTimerRef.current = setTimeout(() => { + disconnectDueToIdle(); + }, IDLE_TIMEOUT_MS); + } + }, [isIdleDisconnected, disconnectDueToIdle]); + + useEffect(() => { + const activityEvents = ['mousedown', 'mousemove', 'keydown', 'scroll', 'touchstart', 'click']; + const handleActivity = () => resetIdleTimer(); + activityEvents.forEach(event => { + window.addEventListener(event, handleActivity, { passive: true }); + }); + resetIdleTimer(); + return () => { + activityEvents.forEach(event => { + window.removeEventListener(event, handleActivity); + }); + if (idleTimerRef.current) { + clearTimeout(idleTimerRef.current); + } + }; + }, [resetIdleTimer]); + + const handleSSEEvent = useCallback((eventName: string, data: string) => { + try { + if (eventName === 'connected') { + setSSEConnected(true); + setLoading(false); + } else if (eventName === 'boat-telemetry') { + const parsedData = JSON.parse(data) as BoatTelemetryData; + setBoatData(parsedData); + if (!dataReceivedRef.current) { + dataReceivedRef.current = true; + setHasData(true); + } + } + } catch {} + }, []); + + const scheduleReconnect = useCallback((deviceSn: string) => { + if (!shouldReconnectRef.current) return; + if (reconnectAttemptsRef.current >= maxReconnectAttempts) return; + + reconnectAttemptsRef.current++; + const delay = Math.min(2000 * Math.pow(1.5, reconnectAttemptsRef.current - 1), 30000); + + reconnectTimerRef.current = setTimeout(() => { + if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) { + doConnect(deviceSn); + } + }, delay); + }, []); + + const doConnect = useCallback(async (deviceSn: string) => { + if (!deviceSn) return; + setLoading(true); + + try { + const token = sessionStorage.getItem('access_token'); + const url = `/api-device/sse/boat/telemetry/${deviceSn}`; + + const abortController = new AbortController(); + abortControllerRef.current = abortController; + + const response = await fetch(url, { + method: 'GET', + headers: { + 'Accept': 'text/event-stream', + 'Cache-Control': 'no-cache', + 'Authorization': `Bearer ${token}`, + 'X-Client-Session-Id': clientSessionIdRef.current, + }, + cache: 'no-store', + signal: abortController.signal, + }); + + if (!response.ok) { + throw new Error(`SSE连接失败: ${response.status}`); + } + + reconnectAttemptsRef.current = 0; + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + if (!reader) { + throw new Error('无法获取SSE流读取器'); + } + + let buffer = ''; + + const readStream = async () => { + try { + while (true) { + const { done, value } = await reader.read(); + + if (done) { + setSSEConnected(false); + if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) { + scheduleReconnect(deviceSn); + } + break; + } + + buffer += decoder.decode(value, { stream: true }); + const lines = buffer.split('\n'); + buffer = lines.pop() || ''; + + let eventName = 'message'; + let data = ''; + + for (const line of lines) { + if (line.startsWith('event:')) { + eventName = line.substring(6).trim(); + } else if (line.startsWith('data:')) { + data = line.substring(5).trim(); + } else if (line === '') { + if (data) { + handleSSEEvent(eventName, data); + } + eventName = 'message'; + data = ''; + } + } + } + } catch (error: any) { + if (error?.name === 'AbortError') return; + setSSEConnected(false); + setLoading(false); + if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) { + scheduleReconnect(deviceSn); + } + } + }; + + readStream(); + } catch (error: any) { + if (error?.name === 'AbortError') return; + setSSEConnected(false); + setLoading(false); + if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) { + scheduleReconnect(deviceSn); + } + } + }, [handleSSEEvent, scheduleReconnect]); + + const connectBoatSSE = useCallback(async (deviceSn: string) => { + if (currentDeviceSnRef.current && currentDeviceSnRef.current !== deviceSn) { + await disconnectBoatSSE(currentDeviceSnRef.current); + } + + if (!deviceSn) return; + + setBoatData(null); + setHasData(false); + dataReceivedRef.current = false; + currentDeviceSnRef.current = deviceSn; + shouldReconnectRef.current = true; + reconnectAttemptsRef.current = 0; + setIsIdleDisconnected(false); + + doConnect(deviceSn); + resetIdleTimer(); + }, [disconnectBoatSSE, doConnect, resetIdleTimer]); + + const resetBoatData = useCallback(() => { + setBoatData(null); + setHasData(false); + dataReceivedRef.current = false; + }, []); + + useEffect(() => { + const handleBeforeUnload = () => { + if (currentDeviceSnRef.current) { + performBeaconDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current); + } + }; + window.addEventListener('beforeunload', handleBeforeUnload); + return () => { + window.removeEventListener('beforeunload', handleBeforeUnload); + }; + }, []); + + useEffect(() => { + return () => { + if (reconnectTimerRef.current) { + clearTimeout(reconnectTimerRef.current); + } + shouldReconnectRef.current = false; + if (currentDeviceSnRef.current) { + const token = sessionStorage.getItem('access_token'); + performDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current, token); + } + if (abortControllerRef.current) { + abortControllerRef.current.abort(); + } + }; + }, []); + + return { + boatData, + sseConnected, + loading, + hasData, + isIdleDisconnected, + connectBoatSSE, + disconnectBoatSSE, + resetBoatData, + }; +}; diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useCesiumBoatTrack.ts b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useCesiumBoatTrack.ts new file mode 100644 index 00000000..662c537b --- /dev/null +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useCesiumBoatTrack.ts @@ -0,0 +1,279 @@ +/** + * 无人船实时轨迹Cesium渲染Hook + * 用于在3D地图上实时显示无人船位置和轨迹 + * @author Claude + * @date 2026-01-06 + */ +import { useEffect, useRef, useCallback, useMemo } from 'react'; +import { useBoatSSE } from './useBoatSSE'; + +interface UseCesiumBoatTrackOptions { + viewerRef: React.RefObject; + enabled: boolean; + deviceSn: string | null; +} + +export function useCesiumBoatTrack({ + viewerRef, + enabled, + deviceSn, +}: UseCesiumBoatTrackOptions) { + const { boatData, connectBoatSSE, disconnectBoatSSE } = useBoatSSE(); + + // Entity引用 + const boatEntityRef = useRef(null); + const trackEntityRef = useRef(null); + const trackPositionsRef = useRef([]); + + // 控制相机自动飞行(仅首次) + const hasFlownToBoatRef = useRef(false); + + // 节流控制 + const lastUpdateTimeRef = useRef(0); + const lastPositionRef = useRef<{ lon: number; lat: number } | null>(null); + + /** + * 获取Cesium对象 + */ + const getCesium = useCallback(() => { + return (window as any).Cesium; + }, []); + + /** + * 飞到无人船位置 + */ + const flyToBoat = useCallback(() => { + const viewer = viewerRef.current; + const Cesium = getCesium(); + if (!viewer || !Cesium || viewer.isDestroyed?.()) return; + if (!boatData?.longitude || !boatData?.latitude) return; + + try { + viewer.camera.flyTo({ + destination: Cesium.Cartesian3.fromDegrees( + boatData.longitude, + boatData.latitude, + 1000 // 视角高度1000米 + ), + orientation: { + heading: 0, + pitch: Cesium.Math.toRadians(-45), // 45度俯视 + roll: 0, + }, + duration: 1.5, + }); + } catch (error) { + console.error('[useCesiumBoatTrack] 飞行到船位置失败:', error); + } + }, [viewerRef, boatData, getCesium]); + + /** + * 清除轨迹和船位置Entity + */ + const clearTrack = useCallback(() => { + const viewer = viewerRef.current; + if (!viewer || viewer.isDestroyed?.()) return; + + try { + if (boatEntityRef.current) { + viewer.entities.remove(boatEntityRef.current); + boatEntityRef.current = null; + } + + if (trackEntityRef.current) { + viewer.entities.remove(trackEntityRef.current); + trackEntityRef.current = null; + } + + trackPositionsRef.current = []; + hasFlownToBoatRef.current = false; + lastUpdateTimeRef.current = 0; + lastPositionRef.current = null; + + console.log('[useCesiumBoatTrack] 清除无人船轨迹'); + } catch (error) { + console.error('[useCesiumBoatTrack] 清除轨迹失败:', error); + } + }, [viewerRef]); + + /** + * 订阅/取消SSE连接 + */ + useEffect(() => { + if (enabled && deviceSn) { + console.log('[useCesiumBoatTrack] 开始订阅无人船SSE:', deviceSn); + connectBoatSSE(deviceSn); + } else { + console.log('[useCesiumBoatTrack] 断开无人船SSE'); + disconnectBoatSSE(); + clearTrack(); + } + + return () => { + disconnectBoatSSE(); + }; + }, [enabled, deviceSn, connectBoatSSE, disconnectBoatSSE, clearTrack]); + + /** + * 计算实时位置数据 + */ + const realtimePosition = useMemo(() => { + if (!boatData) return null; + return { + longitude: boatData.longitude, + latitude: boatData.latitude, + heading: boatData.heading ?? 0, + speed: boatData.speed ?? 0, + battery: boatData.battery ?? 0, + timestamp: Date.now(), + }; + }, [boatData]); + + /** + * 渲染无人船实时位置和轨迹 + */ + useEffect(() => { + const viewer = viewerRef.current; + const Cesium = getCesium(); + + if (!viewer || !Cesium || viewer.isDestroyed?.()) return; + if (!realtimePosition) return; + if (!realtimePosition.longitude || !realtimePosition.latitude) return; + + const now = Date.now(); + const currentPos = { + lon: realtimePosition.longitude, + lat: realtimePosition.latitude, + }; + + // 节流:1秒内且位置没变化则跳过 + const timeSinceLastUpdate = now - lastUpdateTimeRef.current; + const lastPos = lastPositionRef.current; + + if (lastPos && timeSinceLastUpdate < 1000) { + const posChanged = + Math.abs(currentPos.lon - lastPos.lon) > 0.00001 || + Math.abs(currentPos.lat - lastPos.lat) > 0.00001; + + if (!posChanged) { + return; + } + } + + // 更新时间和位置记录 + lastUpdateTimeRef.current = now; + lastPositionRef.current = currentPos; + + try { + const position = Cesium.Cartesian3.fromDegrees( + realtimePosition.longitude, + realtimePosition.latitude, + 0 // 无人船在水面,高度为0 + ); + + // 构建标签文本 + const labelText = [ + '无人船', + `航向:${realtimePosition.heading.toFixed(0)}°`, + `速度:${realtimePosition.speed.toFixed(1)}m/s`, + `电量:${realtimePosition.battery}%`, + ].join(' '); + + // 更新或创建船位置Entity + if (boatEntityRef.current) { + boatEntityRef.current.position = position; + if (boatEntityRef.current.label) { + boatEntityRef.current.label.text = labelText; + } + } else { + boatEntityRef.current = viewer.entities.add({ + name: '无人船实时位置', + position: position, + point: { + pixelSize: 16, + color: Cesium.Color.BLUE, + outlineColor: Cesium.Color.WHITE, + outlineWidth: 3, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + label: { + text: labelText, + font: '14px sans-serif', + fillColor: Cesium.Color.WHITE, + style: Cesium.LabelStyle.FILL_AND_OUTLINE, + outlineWidth: 2, + outlineColor: Cesium.Color.BLACK, + verticalOrigin: Cesium.VerticalOrigin.BOTTOM, + pixelOffset: new Cesium.Cartesian2(0, -20), + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + properties: { + type: 'boat-realtime', + deviceSn: deviceSn, + }, + }); + console.log('[useCesiumBoatTrack] 创建无人船Entity'); + } + + // 添加到轨迹 + trackPositionsRef.current.push(position); + + // 限制轨迹点数量(最多保留最近500个点,避免内存泄漏) + if (trackPositionsRef.current.length > 500) { + trackPositionsRef.current = trackPositionsRef.current.slice(-500); + } + + // 绘制飞行轨迹(至少2个点才能绘制线) + if (trackPositionsRef.current.length >= 2) { + if (trackEntityRef.current) { + trackEntityRef.current.polyline.positions = [...trackPositionsRef.current]; + } else { + trackEntityRef.current = viewer.entities.add({ + name: '无人船航行轨迹', + polyline: { + positions: [...trackPositionsRef.current], + width: 4, + material: new Cesium.PolylineGlowMaterialProperty({ + glowPower: 0.3, + color: Cesium.Color.BLUE, + }), + clampToGround: true, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + properties: { + type: 'boat-track', + deviceSn: deviceSn, + }, + }); + console.log('[useCesiumBoatTrack] 创建无人船轨迹Entity'); + } + } + + // 强制渲染 + viewer.scene.requestRender(); + + // 首次收到位置数据时,自动飞到无人船位置 + if (!hasFlownToBoatRef.current && trackPositionsRef.current.length === 1) { + hasFlownToBoatRef.current = true; + flyToBoat(); + } + } catch (error) { + console.error('[useCesiumBoatTrack] 更新无人船位置出错:', error); + } + }, [realtimePosition, viewerRef, deviceSn, getCesium, flyToBoat]); + + /** + * 组件卸载时清理 + */ + useEffect(() => { + return () => { + clearTrack(); + }; + }, [clearTrack]); + + return { + boatData, + clearTrack, + flyToBoat, + }; +} diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useTilesetLoader.ts b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useTilesetLoader.ts index 6b177598..214ae9d9 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useTilesetLoader.ts +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/hooks/useTilesetLoader.ts @@ -93,12 +93,12 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { }); try { - // 处理跨域问题:开发环境 (localhost) 将 CDN URL 转换为代理路径 + // 处理跨域问题:非 localhost 访问时将 CDN URL 转换为代理路径 let tilesetUrl = config.url; const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'; - if (isLocalhost && tilesetUrl.includes('minicdn.goflytec.com')) { + if (!isLocalhost && tilesetUrl.includes('minicdn.goflytec.com')) { tilesetUrl = tilesetUrl.replace('https://minicdn.goflytec.com', ''); - console.log('[Tileset] 开发环境使用代理路径:', tilesetUrl); + console.log('[Tileset] 使用代理路径:', tilesetUrl); } // 创建3DTileset - 高清晰度渲染配置 @@ -223,7 +223,12 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { } } - // 添加到场景 + // 添加到场景前检查viewer是否仍然有效 + if (!viewer || viewer.isDestroyed?.() || !viewer.scene) { + console.warn(`模型 [${config.name}] 加载完成,但viewer已销毁,跳过添加`); + return null; + } + viewer.scene.primitives.add(tileset); // 存储引用 @@ -267,7 +272,7 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { */ const unloadTileset = useCallback((id: string, viewer: any) => { const tileset = tilesetsRef.current.get(id); - if (tileset && viewer) { + if (tileset && viewer && !viewer.isDestroyed?.() && viewer.scene) { viewer.scene.primitives.remove(tileset); tilesetsRef.current.delete(id); @@ -285,7 +290,7 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { * 卸载所有模型 */ const unloadAllTilesets = useCallback((viewer: any) => { - if (!viewer) return; + if (!viewer || viewer.isDestroyed?.() || !viewer.scene) return; tilesetsRef.current.forEach((tileset, id) => { viewer.scene.primitives.remove(tileset); @@ -301,7 +306,7 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => { */ const flyToTileset = useCallback((id: string, viewer: any, Cesium: any) => { const tileset = tilesetsRef.current.get(id); - if (!tileset || !viewer || !Cesium) return; + if (!tileset || !viewer || !Cesium || viewer.isDestroyed?.() || !viewer.camera) return; const boundingSphere = tileset.boundingSphere; const center = boundingSphere.center; diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/CesiumContainer.tsx b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/CesiumContainer.tsx index 0871c05a..f3a72bcc 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/CesiumContainer.tsx +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/CesiumContainer.tsx @@ -1,13 +1,16 @@ import React, { useEffect, useRef, useState, useCallback, useMemo } from 'react'; import { message, Button, Tooltip } from 'antd'; -import { AppstoreOutlined } from '@ant-design/icons'; +import { AppstoreOutlined, BarsOutlined, ProfileOutlined, EditOutlined } from '@ant-design/icons'; import RightPanel from './3d/BottomPanel/RightPanel'; import LeftControlPanel from './3d/BottomPanel/LeftControlPanel'; import TaskPanel from './3d/BottomPanel/TaskPanel'; -import TilesetPanel from './3d/TilesetPanel'; +import LayerPanel, { LayerPanelProps } from './3d/BottomPanel/LayerPanel'; +import RouteEditor from '../RouteEditor'; +import BoundaryEditor from '../BoundaryEditor'; import { useTilesetLoader, TilesetConfig } from './3d/hooks/useTilesetLoader'; import { useDroneSSE } from './3d/hooks/useDroneSSE'; import { getModelsByDeviceSn, convertToTilesetConfig } from '@/services/threeDModel'; +import TilesetPanel from "@/pages/map3d/components/MapContainer/3d/TilesetPanel"; // 动态导入Cesium let Cesium: any = null; @@ -29,7 +32,9 @@ const CesiumContainer: React.FC = (props) => { const containerRef = useRef(null); const viewerRef = useRef(null); const entitiesRef = useRef>(new Map()); + const pickHandlerRef = useRef(null); const [loading, setLoading] = useState(true); + const [viewerReady, setViewerReady] = useState(false); // 新增:viewer 是否完全就绪 // 3D 模式专属状态 const [selectedDevice, setSelectedDevice] = useState(null); @@ -45,6 +50,18 @@ const CesiumContainer: React.FC = (props) => { const [taskPanelDevice, setTaskPanelDevice] = useState(null); const [taskPanelDockData, setTaskPanelDockData] = useState(null); + // 航线规划面板状态(无人船) + const [routePlanningVisible, setRoutePlanningVisible] = useState(false); + const [routePlanningDevice, setRoutePlanningDevice] = useState(null); + const [routePlanningBoundaryId, setRoutePlanningBoundaryId] = useState(null); + + // 边界编辑面板状态(水域边界) + const [boundaryEditorVisible, setBoundaryEditorVisible] = useState(false); + const [autoShowBoundaryId, setAutoShowBoundaryId] = useState(null); + + // 图层管理面板状态 + const [layerPanelVisible, setLayerPanelVisible] = useState(false); + // 无人机SSE订阅(用于在3D地球上显示无人机位置) const [droneDeviceSn, setDroneDeviceSn] = useState(''); const { droneData, connectDroneSSE, disconnectDroneSSE, resetDroneData } = useDroneSSE(); @@ -274,12 +291,14 @@ const CesiumContainer: React.FC = (props) => { // 使用较短的动画时间,因为相机已经在设备附近了 if (firstTileset && viewerRef.current && !viewerRef.current.isDestroyed?.()) { try { + const radius = Number(firstTileset?.boundingSphere?.radius); + const range = Number.isFinite(radius) && radius > 0 ? Math.max(40, radius * 0.7) : 80; viewerRef.current.flyTo(firstTileset, { - duration: 1.0, // 缩短动画时间,因为已经在附近 + duration: 0.8, // 缩短动画时间,因为已经在附近 offset: new Cesium.HeadingPitchRange( Cesium.Math.toRadians(0), - Cesium.Math.toRadians(-45), - 0 + Cesium.Math.toRadians(-70), // 改为70度俯视,更接近垂直俯视 + range ), }); } catch (e) { @@ -392,6 +411,84 @@ const CesiumContainer: React.FC = (props) => { setTaskPanelVisible(true); }, []); + // 处理从右侧面板点击"航线规划"(无人船) + const handleOpenRoutePlanning = useCallback((device: any) => { + setRoutePlanningDevice(device); + setRoutePlanningVisible(true); + setRoutePlanningBoundaryId(null); + // 关闭其他面板 + setRightPanelVisible(false); + }, []); + + // 关闭航线规划面板 + const handleCloseRoutePlanning = useCallback(() => { + setRoutePlanningVisible(false); + setRoutePlanningDevice(null); + setRoutePlanningBoundaryId(null); + // 退出后恢复右侧面板入口 + if (selectedDevice) { + setRightPanelVisible(true); + } + }, [selectedDevice]); + + // 航线保存成功回调 + const handleRoutesSaveSuccess = useCallback((routeId: string) => { + // 保持航线规划面板不关闭:由 RouteEditor 内部切回“航线库”并刷新列表 + // 这里保留回调入口,便于后续做跨面板联动 + void routeId; + }, []); + + // 从图层管理面板:基于边界快速进入航线规划(仅可航行边界) + const handleOpenRoutePlanningByBoundary = useCallback((boundary: any) => { + if (!selectedDevice) { + message.warning('请先选择设备'); + return; + } + const boundaryId = String(boundary?.boundaryId || '').trim(); + if (!boundaryId) { + message.warning('边界ID无效,无法进入航线规划'); + return; + } + setRoutePlanningDevice(selectedDevice); + setRoutePlanningVisible(true); + setRoutePlanningBoundaryId(boundaryId); + setLayerPanelVisible(false); + setRightPanelVisible(false); + }, [selectedDevice]); + + // 处理从图层管理面板点击"新建边界" + const handleOpenBoundaryEditor = useCallback(() => { + const sn = String(selectedDevice?.deviceSn || '').trim(); + if (!sn) { + message.warning('请先选择设备后再新建边界'); + return; + } + setBoundaryEditorVisible(true); + // 关闭其他面板 + setLayerPanelVisible(false); + setRightPanelVisible(false); + }, [selectedDevice]); + + // 关闭边界编辑器 + const handleCloseBoundaryEditor = useCallback(() => { + setBoundaryEditorVisible(false); + if (selectedDevice) { + setRightPanelVisible(true); + } + }, [selectedDevice]); + + // 边界保存成功回调 + const handleBoundarySaveSuccess = useCallback((boundaryId: string) => { + message.success('边界保存成功'); + setBoundaryEditorVisible(false); + // 重新打开图层管理面板,显示新创建的边界 + setLayerPanelVisible(true); + setAutoShowBoundaryId(boundaryId); + if (selectedDevice) { + setRightPanelVisible(true); + } + }, [selectedDevice]); + // 计算无人机实时位置 const realtimePosition = useMemo(() => { if (!droneData) return null; @@ -582,6 +679,11 @@ const CesiumContainer: React.FC = (props) => { flyToGlobal(); }, [flyToGlobal, unloadAllTilesets, onClearSelection, droneDeviceSn, disconnectDroneSSE, resetDroneData, clearDroneLayers]); + // 收起到“设备面板”(不清空设备、不卸载模型) + const handleRightPanelMinimize = useCallback(() => { + setRightPanelVisible(false); + }, []); + // ========== 3D Tiles 模型管理方法 ========== // 加载模型 @@ -624,6 +726,11 @@ const CesiumContainer: React.FC = (props) => { if (!Cesium) { const cesiumModule = await import('cesium'); Cesium = cesiumModule; + + // 将 Cesium 挂载到 window 上,供其他组件使用(如 BoundaryEditor) + (window as any).Cesium = cesiumModule; + console.log('[CesiumContainer] ✓ Cesium 已挂载到 window'); + const cesiumBaseUrl = process.env.CESIUM_BASE_URL || '/'; Cesium.buildModuleUrl.setBaseUrl(`${cesiumBaseUrl}cesium/`); @@ -717,11 +824,14 @@ const CesiumContainer: React.FC = (props) => { } setLoading(false); + setViewerReady(true); // Viewer 初始化完成 + console.log('[CesiumContainer] ✓ Viewer 初始化完成,viewerReady=true'); message.success('3D地图加载完成'); } catch (error) { console.error('Cesium初始化失败:', error); message.error('3D地图加载失败'); setLoading(false); + setViewerReady(false); // 初始化失败 } }; @@ -731,6 +841,7 @@ const CesiumContainer: React.FC = (props) => { if (viewerRef.current && !viewerRef.current.isDestroyed()) { viewerRef.current.destroy(); } + setViewerReady(false); // 清理时重置状态 }; }, []); @@ -797,9 +908,32 @@ const CesiumContainer: React.FC = (props) => { if (loading || !viewerRef.current || !Cesium) return; const viewer = viewerRef.current; - viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK); + if (viewer.isDestroyed?.()) return; - const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas); + // 清理旧的拾取 handler(React 18 dev 下 effect 可能会触发多次) + if (pickHandlerRef.current) { + try { + pickHandlerRef.current.destroy(); + } catch { + // 忽略 + } + pickHandlerRef.current = null; + } + + try { + viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK); + } catch { + // 忽略 + } + + let handler: any = null; + try { + handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas); + pickHandlerRef.current = handler; + } catch (e) { + console.warn('初始化拾取事件失败:', e); + return; + } handler.setInputAction((movement: any) => { const pickedObject = viewer.scene.pick(movement.position); @@ -828,11 +962,19 @@ const CesiumContainer: React.FC = (props) => { }, Cesium.ScreenSpaceEventType.MOUSE_MOVE); return () => { - handler.destroy(); + if (pickHandlerRef.current === handler) { + try { + handler.destroy(); + } catch { + // 忽略 + } + pickHandlerRef.current = null; + } document.body.style.cursor = 'default'; }; }, [loading, handleDeviceSelect]); + // @ts-ignore return (
@@ -898,7 +1040,7 @@ const CesiumContainer: React.FC = (props) => { )} {/* 3D模型管理按钮 - 当设备有绑定模型时显示 */} - {!loading && currentDeviceModels.length > 0 && ( + {!loading && !boundaryEditorVisible && currentDeviceModels.length > 0 && (
); }; diff --git a/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/RoutePreview.tsx b/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/RoutePreview.tsx new file mode 100644 index 00000000..461353d7 --- /dev/null +++ b/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/RoutePreview.tsx @@ -0,0 +1,147 @@ +/** + * 航线预览组件 + * @author dzc + * @date 2026-01-05 + */ +import React from 'react'; +import { Card, Descriptions, Alert, List, Tag } from 'antd'; +import { + EnvironmentOutlined, + ClockCircleOutlined, + DashboardOutlined, + WarningOutlined, + CheckCircleOutlined, + CloseCircleOutlined, +} from '@ant-design/icons'; +import type { RoutePreviewProps } from './types'; +import styles from './index.less'; + +const RoutePreview: React.FC = ({ + waypoints, + cruiseSpeed, + totalDistance, + estimatedDuration, + validationResult, +}) => { + // 格式化距离 + const formatDistance = (meters: number) => { + if (meters >= 1000) { + return `${(meters / 1000).toFixed(2)} km`; + } + return `${meters.toFixed(0)} m`; + }; + + // 格式化时长 + const formatDuration = (seconds: number) => { + if (seconds < 60) { + return `${seconds} 秒`; + } + const minutes = Math.floor(seconds / 60); + const secs = seconds % 60; + if (minutes < 60) { + return secs > 0 ? `${minutes} 分 ${secs} 秒` : `${minutes} 分钟`; + } + const hours = Math.floor(minutes / 60); + const mins = minutes % 60; + return `${hours} 小时 ${mins} 分钟`; + }; + + return ( +
+ + + 航点数}> + {waypoints.length} + + 巡航速度}> + {cruiseSpeed} m/s + + + {formatDistance(totalDistance)} + + 预计时长}> + {formatDuration(estimatedDuration)} + + + + {/* 校验结果 */} + {validationResult && ( +
+ {validationResult.valid ? ( + } + showIcon + style={{ marginBottom: 8 }} + /> + ) : ( + } + showIcon + style={{ marginBottom: 8 }} + /> + )} + + {/* 错误列表 */} + {validationResult.errors.length > 0 && ( +
+
+ 错误: +
+ {validationResult.errors.map((err, i) => ( + + {err} + + ))} +
+ )} + + {/* 警告列表 */} + {validationResult.warnings.length > 0 && ( +
+
+ 警告: +
+ {validationResult.warnings.map((warn, i) => ( + + {warn} + + ))} +
+ )} +
+ )} +
+ + {/* 航点列表 */} + {waypoints.length > 0 && ( + + ( + + + {wp.isKeyPoint && 关键} + {wp.pointName || `航点${index + 1}`} + + + {wp.longitude.toFixed(4)}, {wp.latitude.toFixed(4)} + + {wp.stayDuration && wp.stayDuration > 0 && ( + {wp.stayDuration}s + )} + + )} + /> + + )} +
+ ); +}; + +export default RoutePreview; diff --git a/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/RouteToolbar.tsx b/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/RouteToolbar.tsx new file mode 100644 index 00000000..e7e0d8de --- /dev/null +++ b/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/RouteToolbar.tsx @@ -0,0 +1,162 @@ +/** + * 航线编辑器工具栏组件 + * @author dzc + * @date 2026-01-05 + */ +import React from 'react'; +import { Button, Tooltip, Popconfirm } from 'antd'; +import { + SelectOutlined, + DeleteOutlined, + UndoOutlined, + CheckCircleOutlined, + SaveOutlined, + CloseOutlined, + AimOutlined, + EyeOutlined, + PauseCircleOutlined, +} from '@ant-design/icons'; +import type { RouteToolbarProps } from './types'; +import styles from './index.less'; + +const RouteToolbar: React.FC = ({ + mode, + hasWaypoints, + hasUnsavedChanges, + canUndo, + isValidating, + isPreviewing, + onModeChange, + onClear, + onUndo, + onValidate, + onSave, + onCancel, + onPreview, + onStopPreview, +}) => { + return ( +
+
+ {/* 绘制模式 */} + + + + + {/* 选择模式 */} + + + +
+ +
+ {/* 第一视角预览 */} + {isPreviewing ? ( + + + + ) : ( + + + + )} +
+ +
+ {/* 撤销 */} + +
+ +
+ {/* 校验 */} + + + {/* 保存 */} + + + {/* 取消 */} + + + +
+
+ ); +}; + +export default RouteToolbar; diff --git a/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/WaypointEditor.tsx b/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/WaypointEditor.tsx new file mode 100644 index 00000000..bf9ff8a6 --- /dev/null +++ b/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/WaypointEditor.tsx @@ -0,0 +1,224 @@ +/** + * 航点编辑器组件 + * @author dzc + * @date 2026-01-05 + */ +import React from 'react'; +import { + Drawer, + Form, + Input, + InputNumber, + Select, + Switch, + Button, + Space, + Divider, + List, + Tag, +} from 'antd'; +import { DeleteOutlined, PlusOutlined } from '@ant-design/icons'; +import type { BoatWaypointDTO, WaypointAction, WaypointActionType, TurnMode } from '@/types/boatRoute'; +import type { WaypointEditorProps } from './types'; + +const { Option } = Select; +const { TextArea } = Input; + +const turnModeOptions: { value: TurnMode; label: string }[] = [ + { value: 'sharp', label: '锐角转弯' }, + { value: 'smooth', label: '平滑转弯' }, + { value: 'arc', label: '弧线转弯' }, +]; + +const actionTypeOptions: { value: WaypointActionType; label: string }[] = [ + { value: 'hover', label: '悬停' }, + { value: 'take_photo', label: '拍照' }, + { value: 'record_video', label: '录像' }, + { value: 'horn', label: '鸣笛' }, + { value: 'light', label: '灯光' }, + { value: 'spray', label: '喷洒' }, +]; + +const WaypointEditor: React.FC = ({ + waypoint, + index, + onUpdate, + onDelete, + onClose, +}) => { + const [form] = Form.useForm(); + + const handleFinish = (values: any) => { + const updated: BoatWaypointDTO = { + ...waypoint, + ...values, + }; + onUpdate(index, updated); + onClose(); + }; + + const handleAddAction = () => { + const actions = form.getFieldValue('actions') || []; + form.setFieldsValue({ + actions: [...actions, { actionType: 'hover', duration: 5 }], + }); + }; + + const handleRemoveAction = (actionIndex: number) => { + const actions = form.getFieldValue('actions') || []; + form.setFieldsValue({ + actions: actions.filter((_: any, i: number) => i !== actionIndex), + }); + }; + + return ( + + + + + } + > +
+ {/* 位置信息(只读) */} +
+
+ 经度: {waypoint.longitude.toFixed(6)} +
+
+ 纬度: {waypoint.latitude.toFixed(6)} +
+
+ + + + + + + + + + + + + + + + + + + + + + 航点动作 + + + {(fields, { remove }) => ( + <> + {fields.map(({ key, name, ...restField }) => ( +
+ + + + + + +
+ ))} + + + )} +
+ + + + +