Merge pull request 'feature_dzc' (#22) from feature_dzc into test

Reviewed-on: http://220.205.16.27:18081/goflytec/GoFly-platform-services/pulls/22
This commit is contained in:
2026-01-09 12:24:38 +00:00
206 changed files with 21626 additions and 5451 deletions
+7 -1
View File
@@ -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": []
Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 MiB

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

Some files were not shown because too many files have changed in this diff Show More