feat: 航线解析以及websocket订阅不关闭bug修复

This commit is contained in:
2025-12-21 14:15:44 +08:00
parent 17bed2438f
commit 5ee8c03671
59 changed files with 10746 additions and 122 deletions
@@ -0,0 +1,59 @@
package com.central.device.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 异步任务配置
*
* @author dzc
* @date 2025-12-17
*/
@Slf4j
@Configuration
@EnableAsync
public class AsyncConfig {
/**
* 航线解析专用线程池
*/
@Bean("waylineParseExecutor")
public Executor waylineParseExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程数
executor.setCorePoolSize(2);
// 最大线程数
executor.setMaxPoolSize(5);
// 队列容量
executor.setQueueCapacity(100);
// 线程名前缀
executor.setThreadNamePrefix("wayline-parse-");
// 拒绝策略:由调用线程处理
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 线程空闲时间
executor.setKeepAliveSeconds(60);
// 等待所有任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
// 等待时间
executor.setAwaitTerminationSeconds(60);
executor.initialize();
log.info("航线解析线程池初始化完成");
return executor;
}
}
@@ -0,0 +1,178 @@
package com.central.device.controller;
import com.central.common.model.Result;
import com.central.device.entity.DroneFlightTrack;
import com.central.device.model.vo.FlightTrackVO;
import com.central.device.service.IDroneFlightTrackService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 飞行轨迹Controller
*
* @author dzc
* @date 2025-12-17
*/
@RestController
@RequestMapping("/api/device/drone/track")
@Tag(name = "飞行轨迹管理", description = "飞行轨迹相关接口")
@Slf4j
public class DroneFlightTrackController {
@Autowired
private IDroneFlightTrackService flightTrackService;
@Operation(summary = "获取飞行轨迹", description = "获取指定设备的飞行轨迹数据")
@GetMapping("/{deviceSn}")
public Result<FlightTrackVO> getFlightTrack(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn,
@Parameter(description = "任务ID")
@RequestParam(required = false) String jobId,
@Parameter(description = "航线任务ID")
@RequestParam(required = false) String routeId,
@Parameter(description = "开始时间")
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
@Parameter(description = "结束时间")
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
@Parameter(description = "限制数量")
@RequestParam(required = false, defaultValue = "1000") Integer limit) {
try {
List<DroneFlightTrack> trackPoints = flightTrackService.getTrackPoints(
deviceSn, jobId, routeId, startTime, endTime, limit);
FlightTrackVO vo = new FlightTrackVO();
vo.setDeviceSn(deviceSn);
vo.setJobId(jobId);
vo.setRouteId(routeId);
if (trackPoints != null && !trackPoints.isEmpty()) {
// 转换轨迹点
List<FlightTrackVO.TrackPointVO> pointVOs = trackPoints.stream()
.map(this::convertToTrackPointVO)
.collect(Collectors.toList());
vo.setTrackPoints(pointVOs);
vo.setTotalPoints(pointVOs.size());
// 计算飞行时长(秒)
LocalDateTime firstTime = trackPoints.get(0).getRecordTime();
LocalDateTime lastTime = trackPoints.get(trackPoints.size() - 1).getRecordTime();
if (firstTime != null && lastTime != null) {
vo.setDuration(java.time.Duration.between(firstTime, lastTime).getSeconds());
}
} else {
vo.setTrackPoints(new ArrayList<>());
vo.setTotalPoints(0);
vo.setDuration(0L);
}
return Result.succeed(vo);
} catch (Exception e) {
log.error("获取飞行轨迹失败: deviceSn={}", deviceSn, e);
return Result.failed("获取失败: " + e.getMessage());
}
}
@Operation(summary = "获取最新轨迹点", description = "获取指定设备的最新轨迹点")
@GetMapping("/latest/{deviceSn}")
public Result<FlightTrackVO.TrackPointVO> getLatestTrackPoint(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn) {
if (!StringUtils.hasText(deviceSn)) {
return Result.failed("设备SN不能为空");
}
try {
DroneFlightTrack track = flightTrackService.getLatestTrackPoint(deviceSn);
if (track != null) {
FlightTrackVO.TrackPointVO vo = convertToTrackPointVO(track);
return Result.succeed(vo);
} else {
return Result.succeed(null, "暂无轨迹数据");
}
} catch (Exception e) {
log.error("获取最新轨迹点失败: deviceSn={}", deviceSn, e);
return Result.failed("获取失败: " + e.getMessage());
}
}
@Operation(summary = "删除历史轨迹", description = "删除指定时间之前的飞行轨迹数据")
@DeleteMapping("/history/{deviceSn}")
public Result<Integer> deleteHistoryTracks(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn,
@Parameter(description = "删除此时间之前的轨迹", required = true)
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime beforeTime) {
if (!StringUtils.hasText(deviceSn)) {
return Result.failed("设备SN不能为空");
}
try {
int count = flightTrackService.deleteTrackPointsBefore(deviceSn, beforeTime);
return Result.succeed(count, "成功删除 " + count + " 条轨迹记录");
} catch (Exception e) {
log.error("删除历史轨迹失败: deviceSn={}", deviceSn, e);
return Result.failed("删除失败: " + e.getMessage());
}
}
@Operation(summary = "统计轨迹点数量", description = "统计指定条件的轨迹点数量")
@GetMapping("/count/{deviceSn}")
public Result<Long> countTrackPoints(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn,
@Parameter(description = "任务ID")
@RequestParam(required = false) String jobId,
@Parameter(description = "航线任务ID")
@RequestParam(required = false) String routeId,
@Parameter(description = "开始时间")
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
@Parameter(description = "结束时间")
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
try {
Long count = flightTrackService.countTrackPoints(deviceSn, jobId, routeId, startTime, endTime);
return Result.succeed(count);
} catch (Exception e) {
log.error("统计轨迹点数量失败", e);
return Result.failed("统计失败: " + e.getMessage());
}
}
/**
* 转换为轨迹点VO
*/
private FlightTrackVO.TrackPointVO convertToTrackPointVO(DroneFlightTrack track) {
FlightTrackVO.TrackPointVO vo = new FlightTrackVO.TrackPointVO();
vo.setLng(track.getLongitude() != null ? track.getLongitude().doubleValue() : 0);
vo.setLat(track.getLatitude() != null ? track.getLatitude().doubleValue() : 0);
vo.setAlt(track.getAltitude() != null ? track.getAltitude().doubleValue() : 0);
vo.setHeight(track.getHeight() != null ? track.getHeight().doubleValue() : 0);
vo.setSpeed(track.getHorizontalSpeed() != null ? track.getHorizontalSpeed().doubleValue() : 0);
vo.setHeading(track.getHeading() != null ? track.getHeading().doubleValue() : 0);
vo.setBatteryPercent(track.getBatteryPercent());
vo.setTime(track.getRecordTime());
// 偏离信息
vo.setDeviationDistance(track.getDeviationDistance() != null ? track.getDeviationDistance().doubleValue() : 0);
vo.setIsDeviation(track.getIsDeviation() != null && track.getIsDeviation() == 1);
return vo;
}
}
@@ -0,0 +1,331 @@
package com.central.device.controller;
import com.central.common.model.Result;
import com.central.device.entity.WaylineAction;
import com.central.device.entity.WaylineRoute;
import com.central.device.entity.WaylineWaypoint;
import com.central.device.model.dto.WaylineRouteCreateDTO;
import com.central.device.model.dto.BindDeviceDTO;
import com.central.device.model.vo.WaylineRouteVO;
import com.central.device.model.vo.WaypointVO;
import com.central.device.model.vo.WaypointActionVO;
import com.central.device.model.vo.RouteDetailVO;
import com.central.device.parser.model.KmzParseResult;
import com.central.device.service.IWaylineParseService;
import com.central.device.service.IWaylineRouteService;
import com.central.device.service.IWaylineWaypointService;
import com.central.device.mapper.WaylineActionMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 航线任务管理Controller
*
* @author dzc
* @date 2025-12-17
*/
@RestController
@RequestMapping("/device/route")
@Tag(name = "航线任务管理", description = "航线任务相关接口")
@Slf4j
@Validated
public class WaylineRouteController {
@Autowired
private IWaylineRouteService waylineRouteService;
@Autowired
private IWaylineParseService waylineParseService;
@Autowired
private IWaylineWaypointService waylineWaypointService;
@Autowired
private WaylineActionMapper waylineActionMapper;
@Autowired
private ObjectMapper objectMapper;
@Operation(summary = "绑定航迹文件到设备并解析", description = "将航迹文件绑定到设备,并自动解析航线、航点、动作数据")
@PostMapping("/bindWaylineToDevice")
public Result<String> bindWaylineToDevice(@RequestBody BindDeviceDTO dto) {
try {
waylineRouteService.bindWaylineToDevice(
dto.getDeviceSn(),
dto.getWaylineId(),
dto.getWaylineName(),
dto.getWorkspaceId()
);
return Result.succeed("绑定成功,航线解析完成");
} catch (Exception e) {
log.error("绑定航迹文件到设备失败: deviceSn={}, waylineId={}",
dto.getDeviceSn(), dto.getWaylineId(), e);
return Result.failed("绑定失败: " + e.getMessage());
}
}
@Operation(summary = "创建航线任务", description = "创建新的航线任务,关联航迹文件和设备")
@PostMapping("/create")
public Result<WaylineRouteVO> createRoute(@Valid @RequestBody WaylineRouteCreateDTO dto) {
try {
WaylineRoute route = waylineRouteService.createRoute(
dto.getRouteName(),
dto.getFileWaylineId(),
dto.getDeviceSn(),
dto.getDeviceName(),
dto.getRemark()
);
WaylineRouteVO vo = convertToRouteVO(route);
return Result.succeed(vo);
} catch (Exception e) {
log.error("创建航线任务失败", e);
return Result.failed("创建失败: " + e.getMessage());
}
}
@Operation(summary = "根据航迹文件ID查询航线任务列表", description = "查询指定航迹文件创建的所有航线任务")
@GetMapping("/listByFileWaylineId/{fileWaylineId}")
public Result<List<WaylineRouteVO>> listByFileWaylineId(
@Parameter(description = "航迹文件ID", required = true)
@PathVariable String fileWaylineId) {
if (!StringUtils.hasText(fileWaylineId)) {
return Result.failed("航迹文件ID不能为空");
}
try {
List<WaylineRoute> routes = waylineRouteService.listByFileWaylineId(fileWaylineId);
List<WaylineRouteVO> vos = routes.stream()
.map(this::convertToRouteVO)
.collect(Collectors.toList());
return Result.succeed(vos);
} catch (Exception e) {
log.error("查询航线任务列表失败: fileWaylineId={}", fileWaylineId, e);
return Result.failed("查询失败: " + e.getMessage());
}
}
@Operation(summary = "根据设备SN查询绑定的航线任务列表", description = "查询指定设备绑定的所有航线任务")
@GetMapping("/listByDevice/{deviceSn}")
public Result<List<WaylineRouteVO>> listByDevice(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn) {
if (!StringUtils.hasText(deviceSn)) {
return Result.failed("设备SN不能为空");
}
try {
List<WaylineRoute> routes = waylineRouteService.listByDeviceSn(deviceSn);
List<WaylineRouteVO> vos = routes.stream()
.map(this::convertToRouteVO)
.collect(Collectors.toList());
return Result.succeed(vos);
} catch (Exception e) {
log.error("查询航线任务列表失败: deviceSn={}", deviceSn, e);
return Result.failed("查询失败: " + e.getMessage());
}
}
@Operation(summary = "获取航线解析详情", description = "获取航线的完整信息,包含航点和动作数据")
@GetMapping("/detail/{routeId}")
public Result<RouteDetailVO> getRouteDetail(
@Parameter(description = "航线任务ID", required = true)
@PathVariable String routeId) {
if (!StringUtils.hasText(routeId)) {
return Result.failed("航线任务ID不能为空");
}
try {
// 获取航线任务信息
WaylineRoute route = waylineRouteService.getByRouteId(routeId);
if (route == null) {
return Result.failed("航线任务不存在");
}
// 获取航点数据
List<WaylineWaypoint> waypoints = waylineWaypointService.listByRouteIdOrderByIndex(routeId);
List<WaypointVO> waypointVOs = waypoints.stream()
.map(this::convertToWaypointVO)
.collect(Collectors.toList());
// 获取动作数据
List<WaypointActionVO> actionVOs = waylineParseService.getActionsByRouteId(routeId);
// 构建返回数据
RouteDetailVO detailVO = new RouteDetailVO();
detailVO.setRouteInfo(convertToRouteVO(route));
detailVO.setWaypoints(waypointVOs);
detailVO.setActions(actionVOs);
detailVO.setTotalWaypoints(waypointVOs.size());
detailVO.setTotalActions(actionVOs.size());
detailVO.setTotalDistance(route.getTotalDistance() != null ? route.getTotalDistance().doubleValue() : null);
detailVO.setTotalDuration(route.getTotalDuration() != null ? route.getTotalDuration().doubleValue() : null);
return Result.succeed(detailVO);
} catch (Exception e) {
log.error("获取航线任务详情失败: routeId={}", routeId, e);
return Result.failed("查询失败: " + e.getMessage());
}
}
@Operation(summary = "获取航线航点列表", description = "获取航线的所有航点坐标信息,用于地图展示")
@GetMapping("/waypoints/{routeId}")
public Result<List<WaypointVO>> getRouteWaypoints(
@Parameter(description = "航线任务ID", required = true)
@PathVariable String routeId) {
if (!StringUtils.hasText(routeId)) {
return Result.failed("航线任务ID不能为空");
}
try {
List<WaylineWaypoint> waypoints = waylineWaypointService.listByRouteIdOrderByIndex(routeId);
List<WaypointVO> vos = waypoints.stream()
.map(this::convertToWaypointVO)
.collect(Collectors.toList());
return Result.succeed(vos);
} catch (Exception e) {
log.error("获取航点列表失败: routeId={}", routeId, e);
return Result.failed("查询失败: " + e.getMessage());
}
}
@Operation(summary = "解析航线任务", description = "解析航线的KMZ文件,提取航点和动作数据")
@PostMapping("/parse/{routeId}")
public Result<KmzParseResult> parseRoute(
@Parameter(description = "航线任务ID", required = true)
@PathVariable String routeId) {
if (!StringUtils.hasText(routeId)) {
return Result.failed("航线任务ID不能为空");
}
try {
KmzParseResult result = waylineParseService.parseRoute(routeId);
if (result.isSuccess()) {
return Result.succeed(result, "解析成功");
} else {
return Result.failed("解析失败: " + result.getErrorMessage());
}
} catch (Exception e) {
log.error("解析航线任务失败: routeId={}", routeId, e);
return Result.failed("解析失败: " + e.getMessage());
}
}
@Operation(summary = "批量解析航线任务", description = "批量解析多个航线的KMZ文件")
@PostMapping("/parse/batch")
public Result<String> batchParseRoutes(@RequestBody List<String> routeIds) {
try {
if (CollectionUtils.isEmpty(routeIds)) {
return Result.failed("航线任务ID列表不能为空");
}
waylineParseService.batchParseRoutes(routeIds.toArray(new String[0]));
return Result.succeed("批量解析任务已提交,正在后台执行");
} catch (Exception e) {
log.error("批量解析航线任务失败", e);
return Result.failed("批量解析失败: " + e.getMessage());
}
}
/**
* 转换为航线任务VO
*/
private WaylineRouteVO convertToRouteVO(WaylineRoute route) {
WaylineRouteVO vo = new WaylineRouteVO();
BeanUtils.copyProperties(route, vo);
// 设置解析状态描述
if (route.getParseStatus() != null) {
WaylineRoute.ParseStatus status = WaylineRoute.ParseStatus.fromCode(route.getParseStatus());
vo.setParseStatusDesc(status.getDesc());
}
return vo;
}
/**
* 转换为航点VO
*/
private WaypointVO convertToWaypointVO(WaylineWaypoint waypoint) {
WaypointVO vo = new WaypointVO();
BeanUtils.copyProperties(waypoint, vo);
vo.setIndex(waypoint.getWaypointIndex());
// 转换布尔值
vo.setUseStraightLine(waypoint.getUseStraightLine() != null && waypoint.getUseStraightLine() == 1);
vo.setIsRisky(waypoint.getIsRisky() != null && waypoint.getIsRisky() == 1);
// 加载动作数据
List<WaylineAction> actions = waylineActionMapper.selectByWaypointId(waypoint.getId());
if (actions != null && !actions.isEmpty()) {
List<WaypointActionVO> actionVOs = new ArrayList<>();
for (WaylineAction action : actions) {
WaypointActionVO actionVO = new WaypointActionVO();
actionVO.setActionGroupId(action.getActionGroupId());
actionVO.setActionIndex(action.getActionIndex());
actionVO.setActionType(action.getActionType());
actionVO.setTriggerType(action.getTriggerType());
// 解析动作参数
if (StringUtils.hasText(action.getActionParams())) {
try {
Map<String, Object> params = objectMapper.readValue(action.getActionParams(), Map.class);
actionVO.setActionParams(params);
// 从参数中提取具体字段
if (params.containsKey("hoverTime")) {
Object hoverTime = params.get("hoverTime");
if (hoverTime instanceof Number) {
actionVO.setHoverTime(((Number) hoverTime).doubleValue());
}
}
if (params.containsKey("aircraftHeading")) {
Object heading = params.get("aircraftHeading");
if (heading instanceof Number) {
actionVO.setAircraftHeading(((Number) heading).doubleValue());
}
}
if (params.containsKey("gimbalPitchRotateAngle")) {
Object pitch = params.get("gimbalPitchRotateAngle");
if (pitch instanceof Number) {
actionVO.setGimbalPitchRotateAngle(((Number) pitch).doubleValue());
}
}
if (params.containsKey("gimbalYawRotateAngle")) {
Object yaw = params.get("gimbalYawRotateAngle");
if (yaw instanceof Number) {
actionVO.setGimbalYawRotateAngle(((Number) yaw).doubleValue());
}
}
// 提取megaphone文件路径
if (params.containsKey("megaphoneOperateFilePath")) {
Object filePath = params.get("megaphoneOperateFilePath");
if (filePath != null) {
actionVO.setMegaphoneFilePath(filePath.toString());
}
}
} catch (Exception e) {
log.warn("解析动作参数失败: waypointId={}, actionId={}", waypoint.getId(), action.getId(), e);
}
}
actionVOs.add(actionVO);
}
vo.setActions(actionVOs);
} else {
vo.setActions(new ArrayList<>());
}
return vo;
}
}
@@ -0,0 +1,190 @@
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 2025-12-17
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("drone_flight_track")
public class DroneFlightTrack 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(关联wayline_job.job_id)
*/
@TableField("job_id")
private String jobId;
/**
* 航线任务ID(关联wayline_route.route_id)
*/
@TableField("route_id")
private String routeId;
/**
* 经度
*/
@TableField("longitude")
private BigDecimal longitude;
/**
* 纬度
*/
@TableField("latitude")
private BigDecimal latitude;
/**
* 海拔高度(m)
*/
@TableField("altitude")
private BigDecimal altitude;
/**
* 相对高度(m)
*/
@TableField("height")
private BigDecimal height;
/**
* 水平速度(m/s)
*/
@TableField("horizontal_speed")
private BigDecimal horizontalSpeed;
/**
* 垂直速度(m/s)
*/
@TableField("vertical_speed")
private BigDecimal verticalSpeed;
/**
* 航向角(度)
*/
@TableField("heading")
private BigDecimal heading;
/**
* 俯仰角(度)
*/
@TableField("pitch")
private BigDecimal pitch;
/**
* 横滚角(度)
*/
@TableField("roll")
private BigDecimal roll;
/**
* 飞行模式
*/
@TableField("flight_mode")
private Integer flightMode;
/**
* 电池电量(%)
*/
@TableField("battery_percent")
private Integer batteryPercent;
/**
* 偏离距离(m)-与计划航线的偏离
*/
@TableField("deviation_distance")
private BigDecimal deviationDistance;
/**
* 是否偏离:0-否,1-是
*/
@TableField("is_deviation")
private Integer isDeviation;
/**
* 记录时间(无人机上报时间)
*/
@TableField("record_time")
private LocalDateTime recordTime;
/**
* 租户ID
*/
@TableField("tenant_id")
private String tenantId;
/**
* 创建时间
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 飞行模式枚举(参考大疆飞行模式)
*/
public enum FlightMode {
MANUAL(0, "手动模式"),
ATTI(1, "姿态模式"),
P_GPS(2, "P-GPS模式"),
F_GPS(3, "F-GPS模式"),
SPORT(4, "运动模式"),
TRIPOD(5, "三脚架模式"),
CINEMATIC(6, "平滑模式"),
SMART(7, "智能模式"),
BOUNCE(8, "弹跳模式"),
WAYPOINT(9, "航线模式"),
POI(10, "兴趣点环绕"),
FOLLOW(11, "智能跟随"),
FPV(12, "FPV模式"),
ACTIVE_TRACK(13, "智能拍摄"),
TAP_FLY(14, "点击飞行"),
QUICK_SHOT(15, "快拍模式");
private final Integer code;
private final String desc;
FlightMode(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
public Integer getCode() {
return code;
}
public String getDesc() {
return desc;
}
public static FlightMode fromCode(Integer code) {
for (FlightMode mode : values()) {
if (mode.getCode().equals(code)) {
return mode;
}
}
return MANUAL;
}
}
}
@@ -0,0 +1,153 @@
package com.central.device.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 航点动作实体
*
* @author dzc
* @date 2025-12-17
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("wayline_action")
public class WaylineAction implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 航点ID(关联wayline_waypoint.id)
*/
@TableField("waypoint_id")
private Long waypointId;
/**
* 航线任务ID(冗余字段,便于查询)
*/
@TableField("route_id")
private String routeId;
/**
* 动作组ID
*/
@TableField("action_group_id")
private Integer actionGroupId;
/**
* 动作序号(组内)
*/
@TableField("action_index")
private Integer actionIndex;
/**
* 动作类型
*/
@TableField("action_type")
private String actionType;
/**
* 动作参数(JSON格式)
*/
@TableField("action_params")
private String actionParams;
/**
* 触发类型:reachPoint-到达航点,betweenAdjacentPoints-航点间
*/
@TableField("trigger_type")
private String triggerType;
/**
* 租户ID
*/
@TableField("tenant_id")
private String tenantId;
/**
* 创建时间
*/
@TableField("create_time")
private LocalDateTime createTime;
/**
* 动作类型枚举
*/
public enum ActionType {
TAKE_PHOTO("takePhoto", "拍照"),
START_RECORD("startRecord", "开始录像"),
STOP_RECORD("stopRecord", "停止录像"),
HOVER("hover", "悬停"),
ZOOM("zoom", "变焦"),
GIMBAL_ROTATE("gimbalRotate", "云台旋转"),
ROTATE_YAW("rotateYaw", "飞机旋转"),
MEGAPHONE("megaphone", "喊话器"),
FOCUS("focus", "对焦"),
GIMBAL_EVENLY_ROTATE("gimbalEvenlyRotate", "云台均匀旋转"),
FLIGHT_PATH_ROTATE_YAW("flightPathRotateYaw", "飞行路径旋转"),
LOOK_AT("lookAt", "查看目标"),
LOOK_AT_TARGET("lookAtTarget", "查看特定目标");
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;
}
public static ActionType fromCode(String code) {
for (ActionType type : values()) {
if (type.getCode().equals(code)) {
return type;
}
}
return null;
}
}
/**
* 触发类型枚举
*/
public enum TriggerType {
REACH_POINT("reachPoint", "到达航点"),
BETWEEN_ADJACENT_POINTS("betweenAdjacentPoints", "航点间"),
AFTER_FINISHED_WAYPOINT("afterFinishedWaypoint", "完成航点后"),
BEFORE_FINISHED_WAYPOINT("beforeFinishedWaypoint", "完成航点前"),
IMMEDIATELY("immediately", "立即触发");
private final String code;
private final String desc;
TriggerType(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
}
@@ -0,0 +1,245 @@
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 2025-12-17
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("wayline_route")
public class WaylineRoute implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 航线任务ID(UUID)
*/
@TableField("route_id")
private String routeId;
/**
* 航线任务名称
*/
@TableField("route_name")
private String routeName;
/**
* 关联航迹文件ID(wayline_file.wayline_id)
*/
@TableField("file_wayline_id")
private String fileWaylineId;
/**
* 绑定设备SN
*/
@TableField("device_sn")
private String deviceSn;
/**
* 设备名称(冗余)
*/
@TableField("device_name")
private String deviceName;
/**
* 解析状态:0-未解析,1-解析中,2-已解析,3-解析失败
*/
@TableField("parse_status")
private Integer parseStatus;
/**
* 解析错误信息
*/
@TableField("parse_error")
private String parseError;
/**
* 航点数量
*/
@TableField("waypoint_count")
private Integer waypointCount;
/**
* 动作总数
*/
@TableField("action_count")
private Integer actionCount;
/**
* 总航程(m)
*/
@TableField("total_distance")
private BigDecimal totalDistance;
/**
* 预计时长(s)
*/
@TableField("total_duration")
private BigDecimal totalDuration;
/**
* 自动飞行速度(m/s)
*/
@TableField("auto_flight_speed")
private BigDecimal autoFlightSpeed;
/**
* 起飞点坐标(经度,纬度,高度)
*/
@TableField("take_off_point")
private String takeOffPoint;
/**
* 完成动作:goHome/hover/landing
*/
@TableField("finish_action")
private String finishAction;
/**
* 遥控器失联动作
*/
@TableField("exit_on_rc_lost")
private String exitOnRcLost;
/**
* 全局返航高度(m)
*/
@TableField("global_rth_height")
private BigDecimal globalRthHeight;
/**
* 坐标系
*/
@TableField("coordinate_mode")
private String coordinateMode;
/**
* 高度模式
*/
@TableField("height_mode")
private String heightMode;
/**
* 状态:0-禁用,1-启用
*/
@TableField("status")
private Integer status;
/**
* 备注
*/
@TableField("remark")
private String remark;
/**
* 工作空间ID
*/
@TableField("workspace_id")
private String workspaceId;
/**
* 租户ID
*/
@TableField("tenant_id")
private String tenantId;
/**
* 创建人
*/
@TableField(value = "create_by", fill = FieldFill.INSERT)
private String createBy;
/**
* 创建时间
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新人
*/
@TableField(value = "update_by", fill = FieldFill.INSERT_UPDATE)
private String updateBy;
/**
* 更新时间
*/
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 解析状态枚举
*/
public enum ParseStatus {
NOT_PARSED(0, "未解析"),
PARSING(1, "解析中"),
PARSED(2, "已解析"),
FAILED(3, "解析失败");
private final Integer code;
private final String desc;
ParseStatus(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
public Integer getCode() {
return code;
}
public String getDesc() {
return desc;
}
public static ParseStatus fromCode(Integer code) {
for (ParseStatus status : values()) {
if (status.getCode().equals(code)) {
return status;
}
}
return NOT_PARSED;
}
}
/**
* 完成动作枚举
*/
public enum FinishAction {
GO_HOME("goHome", "自动返航"),
HOVER("hover", "原地悬停"),
LANDING("landing", "原地降落");
private final String code;
private final String desc;
FinishAction(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
}
@@ -0,0 +1,195 @@
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 2025-12-17
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("wayline_waypoint")
public class WaylineWaypoint implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 航线任务ID(关联wayline_route.route_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)-相对起飞点
*/
@TableField("height")
private BigDecimal height;
/**
* 执行高度(m)
*/
@TableField("execute_height")
private BigDecimal executeHeight;
/**
* 椭球高度(m)
*/
@TableField("ellipsoid_height")
private BigDecimal ellipsoidHeight;
/**
* 飞行速度(m/s)
*/
@TableField("speed")
private BigDecimal speed;
/**
* 航向模式
*/
@TableField("heading_mode")
private String headingMode;
/**
* 航向角(度)
*/
@TableField("heading_angle")
private BigDecimal headingAngle;
/**
* 云台俯仰角(度)
*/
@TableField("gimbal_pitch_angle")
private BigDecimal gimbalPitchAngle;
/**
* 转弯模式
*/
@TableField("turn_mode")
private String turnMode;
/**
* 转弯阻尼距离(m)
*/
@TableField("turn_damping_dist")
private BigDecimal turnDampingDist;
/**
* 是否直线飞行:0-否,1-是
*/
@TableField("use_straight_line")
private Integer useStraightLine;
/**
* 是否风险点:0-否,1-是
*/
@TableField("is_risky")
private Integer isRisky;
/**
* 动作组数量
*/
@TableField("action_group_count")
private Integer actionGroupCount;
/**
* 租户ID
*/
@TableField("tenant_id")
private String tenantId;
/**
* 创建时间
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 航向模式枚举
*/
public enum HeadingMode {
AUTO("auto", "自动"),
MANUAL("manual", "手动"),
TOWARD_POINT_OF_INTEREST("towardPointOfInterest", "朝向兴趣点"),
RC_CONTROL("rcControl", "遥控器控制");
private final String code;
private final String desc;
HeadingMode(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
/**
* 转弯模式枚举
*/
public enum TurnMode {
TO_POINT_AND_STOP("toPointAndStop", "到点停止"),
TO_POINT_AND_GO_WITH_STOP("toPointAndGoWithStop", "到点不停"),
COORDINATE_TURN("coordinateTurn", "协调转弯"),
MANUAL_CONTROL("manualControl", "手动控制");
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;
}
}
}
@@ -0,0 +1,87 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.DroneFlightTrack;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.time.LocalDateTime;
import java.util.List;
/**
* 飞行轨迹Mapper接口
*
* @author dzc
* @date 2025-12-17
*/
@Mapper
public interface DroneFlightTrackMapper extends BaseMapper<DroneFlightTrack> {
/**
* 根据设备SN和查询条件获取轨迹点
*
* @param deviceSn 设备SN
* @param jobId 任务ID(可选)
* @param routeId 航线任务ID(可选)
* @param startTime 开始时间(可选)
* @param endTime 结束时间(可选)
* @param limit 限制数量(可选)
* @return 轨迹点列表
*/
List<DroneFlightTrack> selectTrackPoints(@Param("deviceSn") String deviceSn,
@Param("jobId") String jobId,
@Param("routeId") String routeId,
@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime,
@Param("limit") Integer limit);
/**
* 根据设备SN获取最新的轨迹点
*
* @param deviceSn 设备SN
* @return 最新轨迹点
*/
DroneFlightTrack selectLatestTrackPoint(@Param("deviceSn") String deviceSn);
/**
* 根据设备SN删除指定时间范围的轨迹
*
* @param deviceSn 设备SN
* @param beforeTime 删除此时间之前的轨迹
* @return 影响行数
*/
int deleteByDeviceSnAndTimeBefore(@Param("deviceSn") String deviceSn,
@Param("beforeTime") LocalDateTime beforeTime);
/**
* 统计轨迹点数量
*
* @param deviceSn 设备SN(可选)
* @param jobId 任务ID(可选)
* @param routeId 航线任务ID(可选)
* @param startTime 开始时间(可选)
* @param endTime 结束时间(可选)
* @return 轨迹点数量
*/
Long countTrackPoints(@Param("deviceSn") String deviceSn,
@Param("jobId") String jobId,
@Param("routeId") String routeId,
@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime);
/**
* 批量插入轨迹点
*
* @param trackPoints 轨迹点列表
* @return 影响行数
*/
int batchInsert(@Param("trackPoints") List<DroneFlightTrack> trackPoints);
/**
* 根据航线任务ID删除飞行轨迹
*
* @param routeId 航线任务ID
* @return 影响行数
*/
int deleteByRouteId(@Param("routeId") String routeId);
}
@@ -0,0 +1,58 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.WaylineAction;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 航点动作Mapper接口
*
* @author dzc
* @date 2025-12-17
*/
@Mapper
public interface WaylineActionMapper extends BaseMapper<WaylineAction> {
/**
* 根据航点ID查询动作列表
*
* @param waypointId 航点ID
* @return 动作列表
*/
List<WaylineAction> selectByWaypointId(@Param("waypointId") Long waypointId);
/**
* 根据航线任务ID查询动作列表
*
* @param routeId 航线任务ID
* @return 动作列表
*/
List<WaylineAction> selectByRouteId(@Param("routeId") String routeId);
/**
* 根据航线任务ID删除动作
*
* @param routeId 航线任务ID
* @return 影响行数
*/
int deleteByRouteId(@Param("routeId") String routeId);
/**
* 批量插入动作
*
* @param actions 动作列表
* @return 影响行数
*/
int batchInsert(@Param("actions") List<WaylineAction> actions);
/**
* 统计动作数量
*
* @param routeId 航线任务ID
* @return 动作数量
*/
Integer countByRouteId(@Param("routeId") String routeId);
}
@@ -0,0 +1,102 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.WaylineRoute;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.math.BigDecimal;
import java.util.List;
/**
* 航线任务Mapper接口
*
* @author dzc
* @date 2025-12-17
*/
@Mapper
public interface WaylineRouteMapper extends BaseMapper<WaylineRoute> {
/**
* 根据航迹文件ID查询航线任务列表
*
* @param fileWaylineId 航迹文件ID
* @return 航线任务列表
*/
List<WaylineRoute> selectByFileWaylineId(@Param("fileWaylineId") String fileWaylineId);
/**
* 根据设备SN查询绑定的航线任务列表
*
* @param deviceSn 设备SN
* @return 航线任务列表
*/
List<WaylineRoute> selectByDeviceSn(@Param("deviceSn") String deviceSn);
/**
* 根据航线任务ID查询
*
* @param routeId 航线任务ID
* @return 航线任务
*/
WaylineRoute selectByRouteId(@Param("routeId") String routeId);
/**
* 更新解析状态
*
* @param routeId 航线任务ID
* @param parseStatus 解析状态
* @return 影响行数
*/
int updateParseStatus(@Param("routeId") String routeId, @Param("parseStatus") Integer parseStatus);
/**
* 更新解析状态和错误信息
*
* @param routeId 航线任务ID
* @param parseStatus 解析状态
* @param parseError 解析错误信息
* @return 影响行数
*/
int updateParseStatusWithError(@Param("routeId") String routeId,
@Param("parseStatus") Integer parseStatus,
@Param("parseError") String parseError);
/**
* 更新航线任务统计信息
*
* @param routeId 航线任务ID
* @param waypointCount 航点数量
* @param actionCount 动作数量
* @param totalDistance 总航程
* @param totalDuration 总时长
* @param autoFlightSpeed 自动飞行速度
* @return 影响行数
*/
int updateRouteStats(@Param("routeId") String routeId,
@Param("waypointCount") Integer waypointCount,
@Param("actionCount") Integer actionCount,
@Param("totalDistance") BigDecimal totalDistance,
@Param("totalDuration") BigDecimal totalDuration,
@Param("autoFlightSpeed") BigDecimal autoFlightSpeed);
/**
* 根据设备SN和航迹文件ID查询航线任务
*
* @param deviceSn 设备SN
* @param waylineId 航迹文件ID
* @return 航线任务列表
*/
List<WaylineRoute> selectByDeviceSnAndFileWaylineId(@Param("deviceSn") String deviceSn,
@Param("waylineId") String waylineId);
/**
* 删除设备与航迹文件的绑定(包括相关数据)
*
* @param deviceSn 设备SN
* @param waylineId 航迹文件ID
* @return 影响行数
*/
int deleteBindingByDeviceAndWayline(@Param("deviceSn") String deviceSn,
@Param("waylineId") String waylineId);
}
@@ -0,0 +1,50 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.WaylineWaypoint;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 航点Mapper接口
*
* @author dzc
* @date 2025-12-17
*/
@Mapper
public interface WaylineWaypointMapper extends BaseMapper<WaylineWaypoint> {
/**
* 根据航线任务ID查询航点列表(按序号排序)
*
* @param routeId 航线任务ID
* @return 航点列表
*/
List<WaylineWaypoint> selectByRouteIdOrderByIndex(@Param("routeId") String routeId);
/**
* 根据航线任务ID删除航点
*
* @param routeId 航线任务ID
* @return 影响行数
*/
int deleteByRouteId(@Param("routeId") String routeId);
/**
* 批量插入航点
*
* @param waypoints 航点列表
* @return 影响行数
*/
int batchInsert(@Param("waypoints") List<WaylineWaypoint> waypoints);
/**
* 统计航点数量
*
* @param routeId 航线任务ID
* @return 航点数量
*/
Integer countByRouteId(@Param("routeId") String routeId);
}
@@ -0,0 +1,37 @@
package com.central.device.model.dto;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/**
* 绑定设备DTO
*
* @author dzc
* @date 2025-12-17
*/
@Data
public class BindDeviceDTO {
/**
* 设备SN
*/
@NotBlank(message = "设备SN不能为空")
private String deviceSn;
/**
* 航线ID
*/
@NotBlank(message = "航线ID不能为空")
private String waylineId;
/**
* 航线名称
*/
@NotBlank(message = "航线名称不能为空")
private String waylineName;
/**
* 工作空间ID
*/
private String workspaceId;
}
@@ -0,0 +1,38 @@
package com.central.device.model.dto;
import lombok.Data;
/**
* 创建航线任务DTO
*
* @author dzc
* @date 2025-12-17
*/
@Data
public class WaylineRouteCreateDTO {
/**
* 航线任务名称
*/
private String routeName;
/**
* 关联航迹文件ID
*/
private String fileWaylineId;
/**
* 绑定设备SN
*/
private String deviceSn;
/**
* 设备名称
*/
private String deviceName;
/**
* 备注
*/
private String remark;
}
@@ -0,0 +1,151 @@
package com.central.device.model.vo;
import lombok.Data;
import lombok.Builder;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
/**
* 飞行轨迹VO
*
* @author dzc
* @date 2025-12-17
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class FlightTrackVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 设备SN
*/
private String deviceSn;
/**
* 任务ID
*/
private String jobId;
/**
* 航线任务ID
*/
private String routeId;
/**
* 轨迹点列表
*/
private List<TrackPointVO> trackPoints;
/**
* 总点数
*/
private Integer totalPoints;
/**
* 飞行时长(秒)
*/
private Long duration;
/**
* 开始时间
*/
private LocalDateTime startTime;
/**
* 结束时间
*/
private LocalDateTime endTime;
/**
* 总航程(米)
*/
private Double totalDistance;
/**
* 最大速度(米/秒)
*/
private Double maxSpeed;
/**
* 平均速度(米/秒)
*/
private Double avgSpeed;
/**
* 最大偏离距离(米)
*/
private Double maxDeviationDistance;
/**
* 轨迹点VO
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public static class TrackPointVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 经度
*/
private Double lng;
/**
* 纬度
*/
private Double lat;
/**
* 海拔高度(米)
*/
private Double alt;
/**
* 相对高度(米)
*/
private Double height;
/**
* 水平速度(米/秒)
*/
private Double speed;
/**
* 航向角(度)
*/
private Double heading;
/**
* 电池电量(%)
*/
private Integer batteryPercent;
/**
* 记录时间
*/
private LocalDateTime time;
/**
* 偏离距离(米)
*/
private Double deviationDistance;
/**
* 是否偏离
*/
private Boolean isDeviation;
/**
* 飞行模式
*/
private Integer flightMode;
}
}
@@ -0,0 +1,52 @@
package com.central.device.model.vo;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* 航线详情VO
*
* @author dzc
* @date 2025-12-17
*/
@Data
public class RouteDetailVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 航线任务信息
*/
private WaylineRouteVO routeInfo;
/**
* 航点列表
*/
private List<WaypointVO> waypoints;
/**
* 动作列表
*/
private List<WaypointActionVO> actions;
/**
* 总航点数
*/
private Integer totalWaypoints;
/**
* 总动作数
*/
private Integer totalActions;
/**
* 总距离(米)
*/
private Double totalDistance;
/**
* 总时长(秒)
*/
private Double totalDuration;
}
@@ -0,0 +1,115 @@
package com.central.device.model.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Builder;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 航线任务VO
*
* @author dzc
* @date 2025-12-17
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class WaylineRouteVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 航线任务ID
*/
private String routeId;
/**
* 航线任务名称
*/
private String routeName;
/**
* 关联航迹文件ID
*/
private String fileWaylineId;
/**
* 设备SN
*/
private String deviceSn;
/**
* 设备名称
*/
private String deviceName;
/**
* 解析状态
*/
private Integer parseStatus;
/**
* 解析状态描述
*/
private String parseStatusDesc;
/**
* 解析错误信息
*/
private String parseError;
/**
* 航点数量
*/
private Integer waypointCount;
/**
* 动作总数
*/
private Integer actionCount;
/**
* 总航程(m)
*/
private BigDecimal totalDistance;
/**
* 预计时长(s)
*/
private BigDecimal totalDuration;
/**
* 自动飞行速度(m/s)
*/
private BigDecimal autoFlightSpeed;
/**
* 完成动作
*/
private String finishAction;
/**
* 状态
*/
private Integer status;
/**
* 备注
*/
private String remark;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
}
@@ -0,0 +1,92 @@
package com.central.device.model.vo;
import lombok.Data;
import java.io.Serializable;
import java.util.Map;
/**
* 航点动作VO
*
* @author dzc
* @date 2025-12-17
*/
@Data
public class WaypointActionVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 动作组ID
*/
private Integer actionGroupId;
/**
* 动作序号(组内)
*/
private Integer actionIndex;
/**
* 动作类型
*/
private String actionType;
/**
* 动作类型描述
*/
private String actionTypeDesc;
/**
* 动作参数
*/
private Map<String, Object> actionParams;
/**
* 触发类型
*/
private String triggerType;
/**
* 触发类型描述
*/
private String triggerTypeDesc;
/**
* 延迟时间(毫秒)
*/
private Long delayTime;
/**
* 相机位置索引
*/
private Integer payloadPositionIndex;
/**
* 悬停时间(秒)
*/
private Double hoverTime;
/**
* 飞机航向角
*/
private Double aircraftHeading;
/**
* 云台俯仰旋转角度
*/
private Double gimbalPitchRotateAngle;
/**
* 云台偏航旋转角度
*/
private Double gimbalYawRotateAngle;
/**
* 焦距(毫米)
*/
private Double focalLength;
/**
* 音频文件路径
*/
private String megaphoneFilePath;
}
@@ -0,0 +1,115 @@
package com.central.device.model.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Builder;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
/**
* 航点VO
*
* @author dzc
* @date 2025-12-17
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class WaypointVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 航点序号
*/
private Integer index;
/**
* 经度
*/
private BigDecimal longitude;
/**
* 纬度
*/
private BigDecimal latitude;
/**
* 相对高度(m)
*/
private BigDecimal height;
/**
* 执行高度(m)
*/
private BigDecimal executeHeight;
/**
* 椭球高度(m)
*/
private BigDecimal ellipsoidHeight;
/**
* 飞行速度(m/s)
*/
private BigDecimal speed;
/**
* 航向模式
*/
private String headingMode;
/**
* 航向角(度)
*/
private BigDecimal headingAngle;
/**
* 云台俯仰角(度)
*/
private BigDecimal gimbalPitchAngle;
/**
* 云台横滚角(度)
*/
private BigDecimal gimbalRollAngle;
/**
* 云台偏航角(度)
*/
private BigDecimal gimbalYawAngle;
/**
* 转弯模式
*/
private String turnMode;
/**
* 转弯阻尼距离(m)
*/
private BigDecimal turnDampingDist;
/**
* 是否直线飞行
*/
private Boolean useStraightLine;
/**
* 是否风险点
*/
private Boolean isRisky;
/**
* 动作组数量
*/
private Integer actionGroupCount;
/**
* 动作列表
*/
private List<WaypointActionVO> actions;
}
@@ -0,0 +1,641 @@
package com.central.device.parser;
import com.central.device.parser.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* KMZ文件解析器
* 解析大疆无人机航线文件(KMZ格式),提取航点和动作数据
*
* @author dzc
* @date 2025-12-17
*/
@Component
@Slf4j
public class KmzFileParser {
/**
* 解析KMZ文件
*
* @param kmzBytes KMZ文件字节数组
* @return 解析结果
*/
public KmzParseResult parseKmz(byte[] kmzBytes) {
try {
// 1. 解压KMZ文件
Map<String, byte[]> extractedFiles = unzipKmz(kmzBytes);
// 2. 解析template.kml获取主要信息
byte[] templateKml = extractedFiles.get("wpmz/template.kml");
if (templateKml == null) {
return KmzParseResult.builder()
.success(false)
.errorMessage("template.kml文件不存在")
.build();
}
KmzParseResult result = parseTemplateKml(templateKml);
// 3. 使用任务配置中的autoFlightSpeed填充航点速度
fillWaypointSpeedsFromMissionConfig(result);
// 4. 解析waylines.wpml获取补充信息
byte[] waylinesWpml = extractedFiles.get("wpmz/waylines.wpml");
if (waylinesWpml != null) {
enrichWithWpmlData(result, waylinesWpml);
}
// 5. 如果没有从XML获取到数据,则计算航程和时长
if (result.getTotalDistance() == null || result.getTotalDuration() == null) {
calculateDistanceAndDuration(result);
}
result.setSuccess(true);
return result;
} catch (Exception e) {
log.error("解析KMZ文件失败", e);
return KmzParseResult.builder()
.success(false)
.errorMessage("解析失败: " + e.getMessage())
.build();
}
}
/**
* 解压KMZ文件
*/
private Map<String, byte[]> unzipKmz(byte[] kmzBytes) throws IOException {
Map<String, byte[]> files = new HashMap<>();
try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(kmzBytes))) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (!entry.isDirectory()) {
byte[] content = zis.readAllBytes();
files.put(entry.getName(), content);
}
zis.closeEntry();
}
}
return files;
}
/**
* 解析template.kml文件
*/
private KmzParseResult parseTemplateKml(byte[] kmlBytes) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new ByteArrayInputStream(kmlBytes));
KmzParseResult.KmzParseResultBuilder resultBuilder = KmzParseResult.builder();
List<WaypointData> waypoints = new ArrayList<>();
List<ActionData> actions = new ArrayList<>();
// 解析任务配置
MissionConfig missionConfig = parseMissionConfig(document);
resultBuilder.missionConfig(missionConfig);
// 解析航点
NodeList placemarks = document.getElementsByTagName("Placemark");
for (int i = 0; i < placemarks.getLength(); i++) {
Node placemarkNode = placemarks.item(i);
if (placemarkNode.getNodeType() == Node.ELEMENT_NODE) {
Element placemarkElement = (Element) placemarkNode;
WaypointData waypoint = parseWaypoint(placemarkElement);
if (waypoint != null) {
waypoints.add(waypoint);
// 解析该航点的动作
List<ActionData> waypointActions = parseActions(placemarkElement, waypoint.getIndex());
actions.addAll(waypointActions);
}
}
}
// 设置航点动作关联
for (WaypointData waypoint : waypoints) {
waypoint.setActions(new ArrayList<>());
for (ActionData action : actions) {
if (action.getWaypointIndex().equals(waypoint.getIndex())) {
waypoint.getActions().add(action);
}
}
}
// 4. 从XML中读取距离和时长信息
extractDistanceAndDuration(resultBuilder, document);
return resultBuilder
.waypoints(waypoints)
.actions(actions)
.build();
}
/**
* 解析任务配置
*/
private MissionConfig parseMissionConfig(Document document) {
MissionConfig.MissionConfigBuilder configBuilder = MissionConfig.builder();
NodeList missionConfigs = document.getElementsByTagName("wpml:missionConfig");
if (missionConfigs.getLength() > 0) {
Element missionConfigElement = (Element) missionConfigs.item(0);
configBuilder
.flyToWaylineMode(getElementText(missionConfigElement, "wpml:flyToWaylineMode"))
.finishAction(getElementText(missionConfigElement, "wpml:finishAction"))
.takeOffSecurityHeight(getElementBigDecimal(missionConfigElement, "wpml:takeOffSecurityHeight"))
.globalRthHeight(getElementBigDecimal(missionConfigElement, "wpml:globalRTHHeight"))
.exitOnRcLost(getElementText(missionConfigElement, "wpml:exitOnRcLost"))
.coordinateMode(getElementText(missionConfigElement, "wpml:coordinateMode"))
.heightMode(getElementText(missionConfigElement, "wpml:heightMode"));
}
// 解析模板类型
NodeList templateTypes = document.getElementsByTagName("wpml:templateType");
if (templateTypes.getLength() > 0) {
configBuilder.templateType(templateTypes.item(0).getTextContent());
}
// 解析自动飞行速度
NodeList autoFlightSpeeds = document.getElementsByTagName("wpml:autoFlightSpeed");
if (autoFlightSpeeds.getLength() > 0) {
String speedText = autoFlightSpeeds.item(0).getTextContent();
try {
configBuilder.autoFlightSpeed(new BigDecimal(speedText));
} catch (NumberFormatException e) {
log.warn("解析自动飞行速度失败: {}", speedText);
}
}
return configBuilder.build();
}
/**
* 解析航点
*/
private WaypointData parseWaypoint(Element placemarkElement) {
WaypointData.WaypointDataBuilder waypointBuilder = WaypointData.builder();
// 获取航点序号
String indexText = getElementText(placemarkElement, "wpml:index");
if (indexText == null) {
return null;
}
Integer index = Integer.parseInt(indexText);
waypointBuilder.index(index);
// 获取坐标
String coordinates = getElementText(placemarkElement, "coordinates");
if (coordinates != null) {
String[] coords = coordinates.split(",");
if (coords.length >= 2) {
waypointBuilder
.longitude(new BigDecimal(coords[0]))
.latitude(new BigDecimal(coords[1]));
}
}
// 获取高度信息
waypointBuilder
.height(getElementBigDecimal(placemarkElement, "wpml:height"))
.executeHeight(getElementBigDecimal(placemarkElement, "wpml:executeHeight"))
.ellipsoidHeight(getElementBigDecimal(placemarkElement, "wpml:ellipsoidHeight"));
// 获取飞行参数
waypointBuilder
.speed(getElementBigDecimal(placemarkElement, "wpml:waypointSpeed"))
.headingAngle(getElementBigDecimal(placemarkElement, "wpml:waypointHeadingAngle"))
.gimbalPitchAngle(getElementBigDecimal(placemarkElement, "wpml:gimbalPitchAngle"))
.gimbalRollAngle(getElementBigDecimal(placemarkElement, "wpml:gimbalRollAngle"))
.gimbalYawAngle(getElementBigDecimal(placemarkElement, "wpml:gimbalYawAngle"));
// 获取转弯信息
waypointBuilder
.turnMode(getElementText(placemarkElement, "wpml:turnMode"))
.turnDampingDist(getElementBigDecimal(placemarkElement, "wpml:turnDampingDist"))
.useStraightLine(getElementBoolean(placemarkElement, "wpml:useStraightLine", true))
.isRisky(getElementBoolean(placemarkElement, "wpml:isRisky", false));
// 统计动作组数量
NodeList actionGroups = placemarkElement.getElementsByTagName("wpml:actionGroup");
waypointBuilder.actionGroupCount(actionGroups.getLength());
return waypointBuilder.build();
}
/**
* 解析动作
*/
private List<ActionData> parseActions(Element placemarkElement, Integer waypointIndex) {
List<ActionData> actions = new ArrayList<>();
NodeList actionGroups = placemarkElement.getElementsByTagName("wpml:actionGroup");
for (int groupIndex = 0; groupIndex < actionGroups.getLength(); groupIndex++) {
Element actionGroupElement = (Element) actionGroups.item(groupIndex);
NodeList actionNodes = actionGroupElement.getElementsByTagName("wpml:action");
for (int actionIndex = 0; actionIndex < actionNodes.getLength(); actionIndex++) {
Element actionElement = (Element) actionNodes.item(actionIndex);
ActionData.ActionDataBuilder actionBuilder = ActionData.builder()
.waypointIndex(waypointIndex)
.actionGroupId(groupIndex)
.actionIndex(actionIndex);
// 获取动作类型
String actionType = getElementText(actionElement, "wpml:actionActuatorFunc");
actionBuilder.actionType(actionType);
// 解析动作参数
Map<String, Object> actionParams = new HashMap<>();
// 通用参数
actionBuilder
.payloadPositionIndex(getElementInteger(actionElement, "wpml:payloadParamIndex"))
.triggerType(getElementText(actionGroupElement, "wpml:triggerType"));
// 根据动作类型解析特定参数
parseActionSpecificParams(actionElement, actionBuilder, actionParams, actionType);
actionBuilder.actionParams(actionParams);
actions.add(actionBuilder.build());
}
}
return actions;
}
/**
* 解析动作特定参数
*/
private void parseActionSpecificParams(Element actionElement, ActionData.ActionDataBuilder actionBuilder, Map<String, Object> actionParams, String actionType) {
if ("hover".equals(actionType)) {
Double hoverTime = getElementDouble(actionElement, "wpml:hoverTime");
actionBuilder.hoverTime(hoverTime);
if (hoverTime != null) {
actionParams.put("hoverTime", hoverTime);
}
} else if ("rotateYaw".equals(actionType)) {
Double aircraftHeading = getElementDouble(actionElement, "wpml:aircraftHeading");
actionBuilder.aircraftHeading(aircraftHeading);
if (aircraftHeading != null) {
actionParams.put("heading", aircraftHeading);
}
} else if ("gimbalRotate".equals(actionType)) {
Double gimbalPitchRotateAngle = getElementDouble(actionElement, "wpml:gimbalPitchRotateAngle");
Double gimbalRollRotateAngle = getElementDouble(actionElement, "wpml:gimbalRollRotateAngle");
Double gimbalYawRotateAngle = getElementDouble(actionElement, "wpml:gimbalYawRotateAngle");
Double gimbalRotateSpeed = getElementDouble(actionElement, "wpml:gimbalRotateSpeed");
actionBuilder
.gimbalPitchRotateAngle(gimbalPitchRotateAngle)
.gimbalRollRotateAngle(gimbalRollRotateAngle)
.gimbalYawRotateAngle(gimbalYawRotateAngle)
.gimbalRotateSpeed(gimbalRotateSpeed);
if (gimbalPitchRotateAngle != null) {
actionParams.put("pitch", gimbalPitchRotateAngle);
}
if (gimbalYawRotateAngle != null) {
actionParams.put("yaw", gimbalYawRotateAngle);
}
} else if ("zoom".equals(actionType)) {
Double focalLength = getElementDouble(actionElement, "wpml:focalLength");
actionBuilder.focalLength(focalLength);
if (focalLength != null) {
actionParams.put("focalLength", focalLength);
}
} else if ("megaphone".equals(actionType)) {
String filePath = getElementText(actionElement, "wpml:megaphoneOperateFilePath");
actionBuilder.megaphoneFilePath(filePath);
if (filePath != null) {
actionParams.put("filePath", filePath);
}
}
// 拍照和录像的参数
String photoFileFormat = getElementText(actionElement, "wpml:photoFileFormat");
if (photoFileFormat != null) {
actionBuilder.photoFileFormat(photoFileFormat);
actionParams.put("fileFormat", photoFileFormat);
}
String videoFileFormat = getElementText(actionElement, "wpml:videoFileFormat");
if (videoFileFormat != null) {
actionBuilder.videoFileFormat(videoFileFormat);
actionParams.put("fileFormat", videoFileFormat);
}
}
/**
* 从XML中提取距离和时长信息
*/
private void extractDistanceAndDuration(KmzParseResult.KmzParseResultBuilder resultBuilder, Document document) {
// 尝试从多个位置提取距离和时长
// 1. 从 Folder/Document 中提取
NodeList folders = document.getElementsByTagName("Folder");
if (folders.getLength() > 0) {
Element folderElement = (Element) folders.item(0);
// 提取距离
String distanceText = getElementText(folderElement, "wpml:distance");
if (distanceText != null && !distanceText.isEmpty()) {
try {
resultBuilder.totalDistance(Double.parseDouble(distanceText));
log.info("从XML中提取到距离: {}", distanceText);
} catch (NumberFormatException e) {
log.warn("解析距离失败: {}", distanceText);
}
}
// 提取时长
String durationText = getElementText(folderElement, "wpml:duration");
if (durationText != null && !durationText.isEmpty()) {
try {
resultBuilder.totalDuration(Double.parseDouble(durationText));
log.info("从XML中提取到时长: {}", durationText);
} catch (NumberFormatException e) {
log.warn("解析时长失败: {}", durationText);
}
}
}
// 2. 从 Document 根节点直接提取
if (document.getDocumentElement() != null) {
Element docElement = document.getDocumentElement();
// 尝试其他可能的标签名称
String[] distanceTags = {"distance", "wpml:distance", "totalDistance"};
String[] durationTags = {"duration", "wpml:duration", "totalDuration"};
for (String tag : distanceTags) {
String distanceText = getElementText(docElement, tag);
if (distanceText != null && !distanceText.isEmpty()) {
try {
resultBuilder.totalDistance(Double.parseDouble(distanceText));
log.info("从根节点提取到距离: {}", distanceText);
break;
} catch (NumberFormatException e) {
log.debug("解析距离失败: tag={}, value={}", tag, distanceText);
}
}
}
for (String tag : durationTags) {
String durationText = getElementText(docElement, tag);
if (durationText != null && !durationText.isEmpty()) {
try {
resultBuilder.totalDuration(Double.parseDouble(durationText));
log.info("从根节点提取到时长: {}", durationText);
break;
} catch (NumberFormatException e) {
log.debug("解析时长失败: tag={}, value={}", tag, durationText);
}
}
}
}
// 3. 从所有子节点中搜索
NodeList allNodes = document.getElementsByTagName("*");
for (int i = 0; i < allNodes.getLength(); i++) {
Element element = (Element) allNodes.item(i);
// 查找包含"duration"文本的节点
if (resultBuilder.build().getTotalDuration() == null) {
String nodeName = element.getNodeName().toLowerCase();
String durationText = element.getTextContent().trim();
// 只从明确表示持续时间的节点中提取
boolean isDurationNode = (nodeName.contains("duration") &&
!nodeName.contains("timestamp") &&
!nodeName.contains("time")) ||
nodeName.equals("wpml:duration");
if (isDurationNode && durationText.matches(".*\\d+\\.?\\d*.*")) {
try {
// 尝试提取数字
String numStr = durationText.replaceAll("[^\\d.]", "");
// 过滤掉时间戳(通常大于10^10)
if (!numStr.isEmpty()) {
double value = Double.parseDouble(numStr);
// 只接受合理的持续时间值(秒),过滤掉时间戳(毫秒)
if (value < 100000) { // 100000秒约等于27小时,作为合理上限
resultBuilder.totalDuration(value);
log.info("从文本内容提取到时长: {}", value);
} else {
log.debug("忽略时间戳值: {}", value);
}
}
} catch (NumberFormatException e) {
log.debug("从文本解析时长失败: {}", durationText);
}
}
}
}
}
/**
* 使用任务配置中的autoFlightSpeed填充航点速度
*/
private void fillWaypointSpeedsFromMissionConfig(KmzParseResult result) {
if (result.getMissionConfig() == null || result.getMissionConfig().getAutoFlightSpeed() == null) {
log.debug("任务配置中没有autoFlightSpeed,跳过航点速度填充");
return;
}
BigDecimal autoFlightSpeed = result.getMissionConfig().getAutoFlightSpeed();
List<WaypointData> waypoints = result.getWaypoints();
if (waypoints != null && !waypoints.isEmpty()) {
int updatedCount = 0;
for (WaypointData waypoint : waypoints) {
// 只有当航点没有设置速度时,才使用autoFlightSpeed
if (waypoint.getSpeed() == null) {
waypoint.setSpeed(autoFlightSpeed);
updatedCount++;
}
}
log.info("使用autoFlightSpeed({})填充了{}个航点的速度", autoFlightSpeed, updatedCount);
}
}
/**
* 使用WPML数据丰富解析结果
*/
private void enrichWithWpmlData(KmzParseResult result, byte[] wpmlBytes) {
// TODO: 解析waylines.wpml文件,补充执行高度等信息
// 这里可以根据需要实现WPML格式的解析
log.debug("解析waylines.wpml文件,大小: {} bytes", wpmlBytes.length);
}
/**
* 计算航程和时长
*/
private void calculateDistanceAndDuration(KmzParseResult result) {
List<WaypointData> waypoints = result.getWaypoints();
if (waypoints == null || waypoints.size() < 2) {
return;
}
double totalDistance = 0;
double totalDuration = 0;
// 获取默认飞行速度(优先使用任务配置中的autoFlightSpeed)
BigDecimal defaultSpeed = BigDecimal.valueOf(1.0); // 默认1m/s
if (result.getMissionConfig() != null && result.getMissionConfig().getAutoFlightSpeed() != null) {
defaultSpeed = result.getMissionConfig().getAutoFlightSpeed();
log.debug("使用任务配置中的autoFlightSpeed作为默认速度: {}", defaultSpeed);
}
// 首先计算所有航点的动作时间总和
double totalActionTime = 0;
for (WaypointData waypoint : waypoints) {
if (waypoint.getActions() != null && !waypoint.getActions().isEmpty()) {
for (ActionData action : waypoint.getActions()) {
if ("hover".equals(action.getActionType()) && action.getHoverTime() != null) {
totalActionTime += action.getHoverTime();
}
}
}
}
// 计算总飞行距离
double totalFlyDistance = 0;
for (int i = 1; i < waypoints.size(); i++) {
WaypointData prev = waypoints.get(i - 1);
WaypointData curr = waypoints.get(i);
// 计算两航点间的距离
double distance = calculateDistance(
prev.getLongitude().doubleValue(),
prev.getLatitude().doubleValue(),
curr.getLongitude().doubleValue(),
curr.getLatitude().doubleValue()
);
totalFlyDistance += distance;
}
// 计算飞行时间(使用平均速度)
double avgSpeed = defaultSpeed.doubleValue();
// 计算所有设置了速度的航点的平均速度
double speedSum = 0;
int speedCount = 0;
for (WaypointData waypoint : waypoints) {
if (waypoint.getSpeed() != null) {
speedSum += waypoint.getSpeed().doubleValue();
speedCount++;
}
}
if (speedCount > 0) {
avgSpeed = speedSum / speedCount;
}
// 飞行时间 = 距离 / 平均速度
double flyTime = avgSpeed > 0 ? totalFlyDistance / avgSpeed : 0;
// 总时长 = 飞行时间 + 动作时间
totalDuration = flyTime + totalActionTime;
totalDistance = totalFlyDistance;
result.setTotalDistance(totalDistance);
result.setTotalDuration(totalDuration);
// 添加调试日志
log.info("解析完成 - 航点数: {}, 总距离: {}米, 总时长: {}秒",
waypoints.size(), totalDistance, totalDuration);
}
/**
* 计算两点间距离(Haversine公式)
*/
private double calculateDistance(double lng1, double lat1, double lng2, double lat2) {
final double R = 6371000; // 地球半径(米)
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng / 2) * Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
// 辅助方法
private String getElementText(Element parent, String tagName) {
NodeList nodes = parent.getElementsByTagName(tagName);
if (nodes.getLength() > 0) {
return nodes.item(0).getTextContent().trim();
}
return null;
}
private BigDecimal getElementBigDecimal(Element parent, String tagName) {
String text = getElementText(parent, tagName);
if (text != null && !text.isEmpty()) {
try {
return new BigDecimal(text);
} catch (NumberFormatException e) {
log.warn("解析BigDecimal失败: {} = {}", tagName, text);
}
}
return null;
}
private Integer getElementInteger(Element parent, String tagName) {
String text = getElementText(parent, tagName);
if (text != null && !text.isEmpty()) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
log.warn("解析Integer失败: {} = {}", tagName, text);
}
}
return null;
}
private Double getElementDouble(Element parent, String tagName) {
String text = getElementText(parent, tagName);
if (text != null && !text.isEmpty()) {
try {
return Double.parseDouble(text);
} catch (NumberFormatException e) {
log.warn("解析Double失败: {} = {}", tagName, text);
}
}
return null;
}
private Boolean getElementBoolean(Element parent, String tagName, Boolean defaultValue) {
String text = getElementText(parent, tagName);
if (text != null && !text.isEmpty()) {
return Boolean.parseBoolean(text);
}
return defaultValue;
}
}
@@ -0,0 +1,106 @@
package com.central.device.parser.model;
import lombok.Data;
import lombok.Builder;
import java.util.Map;
/**
* 动作数据
*
* @author dzc
* @date 2025-12-17
*/
@Data
@Builder
public class ActionData {
/**
* 航点序号
*/
private Integer waypointIndex;
/**
* 动作组ID
*/
private Integer actionGroupId;
/**
* 动作序号(组内)
*/
private Integer actionIndex;
/**
* 动作类型
*/
private String actionType;
/**
* 动作参数
*/
private Map<String, Object> actionParams;
/**
* 触发类型
*/
private String triggerType;
/**
* 延迟时间(毫秒)
*/
private Long delayTime;
/**
* 相机位置索引
*/
private Integer payloadPositionIndex;
/**
* 拍照相关参数
*/
private String photoFileFormat;
/**
* 录像相关参数
*/
private String videoFileFormat;
/**
* 云台俯仰旋转角度
*/
private Double gimbalPitchRotateAngle;
/**
* 云台横滚旋转角度
*/
private Double gimbalRollRotateAngle;
/**
* 云台偏航旋转角度
*/
private Double gimbalYawRotateAngle;
/**
* 云台旋转速度
*/
private Double gimbalRotateSpeed;
/**
* 飞机航向角
*/
private Double aircraftHeading;
/**
* 悬停时间(秒)
*/
private Double hoverTime;
/**
* 焦距(毫米)
*/
private Double focalLength;
/**
* 音频文件路径
*/
private String megaphoneFilePath;
}
@@ -0,0 +1,51 @@
package com.central.device.parser.model;
import lombok.Data;
import lombok.Builder;
import java.util.List;
/**
* KMZ文件解析结果
*
* @author dzc
* @date 2025-12-17
*/
@Data
@Builder
public class KmzParseResult {
/**
* 任务配置
*/
private MissionConfig missionConfig;
/**
* 航点列表
*/
private List<WaypointData> waypoints;
/**
* 动作列表
*/
private List<ActionData> actions;
/**
* 解析错误信息
*/
private String errorMessage;
/**
* 解析是否成功
*/
private boolean success;
/**
* 总航程(米)
*/
private Double totalDistance;
/**
* 总时长(秒)
*/
private Double totalDuration;
}
@@ -0,0 +1,71 @@
package com.central.device.parser.model;
import lombok.Data;
import lombok.Builder;
import java.math.BigDecimal;
/**
* 任务配置
*
* @author dzc
* @date 2025-12-17
*/
@Data
@Builder
public class MissionConfig {
/**
* 飞往航线模式
*/
private String flyToWaylineMode;
/**
* 完成动作
*/
private String finishAction;
/**
* 起飞安全高度
*/
private BigDecimal takeOffSecurityHeight;
/**
* 全局返航高度
*/
private BigDecimal globalRthHeight;
/**
* 遥控器失联动作
*/
private String exitOnRcLost;
/**
* 坐标系
*/
private String coordinateMode;
/**
* 高度模式
*/
private String heightMode;
/**
* 自动飞行速度
*/
private BigDecimal autoFlightSpeed;
/**
* 无人机信息
*/
private String droneInfo;
/**
* 载荷信息
*/
private String payloadInfo;
/**
* 模板类型
*/
private String templateType;
}
@@ -0,0 +1,107 @@
package com.central.device.parser.model;
import lombok.Data;
import lombok.Builder;
import java.math.BigDecimal;
import java.util.List;
/**
* 航点数据
*
* @author dzc
* @date 2025-12-17
*/
@Data
@Builder
public class WaypointData {
/**
* 航点序号
*/
private Integer index;
/**
* 经度
*/
private BigDecimal longitude;
/**
* 纬度
*/
private BigDecimal latitude;
/**
* 相对高度(米)
*/
private BigDecimal height;
/**
* 执行高度(米)
*/
private BigDecimal executeHeight;
/**
* 椭球高度(米)
*/
private BigDecimal ellipsoidHeight;
/**
* 飞行速度(米/秒)
*/
private BigDecimal speed;
/**
* 航向模式
*/
private String headingMode;
/**
* 航向角(度)
*/
private BigDecimal headingAngle;
/**
* 云台俯仰角(度)
*/
private BigDecimal gimbalPitchAngle;
/**
* 云台横滚角(度)
*/
private BigDecimal gimbalRollAngle;
/**
* 云台偏航角(度)
*/
private BigDecimal gimbalYawAngle;
/**
* 转弯模式
*/
private String turnMode;
/**
* 转弯阻尼距离(米)
*/
private BigDecimal turnDampingDist;
/**
* 是否使用直线飞行
*/
private Boolean useStraightLine;
/**
* 是否为风险点
*/
private Boolean isRisky;
/**
* 动作组数量
*/
private Integer actionGroupCount;
/**
* 动作列表
*/
private List<ActionData> actions;
}
@@ -0,0 +1,76 @@
package com.central.device.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.device.entity.DroneFlightTrack;
import java.time.LocalDateTime;
import java.util.List;
/**
* 飞行轨迹服务接口
*
* @author dzc
* @date 2025-12-17
*/
public interface IDroneFlightTrackService extends IService<DroneFlightTrack> {
/**
* 记录轨迹点
*
* @param track 轨迹点数据
* @return 是否成功
*/
boolean recordTrackPoint(DroneFlightTrack track);
/**
* 批量记录轨迹点
*
* @param tracks 轨迹点列表
* @return 成功数量
*/
int batchRecordTrackPoints(List<DroneFlightTrack> tracks);
/**
* 获取设备飞行轨迹
*
* @param deviceSn 设备SN
* @param jobId 任务ID(可选)
* @param routeId 航线任务ID(可选)
* @param startTime 开始时间(可选)
* @param endTime 结束时间(可选)
* @param limit 限制数量(可选)
* @return 轨迹点列表
*/
List<DroneFlightTrack> getTrackPoints(String deviceSn, String jobId, String routeId,
LocalDateTime startTime, LocalDateTime endTime, Integer limit);
/**
* 获取设备最新轨迹点
*
* @param deviceSn 设备SN
* @return 最新轨迹点
*/
DroneFlightTrack getLatestTrackPoint(String deviceSn);
/**
* 删除指定时间之前的轨迹
*
* @param deviceSn 设备SN
* @param beforeTime 删除此时间之前的轨迹
* @return 删除数量
*/
int deleteTrackPointsBefore(String deviceSn, LocalDateTime beforeTime);
/**
* 统计轨迹点数量
*
* @param deviceSn 设备SN(可选)
* @param jobId 任务ID(可选)
* @param routeId 航线任务ID(可选)
* @param startTime 开始时间(可选)
* @param endTime 结束时间(可选)
* @return 轨迹点数量
*/
Long countTrackPoints(String deviceSn, String jobId, String routeId,
LocalDateTime startTime, LocalDateTime endTime);
}
@@ -0,0 +1,46 @@
package com.central.device.service;
import com.central.device.parser.model.KmzParseResult;
import com.central.device.model.vo.WaypointActionVO;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* 航线解析服务接口
*
* @author dzc
* @date 2025-12-17
*/
public interface IWaylineParseService {
/**
* 解析航线任务
*
* @param routeId 航线任务ID
* @return 解析结果
*/
KmzParseResult parseRoute(String routeId);
/**
* 异步解析航线任务
*
* @param routeId 航线任务ID
* @return CompletableFuture
*/
CompletableFuture<Void> parseRouteAsync(String routeId);
/**
* 批量解析航线任务
*
* @param routeIds 航线任务ID列表
*/
void batchParseRoutes(String... routeIds);
/**
* 根据航线ID获取动作列表
*
* @param routeId 航线任务ID
* @return 动作列表
*/
List<WaypointActionVO> getActionsByRouteId(String routeId);
}
@@ -0,0 +1,90 @@
package com.central.device.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.device.entity.WaylineRoute;
import java.util.List;
/**
* 航线任务服务接口
*
* @author dzc
* @date 2025-12-17
*/
public interface IWaylineRouteService extends IService<WaylineRoute> {
/**
* 根据航迹文件ID查询航线任务列表
*
* @param fileWaylineId 航迹文件ID
* @return 航线任务列表
*/
List<WaylineRoute> listByFileWaylineId(String fileWaylineId);
/**
* 根据设备SN查询绑定的航线任务列表
*
* @param deviceSn 设备SN
* @return 航线任务列表
*/
List<WaylineRoute> listByDeviceSn(String deviceSn);
/**
* 根据航线任务ID查询
*
* @param routeId 航线任务ID
* @return 航线任务
*/
WaylineRoute getByRouteId(String routeId);
/**
* 创建航线任务
*
* @param routeName 航线任务名称
* @param fileWaylineId 航迹文件ID
* @param deviceSn 设备SN
* @param deviceName 设备名称
* @param remark 备注
* @return 创建的航线任务
*/
WaylineRoute createRoute(String routeName, String fileWaylineId, String deviceSn, String deviceName, String remark);
/**
* 更新解析状态
*
* @param routeId 航线任务ID
* @param parseStatus 解析状态
*/
void updateParseStatus(String routeId, Integer parseStatus);
/**
* 更新解析状态和错误信息
*
* @param routeId 航线任务ID
* @param parseStatus 解析状态
* @param parseError 解析错误信息
*/
void updateParseStatus(String routeId, Integer parseStatus, String parseError);
/**
* 更新航线任务统计信息
*
* @param routeId 航线任务ID
* @param waypointCount 航点数量
* @param actionCount 动作数量
* @param totalDistance 总航程
* @param totalDuration 总时长
*/
void updateRouteStats(String routeId, Integer waypointCount, Integer actionCount,
Double totalDistance, Double totalDuration);
/**
* 绑定航迹文件到设备并解析
*
* @param deviceSn 设备SN
* @param waylineId 航线ID
* @param waylineName 航线名称
* @param workspaceId 工作空间ID
*/
void bindWaylineToDevice(String deviceSn, String waylineId, String waylineName, String workspaceId);
}
@@ -0,0 +1,39 @@
package com.central.device.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.device.entity.WaylineWaypoint;
import java.util.List;
/**
* 航点服务接口
*
* @author dzc
* @date 2025-12-17
*/
public interface IWaylineWaypointService extends IService<WaylineWaypoint> {
/**
* 根据航线任务ID查询航点列表(按序号排序)
*
* @param routeId 航线任务ID
* @return 航点列表
*/
List<WaylineWaypoint> listByRouteIdOrderByIndex(String routeId);
/**
* 根据航线任务ID删除航点
*
* @param routeId 航线任务ID
* @return 删除数量
*/
int deleteByRouteId(String routeId);
/**
* 统计航点数量
*
* @param routeId 航线任务ID
* @return 航点数量
*/
Integer countByRouteId(String routeId);
}
@@ -0,0 +1,156 @@
package com.central.device.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.device.entity.DroneFlightTrack;
import com.central.device.mapper.DroneFlightTrackMapper;
import com.central.device.service.IDroneFlightTrackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
/**
* 飞行轨迹服务实现
*
* @author dzc
* @date 2025-12-17
*/
@Service
@Slf4j
public class DroneFlightTrackServiceImpl extends ServiceImpl<DroneFlightTrackMapper, DroneFlightTrack> implements IDroneFlightTrackService {
@Override
public boolean recordTrackPoint(DroneFlightTrack track) {
try {
// 设置记录时间
if (track.getRecordTime() == null) {
track.setRecordTime(LocalDateTime.now());
}
return save(track);
} catch (Exception e) {
log.error("记录轨迹点失败: deviceSn={}", track.getDeviceSn(), e);
return false;
}
}
@Override
public int batchRecordTrackPoints(List<DroneFlightTrack> tracks) {
if (tracks == null || tracks.isEmpty()) {
return 0;
}
try {
// 设置记录时间
LocalDateTime now = LocalDateTime.now();
tracks.forEach(track -> {
if (track.getRecordTime() == null) {
track.setRecordTime(now);
}
});
return baseMapper.batchInsert(tracks);
} catch (Exception e) {
log.error("批量记录轨迹点失败", e);
return 0;
}
}
@Override
public List<DroneFlightTrack> getTrackPoints(String deviceSn, String jobId, String routeId,
LocalDateTime startTime, LocalDateTime endTime, Integer limit) {
try {
return baseMapper.selectTrackPoints(deviceSn, jobId, routeId, startTime, endTime, limit);
} catch (Exception e) {
log.error("获取轨迹点失败: deviceSn={}, jobId={}", deviceSn, jobId, e);
return null;
}
}
@Override
public DroneFlightTrack getLatestTrackPoint(String deviceSn) {
try {
return baseMapper.selectLatestTrackPoint(deviceSn);
} catch (Exception e) {
log.error("获取最新轨迹点失败: deviceSn={}", deviceSn, e);
return null;
}
}
@Override
public int deleteTrackPointsBefore(String deviceSn, LocalDateTime beforeTime) {
try {
return baseMapper.deleteByDeviceSnAndTimeBefore(deviceSn, beforeTime);
} catch (Exception e) {
log.error("删除历史轨迹失败: deviceSn={}, beforeTime={}", deviceSn, beforeTime, e);
return 0;
}
}
@Override
public Long countTrackPoints(String deviceSn, String jobId, String routeId,
LocalDateTime startTime, LocalDateTime endTime) {
try {
return baseMapper.countTrackPoints(deviceSn, jobId, routeId, startTime, endTime);
} catch (Exception e) {
log.error("统计轨迹点数量失败", e);
return 0L;
}
}
/**
* 从无人机OSD数据构建轨迹点
*
* @param deviceSn 设备SN
* @param osdData OSD数据
* @param jobId 任务ID
* @param routeId 航线任务ID
* @return 轨迹点
*/
public DroneFlightTrack buildTrackFromOsd(String deviceSn, Object osdData, String jobId, String routeId) {
DroneFlightTrack track = new DroneFlightTrack();
track.setDeviceSn(deviceSn);
track.setJobId(jobId);
track.setRouteId(routeId);
// TODO: 根据实际的OSD数据格式提取位置信息
// 这里需要根据实际的数据结构进行解析
try {
// 示例代码,需要根据实际情况调整
if (osdData instanceof com.alibaba.fastjson.JSONObject) {
com.alibaba.fastjson.JSONObject json = (com.alibaba.fastjson.JSONObject) osdData;
// 提取位置信息
track.setLongitude(json.getBigDecimal("longitude"));
track.setLatitude(json.getBigDecimal("latitude"));
track.setAltitude(json.getBigDecimal("elevation"));
track.setHeight(json.getBigDecimal("height"));
// 提取速度信息
track.setHorizontalSpeed(json.getBigDecimal("horizontal_speed"));
track.setVerticalSpeed(json.getBigDecimal("vertical_speed"));
// 提取姿态信息
track.setHeading(json.getBigDecimal("attitude_head"));
track.setPitch(json.getBigDecimal("attitude_pitch"));
track.setRoll(json.getBigDecimal("attitude_roll"));
// 其他信息
track.setFlightMode(json.getInteger("flight_mode"));
track.setBatteryPercent(json.getInteger("battery_percent"));
// 记录时间
if (json.containsKey("timestamp")) {
Long timestamp = json.getLong("timestamp");
track.setRecordTime(LocalDateTime.now()); // 实际应该转换timestamp
}
}
} catch (Exception e) {
log.warn("解析OSD数据失败", e);
}
return track;
}
}
@@ -0,0 +1,386 @@
package com.central.device.service.impl;
import com.central.device.entity.WaylineAction;
import com.central.device.entity.WaylineRoute;
import com.central.device.entity.WaylineWaypoint;
import com.central.device.feign.FileCenterService;
import com.central.device.mapper.WaylineActionMapper;
import com.central.device.mapper.WaylineRouteMapper;
import com.central.device.mapper.WaylineWaypointMapper;
import com.central.device.parser.KmzFileParser;
import com.central.device.parser.model.ActionData;
import com.central.device.parser.model.KmzParseResult;
import com.central.device.parser.model.WaypointData;
import com.central.device.service.IWaylineParseService;
import com.central.device.service.ILineFileService;
import com.central.device.model.LineFile;
import com.central.device.model.vo.WaypointActionVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.util.*;
import java.util.concurrent.CompletableFuture;
/**
* 航线解析服务实现
*
* @author dzc
* @date 2025-12-17
*/
@Service
@Slf4j
public class WaylineParseServiceImpl implements IWaylineParseService {
@Autowired
private WaylineRouteMapper waylineRouteMapper;
@Autowired
private WaylineWaypointMapper waylineWaypointMapper;
@Autowired
private WaylineActionMapper waylineActionMapper;
@Autowired
private KmzFileParser kmzFileParser;
@Autowired
private ILineFileService lineFileService;
@Resource
private FileCenterService fileCenterService;
@Autowired
private ObjectMapper objectMapper;
@Override
@Transactional
public KmzParseResult parseRoute(String routeId) {
try {
// 1. 获取航线任务信息
WaylineRoute route = waylineRouteMapper.selectByRouteId(routeId);
if (route == null) {
throw new RuntimeException("航线任务不存在: " + routeId);
}
// 2. 更新状态为解析中
waylineRouteMapper.updateParseStatus(routeId, WaylineRoute.ParseStatus.PARSING.getCode());
// 3. 下载并解析KMZ文件
byte[] kmzBytes = downloadKmzFile(route.getFileWaylineId());
if (kmzBytes == null || kmzBytes.length == 0) {
throw new RuntimeException("KMZ文件下载失败或为空");
}
// 4. 解析KMZ文件
KmzParseResult parseResult = kmzFileParser.parseKmz(kmzBytes);
if (!parseResult.isSuccess()) {
throw new RuntimeException("KMZ文件解析失败: " + parseResult.getErrorMessage());
}
// 5. 保存解析结果
saveParseResult(routeId, parseResult);
// 6. 更新统计信息
updateRouteStats(routeId, parseResult);
// 7. 更新状态为已解析
waylineRouteMapper.updateParseStatus(routeId, WaylineRoute.ParseStatus.PARSED.getCode());
log.info("航线任务解析成功: routeId={}, 航点数={}, 动作数={}",
routeId, parseResult.getWaypoints().size(), parseResult.getActions().size());
return parseResult;
} catch (Exception e) {
log.error("解析航线任务失败: routeId={}", routeId, e);
waylineRouteMapper.updateParseStatusWithError(
routeId,
WaylineRoute.ParseStatus.FAILED.getCode(),
e.getMessage()
);
throw new RuntimeException("解析失败: " + e.getMessage(), e);
}
}
@Override
@Async("waylineParseExecutor")
public CompletableFuture<Void> parseRouteAsync(String routeId) {
try {
parseRoute(routeId);
return CompletableFuture.completedFuture(null);
} catch (Exception e) {
log.error("异步解析航线任务失败: routeId={}", routeId, e);
return CompletableFuture.failedFuture(e);
}
}
@Override
@Async("waylineParseExecutor")
public void batchParseRoutes(String... routeIds) {
if (routeIds == null || routeIds.length == 0) {
return;
}
log.info("开始批量解析航线任务,数量: {}", routeIds.length);
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (String routeId : routeIds) {
CompletableFuture<Void> future = parseRouteAsync(routeId);
futures.add(future);
}
// 等待所有任务完成
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.thenRun(() -> log.info("批量解析航线任务完成"))
.exceptionally(e -> {
log.error("批量解析航线任务出现异常", e);
return null;
});
}
/**
* 下载KMZ文件
*/
private byte[] downloadKmzFile(String fileWaylineId) {
try {
// 根据fileWaylineId从wayline_file表获取文件信息
LineFile lineFile = lineFileService.findLineFileByWaylineId(fileWaylineId);
if (lineFile == null) {
throw new RuntimeException("航迹文件不存在: " + fileWaylineId);
}
String fileurl = fileCenterService.getFileViewUrl(lineFile.getWaylineId());
if (fileurl == null || fileurl.isEmpty()) {
throw new RuntimeException("航迹文件URL为空");
}
// 下载文件
try (InputStream in = new URL(fileurl).openStream()) {
return in.readAllBytes();
}
} catch (IOException e) {
log.error("下载KMZ文件失败: fileWaylineId={}", fileWaylineId, e);
throw new RuntimeException("下载文件失败: " + e.getMessage(), e);
}
}
/**
* 保存解析结果
*/
private void saveParseResult(String routeId, KmzParseResult parseResult) {
// 1. 清除旧的解析数据
waylineWaypointMapper.deleteByRouteId(routeId);
waylineActionMapper.deleteByRouteId(routeId);
// 2. 保存航点数据
List<WaypointData> waypointDataList = parseResult.getWaypoints();
if (waypointDataList != null && !waypointDataList.isEmpty()) {
List<WaylineWaypoint> waypoints = new ArrayList<>();
for (WaypointData data : waypointDataList) {
WaylineWaypoint waypoint = buildWaypointEntity(routeId, data);
waypoints.add(waypoint);
}
// 批量插入航点
waylineWaypointMapper.batchInsert(waypoints);
}
// 3. 保存动作数据
List<ActionData> actionDataList = parseResult.getActions();
if (actionDataList != null && !actionDataList.isEmpty()) {
// 根据航点索引获取航点ID
List<WaylineWaypoint> waypointEntities = waylineWaypointMapper.selectByRouteIdOrderByIndex(routeId);
Map<Integer, Long> waypointIndexToIdMap = new HashMap<>();
for (WaylineWaypoint waypoint : waypointEntities) {
waypointIndexToIdMap.put(waypoint.getWaypointIndex(), waypoint.getId());
}
List<WaylineAction> actions = new ArrayList<>();
for (ActionData data : actionDataList) {
WaylineAction action = buildActionEntity(routeId, data, waypointIndexToIdMap);
if (action != null) {
actions.add(action);
}
}
// 批量插入动作
waylineActionMapper.batchInsert(actions);
}
}
/**
* 构建航点实体
*/
private WaylineWaypoint buildWaypointEntity(String routeId, WaypointData data) {
WaylineWaypoint waypoint = new WaylineWaypoint();
waypoint.setRouteId(routeId);
waypoint.setWaypointIndex(data.getIndex());
waypoint.setLongitude(data.getLongitude());
waypoint.setLatitude(data.getLatitude());
waypoint.setHeight(data.getHeight());
waypoint.setExecuteHeight(data.getExecuteHeight());
waypoint.setEllipsoidHeight(data.getEllipsoidHeight());
waypoint.setSpeed(data.getSpeed());
waypoint.setHeadingMode(data.getHeadingMode());
waypoint.setHeadingAngle(data.getHeadingAngle());
waypoint.setGimbalPitchAngle(data.getGimbalPitchAngle());
waypoint.setTurnMode(data.getTurnMode());
waypoint.setTurnDampingDist(data.getTurnDampingDist());
waypoint.setUseStraightLine(data.getUseStraightLine() != null && data.getUseStraightLine() ? 1 : 0);
waypoint.setIsRisky(data.getIsRisky() != null && data.getIsRisky() ? 1 : 0);
waypoint.setActionGroupCount(data.getActionGroupCount());
return waypoint;
}
/**
* 构建动作实体
*/
private WaylineAction buildActionEntity(String routeId, ActionData data, Map<Integer, Long> waypointIndexToIdMap) {
Long waypointId = waypointIndexToIdMap.get(data.getWaypointIndex());
if (waypointId == null) {
log.warn("航点ID未找到: waypointIndex={}", data.getWaypointIndex());
return null;
}
WaylineAction action = new WaylineAction();
action.setWaypointId(waypointId);
action.setRouteId(routeId);
action.setActionGroupId(data.getActionGroupId());
action.setActionIndex(data.getActionIndex());
action.setActionType(data.getActionType());
action.setTriggerType(data.getTriggerType());
// 将动作参数转换为JSON字符串
if (data.getActionParams() != null && !data.getActionParams().isEmpty()) {
try {
String paramsJson = objectMapper.writeValueAsString(data.getActionParams());
action.setActionParams(paramsJson);
} catch (Exception e) {
log.warn("动作参数序列化失败", e);
}
}
return action;
}
/**
* 更新航线任务统计信息
*/
private void updateRouteStats(String routeId, KmzParseResult parseResult) {
int waypointCount = parseResult.getWaypoints() != null ? parseResult.getWaypoints().size() : 0;
int actionCount = parseResult.getActions() != null ? parseResult.getActions().size() : 0;
Double totalDistance = parseResult.getTotalDistance();
Double totalDuration = parseResult.getTotalDuration();
// 转换Double为BigDecimal
BigDecimal distance = totalDistance != null ? BigDecimal.valueOf(totalDistance) : null;
BigDecimal duration = totalDuration != null ? BigDecimal.valueOf(totalDuration) : null;
// 获取autoFlightSpeed
BigDecimal autoFlightSpeed = null;
if (parseResult.getMissionConfig() != null && parseResult.getMissionConfig().getAutoFlightSpeed() != null) {
autoFlightSpeed = parseResult.getMissionConfig().getAutoFlightSpeed();
}
waylineRouteMapper.updateRouteStats(routeId, waypointCount, actionCount, distance, duration, autoFlightSpeed);
}
@Override
public List<WaypointActionVO> getActionsByRouteId(String routeId) {
List<WaylineAction> actions = waylineActionMapper.selectByRouteId(routeId);
List<WaypointActionVO> vos = new ArrayList<>();
if (actions != null && !actions.isEmpty()) {
for (WaylineAction action : actions) {
WaypointActionVO vo = new WaypointActionVO();
vo.setActionGroupId(action.getActionGroupId());
vo.setActionIndex(action.getActionIndex());
vo.setActionType(action.getActionType());
vo.setTriggerType(action.getTriggerType());
// 解析动作参数,从中提取其他字段
if (StringUtils.hasText(action.getActionParams())) {
try {
Map<String, Object> params = objectMapper.readValue(action.getActionParams(), Map.class);
vo.setActionParams(params);
// 从参数中提取具体字段(如果存在)
if (params.containsKey("delayTime")) {
Object delayTime = params.get("delayTime");
if (delayTime instanceof Number) {
vo.setDelayTime(((Number) delayTime).longValue());
}
}
if (params.containsKey("payloadPositionIndex")) {
Object payloadIndex = params.get("payloadPositionIndex");
if (payloadIndex instanceof Number) {
vo.setPayloadPositionIndex(((Number) payloadIndex).intValue());
}
}
if (params.containsKey("hoverTime")) {
Object hoverTime = params.get("hoverTime");
if (hoverTime instanceof Number) {
vo.setHoverTime(((Number) hoverTime).doubleValue());
}
}
if (params.containsKey("aircraftHeading")) {
Object heading = params.get("aircraftHeading");
if (heading instanceof Number) {
vo.setAircraftHeading(((Number) heading).doubleValue());
}
}
if (params.containsKey("gimbalPitchRotateAngle")) {
Object pitch = params.get("gimbalPitchRotateAngle");
if (pitch instanceof Number) {
vo.setGimbalPitchRotateAngle(((Number) pitch).doubleValue());
}
}
if (params.containsKey("gimbalYawRotateAngle")) {
Object yaw = params.get("gimbalYawRotateAngle");
if (yaw instanceof Number) {
vo.setGimbalYawRotateAngle(((Number) yaw).doubleValue());
}
}
if (params.containsKey("focalLength")) {
Object focalLength = params.get("focalLength");
if (focalLength instanceof Number) {
vo.setFocalLength(((Number) focalLength).doubleValue());
}
}
// megaphone相关的参数
if (params.containsKey("megaphoneOperateFilePath")) {
Object filePath = params.get("megaphoneOperateFilePath");
if (filePath != null) {
vo.setMegaphoneFilePath(filePath.toString());
}
} else if (params.containsKey("megaphoneFilePath")) {
Object filePath = params.get("megaphoneFilePath");
if (filePath != null) {
vo.setMegaphoneFilePath(filePath.toString());
}
}
} catch (Exception e) {
log.warn("解析动作参数失败: routeId={}, actionId={}", routeId, action.getId(), e);
}
}
vos.add(vo);
}
}
return vos;
}
}
@@ -0,0 +1,173 @@
package com.central.device.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.device.entity.WaylineRoute;
import com.central.device.mapper.WaylineRouteMapper;
import com.central.device.mapper.WaylineActionMapper;
import com.central.device.mapper.WaylineWaypointMapper;
import com.central.device.mapper.DroneFlightTrackMapper;
import com.central.device.service.IWaylineRouteService;
import com.central.device.model.LineFile;
import com.central.device.service.IWaylineParseService;
import com.central.device.parser.model.KmzParseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
/**
* 航线任务服务实现
*
* @author dzc
* @date 2025-12-17
*/
@Service
@Slf4j
public class WaylineRouteServiceImpl extends ServiceImpl<WaylineRouteMapper, WaylineRoute> implements IWaylineRouteService {
@Autowired
private IWaylineParseService waylineParseService;
@Autowired
private WaylineActionMapper waylineActionMapper;
@Autowired
private WaylineWaypointMapper waylineWaypointMapper;
@Autowired
private DroneFlightTrackMapper droneFlightTrackMapper;
@Override
public List<WaylineRoute> listByFileWaylineId(String fileWaylineId) {
return baseMapper.selectByFileWaylineId(fileWaylineId);
}
@Override
public List<WaylineRoute> listByDeviceSn(String deviceSn) {
return baseMapper.selectByDeviceSn(deviceSn);
}
@Override
public WaylineRoute getByRouteId(String routeId) {
return baseMapper.selectByRouteId(routeId);
}
@Override
@Transactional
public WaylineRoute createRoute(String routeName, String fileWaylineId, String deviceSn, String deviceName, String remark) {
// 创建航线任务
WaylineRoute route = new WaylineRoute();
route.setRouteId(UUID.randomUUID().toString());
route.setRouteName(routeName);
route.setFileWaylineId(fileWaylineId);
route.setDeviceSn(deviceSn);
route.setDeviceName(deviceName);
route.setRemark(remark);
// 设置默认值
route.setParseStatus(WaylineRoute.ParseStatus.NOT_PARSED.getCode());
route.setWaypointCount(0);
route.setActionCount(0);
route.setStatus(1);
route.setCoordinateMode("WGS84");
route.setHeightMode("relativeToStartPoint");
// 保存到数据库
save(route);
log.info("创建航线任务成功: routeId={}, routeName={}, deviceSn={}",
route.getRouteId(), routeName, deviceSn);
return route;
}
@Override
@Transactional
public void updateParseStatus(String routeId, Integer parseStatus) {
baseMapper.updateParseStatus(routeId, parseStatus);
}
@Override
@Transactional
public void updateParseStatus(String routeId, Integer parseStatus, String parseError) {
baseMapper.updateParseStatusWithError(routeId, parseStatus, parseError);
}
@Override
@Transactional
public void updateRouteStats(String routeId, Integer waypointCount, Integer actionCount,
Double totalDistance, Double totalDuration) {
// 转换Double为BigDecimal
BigDecimal distance = totalDistance != null ? BigDecimal.valueOf(totalDistance) : null;
BigDecimal duration = totalDuration != null ? BigDecimal.valueOf(totalDuration) : null;
baseMapper.updateRouteStats(routeId, waypointCount, actionCount, distance, duration, null);
}
@Override
@Transactional
public void bindWaylineToDevice(String deviceSn, String waylineId, String waylineName, String workspaceId) {
log.info("开始绑定航迹文件到设备: deviceSn={}, waylineId={}, waylineName={}",
deviceSn, waylineId, waylineName);
// 1. 检查并删除已存在的绑定(避免重复数据)
List<WaylineRoute> existingRoutes = baseMapper.selectByDeviceSnAndFileWaylineId(deviceSn, waylineId);
if (existingRoutes != null && !existingRoutes.isEmpty()) {
log.info("发现已存在的绑定关系,删除旧数据: deviceSn={}, waylineId={}, count={}",
deviceSn, waylineId, existingRoutes.size());
// 先删除相关的航点、动作和飞行轨迹数据
for (WaylineRoute existingRoute : existingRoutes) {
// 删除航点动作数据
waylineActionMapper.deleteByRouteId(existingRoute.getRouteId());
// 删除航点数据
waylineWaypointMapper.deleteByRouteId(existingRoute.getRouteId());
// 删除飞行轨迹数据
droneFlightTrackMapper.deleteByRouteId(existingRoute.getRouteId());
log.debug("已删除航线任务的相关数据: routeId={}", existingRoute.getRouteId());
}
// 删除航线任务
baseMapper.deleteBindingByDeviceAndWayline(deviceSn, waylineId);
}
// 2. 创建航线任务
String routeName = StringUtils.hasText(waylineName) ? waylineName : waylineName;
WaylineRoute route = createRoute(routeName, waylineId, deviceSn, null, null);
// 3. 设置工作空间ID
if (StringUtils.hasText(workspaceId)) {
route.setWorkspaceId(workspaceId);
updateById(route);
}
// 4. 解析航迹文件
try {
updateParseStatus(route.getRouteId(), WaylineRoute.ParseStatus.PARSING.getCode());
KmzParseResult result = waylineParseService.parseRoute(route.getRouteId());
if (result.isSuccess()) {
updateParseStatus(route.getRouteId(), WaylineRoute.ParseStatus.PARSED.getCode());
log.info("航迹文件解析成功: routeId={}, waypointCount={}",
route.getRouteId(), result.getWaypoints().size());
} else {
updateParseStatus(route.getRouteId(), WaylineRoute.ParseStatus.FAILED.getCode(),
result.getErrorMessage());
throw new RuntimeException("航迹文件解析失败: " + result.getErrorMessage());
}
} catch (Exception e) {
updateParseStatus(route.getRouteId(), WaylineRoute.ParseStatus.FAILED.getCode(),
e.getMessage());
throw new RuntimeException("解析航迹文件时发生错误: " + e.getMessage(), e);
}
log.info("航迹文件绑定成功: routeId={}, deviceSn={}", route.getRouteId(), deviceSn);
}
}
@@ -0,0 +1,34 @@
package com.central.device.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.device.entity.WaylineWaypoint;
import com.central.device.mapper.WaylineWaypointMapper;
import com.central.device.service.IWaylineWaypointService;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 航点服务实现
*
* @author dzc
* @date 2025-12-17
*/
@Service
public class WaylineWaypointServiceImpl extends ServiceImpl<WaylineWaypointMapper, WaylineWaypoint> implements IWaylineWaypointService {
@Override
public List<WaylineWaypoint> listByRouteIdOrderByIndex(String routeId) {
return baseMapper.selectByRouteIdOrderByIndex(routeId);
}
@Override
public int deleteByRouteId(String routeId) {
return baseMapper.deleteByRouteId(routeId);
}
@Override
public Integer countByRouteId(String routeId) {
return baseMapper.countByRouteId(routeId);
}
}
@@ -103,6 +103,40 @@ public class DeviceStatusSseController {
}
}
/**
* 使用 Beacon API 断开SSE连接(POST方式)
* 用于浏览器刷新/关闭时,sendBeacon只支持POST请求
* 这是一个备用端点,与DELETE端点功能相同
*
* @param deviceSn 设备SN
* @param body 包含 sessionId 的请求体
* @return 断开结果
*/
@Operation(summary = "Beacon方式断开SSE连接(浏览器刷新/关闭时使用)")
@PostMapping("/device-status/{deviceSn}/disconnect")
public org.springframework.http.ResponseEntity<String> disconnectDeviceStatusByBeacon(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn,
@org.springframework.web.bind.annotation.RequestBody(required = false) java.util.Map<String, String> body) {
String clientSessionId = body != null ? body.get("sessionId") : null;
if (clientSessionId == null || clientSessionId.trim().isEmpty()) {
log.warn("Beacon断开请求缺少sessionId: deviceSn={}", deviceSn);
return org.springframework.http.ResponseEntity.badRequest().body("缺少sessionId");
}
String sessionId = clientSessionId + "_" + deviceSn;
log.info("Beacon方式断开SSE连接: session={}, deviceSn={}", sessionId, deviceSn);
boolean success = sseEmitterManager.removeEmitterBySessionId(sessionId, deviceSn);
if (success) {
return org.springframework.http.ResponseEntity.ok("连接已断开");
} else {
return org.springframework.http.ResponseEntity.ok("连接不存在或已断开");
}
}
/**
* 订阅无人机遥测数据(msg_alarm)
* 进入操控台时调用,开始接收无人机实时遥测数据
@@ -223,4 +257,37 @@ public class DeviceStatusSseController {
return org.springframework.http.ResponseEntity.ok("连接不存在或已断开");
}
}
/**
* 使用 Beacon API 断开无人机遥测数据SSE连接(POST方式)
* 用于浏览器刷新/关闭时,sendBeacon只支持POST请求
*
* @param deviceSn 设备SN
* @param body 包含 sessionId 的请求体
* @return 断开结果
*/
@Operation(summary = "Beacon方式断开无人机遥测数据SSE连接(浏览器刷新/关闭时使用)")
@PostMapping("/drone-telemetry/{deviceSn}/disconnect")
public org.springframework.http.ResponseEntity<String> disconnectDroneTelemetrySseByBeacon(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn,
@org.springframework.web.bind.annotation.RequestBody(required = false) java.util.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 org.springframework.http.ResponseEntity.badRequest().body("缺少sessionId");
}
String sessionId = "drone_" + clientSessionId + "_" + deviceSn;
log.info("Beacon方式断开无人机遥测数据SSE连接: session={}, deviceSn={}", sessionId, deviceSn);
boolean success = sseEmitterManager.removeEmitterBySessionId(sessionId, deviceSn);
if (success) {
return org.springframework.http.ResponseEntity.ok("无人机遥测数据连接已断开");
} else {
return org.springframework.http.ResponseEntity.ok("连接不存在或已断开");
}
}
}
@@ -2,9 +2,13 @@ package com.central.device.sse.manager;
import com.central.device.sse.dto.DeviceRealtimeDataDTO;
import com.central.device.sse.model.EmitterWrapper;
import com.central.device.websocket.client.JetLinksWebSocketClient;
import com.central.device.websocket.handler.DeviceMessageHandler;
import com.central.device.websocket.manager.DeviceSubscriptionManager;
import com.central.device.websocket.manager.SubscriptionPoolService;
import com.central.device.websocket.manager.SubscriptionPoolService.TopicType;
import com.central.device.websocket.model.DeviceRealtimeData;
import com.central.device.websocket.model.SubscriptionTopic;
import com.central.device.websocket.model.DroneRealtimeData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
@@ -41,6 +45,12 @@ public class SseEmitterManager {
@Autowired
private DeviceMessageHandler messageHandler;
@Autowired
private SubscriptionPoolService subscriptionPoolService;
@Autowired
private JetLinksWebSocketClient jetLinksWebSocketClient;
/**
* SSE连接池: sessionId -> EmitterWrapper
*/
@@ -48,6 +58,7 @@ public class SseEmitterManager {
/**
* 设备订阅计数: deviceSn -> count(引用计数)
* 【保留】用于本地快速查询,与Redis订阅池配合使用
*/
private final ConcurrentHashMap<String, Integer> deviceRefCount = new ConcurrentHashMap<>();
@@ -56,6 +67,11 @@ public class SseEmitterManager {
*/
private ScheduledExecutorService heartbeatExecutor;
/**
* 孤儿订阅清理执行器
*/
private ScheduledExecutorService cleanupExecutor;
/**
* 初始化
*/
@@ -64,8 +80,15 @@ public class SseEmitterManager {
// 设置DeviceMessageHandler的SSE管理器引用(解决循环依赖)
messageHandler.setSseEmitterManager(this);
// 【P1优化】设置JetLinksWebSocketClient的订阅池服务引用
// 用于WebSocket重连时基于Redis状态重新订阅
jetLinksWebSocketClient.setSubscriptionPoolService(subscriptionPoolService);
// 启动心跳
startHeartbeat();
// 启动孤儿订阅清理任务
startOrphanSubscriptionCleanup();
}
/**
@@ -123,15 +146,23 @@ public class SseEmitterManager {
log.error("发送连接确认消息失败: session={}, error={}", sessionId, e.getMessage());
}
// 增加设备引用计数
// 增加本地引用计数(快速查询用)
int refCount = deviceRefCount.compute(deviceSn, (k, v) -> v == null ? 1 : v + 1);
// 关键:如果是首次订阅该设备,触发WebSocket懒加载和设备订阅
if (refCount == 1) {
log.info("设备 {} 首次订阅,触发WebSocket懒加载", deviceSn);
// 【关键】使用Redis订阅池管理订阅,支持多客户端隔离
// 添加机库状态订阅(fire_alarm, online, offline)
boolean isFirstFireAlarm = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.FIRE_ALARM);
boolean isFirstOnline = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.ONLINE);
boolean isFirstOffline = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.OFFLINE);
// 只有当该设备的某个主题是首次被订阅时,才触发WebSocket订阅
if (isFirstFireAlarm || isFirstOnline || isFirstOffline) {
log.info("设备 {} 首次订阅(Redis池),触发WebSocket懒加载, isFirstFireAlarm={}, isFirstOnline={}, isFirstOffline={}",
deviceSn, isFirstFireAlarm, isFirstOnline, isFirstOffline);
deviceSubscriptionManager.subscribeDevice(deviceSn, tenantId);
} else {
log.info("设备 {} 新增订阅,复用现有连接,当前引用计数: {}", deviceSn, refCount);
log.info("设备 {} 新增订阅,复用现有WebSocket订阅,本地引用计数: {}, Redis订阅数: {}",
deviceSn, refCount, subscriptionPoolService.getSubscriberCount(deviceSn, TopicType.FIRE_ALARM));
}
// 立即推送一次当前设备数据(如果存在)
@@ -148,6 +179,7 @@ public class SseEmitterManager {
/**
* 移除SSE连接(减少设备引用计数,必要时取消订阅)
* 【v3.1优化】使用Redis订阅池,支持多客户端隔离,互不影响
*/
private void removeEmitter(String sessionId, String deviceSn) {
EmitterWrapper wrapper = emitters.remove(sessionId);
@@ -169,27 +201,79 @@ public class SseEmitterManager {
log.info("移除SSE连接: session={}, deviceSn={}, isDroneTelemetry={}, 剩余连接数: {}",
sessionId, deviceSn, isDroneTelemetry, emitters.size());
// 【关键】如果是无人机SSE连接,需要先取消 msg_alarm 订阅
// 无论引用计数是否归零,都要取消无人机遥测数据订阅
if (isDroneTelemetry) {
log.info("无人机SSE连接断开,取消 msg_alarm 订阅: deviceSn={}", deviceSn);
deviceSubscriptionManager.unsubscribeDroneTelemetry(deviceSn);
}
// 减少设备引用计数
Integer refCount = deviceRefCount.compute(deviceSn, (k, v) -> {
// 减少本地引用计数(快速查询用)
Integer localRefCount = deviceRefCount.compute(deviceSn, (k, v) -> {
if (v == null || v <= 1) {
return null; // 移除key
}
return v - 1;
});
// 关键:如果引用计数归零,取消所有设备订阅(机库订阅)
if (refCount == null) {
log.info("设备 {} 引用计数归零,取消所有订阅", deviceSn);
deviceSubscriptionManager.unsubscribeDevice(deviceSn);
// 【关键】使用Redis订阅池管理取消订阅,保证多客户端隔离
if (isDroneTelemetry) {
// 无人机SSE连接:取消该session的msg_alarm订阅
boolean isLastMsgAlarm = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.MSG_ALARM);
// 【P0修复】同时移除在 addDroneTelemetryEmitter 中添加的 ONLINE/OFFLINE 订阅
// 这些订阅是为了触发WebSocket懒加载而添加的,断开时必须同步移除
boolean isLastOnline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.ONLINE);
boolean isLastOffline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.OFFLINE);
log.info("无人机SSE连接断开: sessionId={}, deviceSn={}, isLastMsgAlarm={}, isLastOnline={}, isLastOffline={}",
sessionId, deviceSn, isLastMsgAlarm, isLastOnline, isLastOffline);
// 只有当这是最后一个msg_alarm订阅者时,才取消无人机遥测WebSocket订阅
if (isLastMsgAlarm) {
log.info("设备 {} 无人机遥测数据最后一个订阅者离开,取消WebSocket订阅", deviceSn);
deviceSubscriptionManager.unsubscribeDroneTelemetry(deviceSn);
} else {
log.info("设备 {} 无人机遥测数据仍有其他订阅者,保持WebSocket订阅, 剩余: {}",
deviceSn, subscriptionPoolService.getSubscriberCount(deviceSn, TopicType.MSG_ALARM));
}
// 如果ONLINE和OFFLINE都是最后一个订阅者,且没有机库SSE连接订阅,则取消设备基础订阅
if (isLastOnline && isLastOffline) {
// 检查是否还有fire_alarm订阅(机库SSE连接)
boolean hasFireAlarmSubscribers = subscriptionPoolService.hasSubscribers(deviceSn, TopicType.FIRE_ALARM);
if (!hasFireAlarmSubscribers) {
log.info("设备 {} 所有基础主题订阅者都已离开,取消设备WebSocket订阅", deviceSn);
deviceSubscriptionManager.unsubscribeDevice(deviceSn);
} else {
log.info("设备 {} 仍有机库SSE连接,保持设备WebSocket订阅", deviceSn);
}
}
} else {
log.info("设备 {} 仍有 {} 个订阅,保持连接", deviceSn, refCount);
// 机库SSE连接:取消该session的fire_alarm, online, offline订阅
boolean isLastFireAlarm = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.FIRE_ALARM);
boolean isLastOnline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.ONLINE);
boolean isLastOffline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.OFFLINE);
log.info("机库SSE连接断开: sessionId={}, deviceSn={}, isLastFireAlarm={}, isLastOnline={}, isLastOffline={}",
sessionId, deviceSn, isLastFireAlarm, isLastOnline, isLastOffline);
// 【P0修复】分别处理每个主题的WebSocket订阅取消,而不是要求所有条件同时满足
// 1. 如果 fire_alarm 是最后一个订阅者,取消 FIRE_ALARM 主题的WebSocket订阅
if (isLastFireAlarm) {
log.info("设备 {} 机库数据(FIRE_ALARM)最后一个订阅者离开,取消该主题的WebSocket订阅", deviceSn);
jetLinksWebSocketClient.unsubscribeDevice(deviceSn, SubscriptionTopic.EVENT_FIRE_ALARM);
} else {
log.info("设备 {} FIRE_ALARM仍有其他订阅者,保持WebSocket订阅, 剩余: {}",
deviceSn, subscriptionPoolService.getSubscriberCount(deviceSn, TopicType.FIRE_ALARM));
}
// 2. 如果 ONLINE 和 OFFLINE 都是最后一个订阅者,检查是否还有 msg_alarm 订阅
if (isLastOnline && isLastOffline) {
boolean hasMsgAlarmSubscribers = subscriptionPoolService.hasSubscribers(deviceSn, TopicType.MSG_ALARM);
if (!hasMsgAlarmSubscribers) {
log.info("设备 {} ONLINE/OFFLINE基础主题最后一个订阅者离开,取消WebSocket订阅", deviceSn);
jetLinksWebSocketClient.unsubscribeDevice(deviceSn,
SubscriptionTopic.ONLINE, SubscriptionTopic.OFFLINE);
// 移除设备数据缓存
messageHandler.removeDevice(deviceSn);
} else {
log.info("设备 {} 仍有无人机遥测(MSG_ALARM)订阅,保持ONLINE/OFFLINE的WebSocket订阅", deviceSn);
}
}
}
}
@@ -284,6 +368,7 @@ public class SseEmitterManager {
/**
* 启动心跳
* 【优化】缩短心跳间隔到15秒,更快检测断开的连接
*/
private void startHeartbeat() {
heartbeatExecutor = Executors.newSingleThreadScheduledExecutor();
@@ -308,16 +393,126 @@ public class SseEmitterManager {
});
// 清理失败的连接
deadEmitters.forEach(sessionId -> {
EmitterWrapper wrapper = emitters.get(sessionId);
if (wrapper != null) {
removeEmitter(sessionId, wrapper.getDeviceSn());
if (!deadEmitters.isEmpty()) {
log.info("心跳检测到 {} 个断开的连接,开始清理", deadEmitters.size());
deadEmitters.forEach(sessionId -> {
EmitterWrapper wrapper = emitters.get(sessionId);
if (wrapper != null) {
log.info("心跳清理断开的SSE连接: session={}, deviceSn={}, isDroneTelemetry={}",
sessionId, wrapper.getDeviceSn(), wrapper.getIsDroneTelemetry());
removeEmitter(sessionId, wrapper.getDeviceSn());
}
});
}
}, 15000, 15000, TimeUnit.MILLISECONDS); // 【优化】每15秒发送一次心跳(原30秒)
log.info("SSE心跳已启动,间隔: 15秒");
}
/**
* 启动孤儿订阅清理任务
* 定期检查Redis订阅池中的session是否还有对应的SSE连接
* 如果没有,则清理该session的所有订阅
* 【优化】缩短间隔到30秒,更快清理孤儿订阅
*/
private void startOrphanSubscriptionCleanup() {
cleanupExecutor = Executors.newSingleThreadScheduledExecutor();
cleanupExecutor.scheduleAtFixedRate(() -> {
try {
cleanupOrphanSubscriptions();
} catch (Exception e) {
log.error("孤儿订阅清理任务执行失败: {}", e.getMessage(), e);
}
}, 30000, 30000, TimeUnit.MILLISECONDS); // 【优化】每30秒执行一次(原60秒)
log.info("孤儿订阅清理任务已启动,间隔: 30秒");
}
/**
* 清理孤儿订阅
* 检查Redis订阅池中记录的session是否还有对应的SSE连接
* 用于处理浏览器刷新等场景下,前端无法正常发送断开请求的情况
* 【修复】同时清理WebSocket订阅,而不仅仅是Redis记录
*/
private void cleanupOrphanSubscriptions() {
// 获取当前所有活跃的SSE session
java.util.Set<String> activeSessionIds = new java.util.HashSet<>(emitters.keySet());
log.debug("孤儿订阅清理开始: 当前活跃SSE连接数={}", activeSessionIds.size());
// 获取所有Redis中的session
java.util.Set<String> allRedisSessionIds = subscriptionPoolService.getAllSessionIds();
if (allRedisSessionIds.isEmpty()) {
log.debug("孤儿订阅清理完成: Redis中没有订阅记录");
return;
}
int cleanedCount = 0;
// 遍历Redis中的session,检查是否还有对应的SSE连接
for (String sessionId : allRedisSessionIds) {
if (!activeSessionIds.contains(sessionId)) {
log.info("发现孤儿订阅: sessionId={}, 开始清理", sessionId);
// 清理该session的所有订阅,并获取需要取消WebSocket订阅的列表
java.util.List<SubscriptionPoolService.DeviceTopicPair> toUnsubscribe =
subscriptionPoolService.removeAllSubscriptions(sessionId);
// 【关键】实际取消WebSocket订阅
for (SubscriptionPoolService.DeviceTopicPair pair : toUnsubscribe) {
String deviceSn = pair.getDeviceSn();
SubscriptionPoolService.TopicType topicType = pair.getTopicType();
log.info("孤儿清理: 取消设备 {} 的 {} WebSocket订阅", deviceSn, topicType);
// 根据主题类型取消对应的WebSocket订阅
switch (topicType) {
case FIRE_ALARM:
jetLinksWebSocketClient.unsubscribeDevice(deviceSn, SubscriptionTopic.EVENT_FIRE_ALARM);
break;
case MSG_ALARM:
jetLinksWebSocketClient.unsubscribeDevice(deviceSn, SubscriptionTopic.EVENT_MSG_ALARM);
break;
case ONLINE:
jetLinksWebSocketClient.unsubscribeDevice(deviceSn, SubscriptionTopic.ONLINE);
break;
case OFFLINE:
jetLinksWebSocketClient.unsubscribeDevice(deviceSn, SubscriptionTopic.OFFLINE);
break;
}
}
});
}, 30000, 30000, TimeUnit.MILLISECONDS); // 每30秒发送一次心跳
// 如果清理了该设备的所有订阅,移除设备数据缓存
if (!toUnsubscribe.isEmpty()) {
// 检查该设备是否还有其他订阅
String deviceSn = toUnsubscribe.get(0).getDeviceSn();
boolean hasAnySubscriber =
subscriptionPoolService.hasSubscribers(deviceSn, SubscriptionPoolService.TopicType.FIRE_ALARM) ||
subscriptionPoolService.hasSubscribers(deviceSn, SubscriptionPoolService.TopicType.MSG_ALARM) ||
subscriptionPoolService.hasSubscribers(deviceSn, SubscriptionPoolService.TopicType.ONLINE) ||
subscriptionPoolService.hasSubscribers(deviceSn, SubscriptionPoolService.TopicType.OFFLINE);
log.info("SSE心跳已启动,间隔: 30秒");
if (!hasAnySubscriber) {
log.info("孤儿清理: 设备 {} 所有订阅已清理,移除设备数据缓存", deviceSn);
messageHandler.removeDevice(deviceSn);
}
}
cleanedCount++;
}
}
if (cleanedCount > 0) {
log.info("孤儿订阅清理完成: 清理了 {} 个孤儿session", cleanedCount);
// 打印当前订阅状态
if (log.isDebugEnabled()) {
subscriptionPoolService.printSubscriptionStatus();
}
} else {
log.debug("孤儿订阅清理完成: 没有发现孤儿订阅");
}
}
/**
@@ -412,24 +607,32 @@ public class SseEmitterManager {
log.error("发送无人机连接确认消息失败: session={}, error={}", sessionId, e.getMessage());
}
// 增加设备引用计数(无人机专用)
// 增加本地引用计数(快速查询用)
int refCount = deviceRefCount.compute(deviceSn, (k, v) -> v == null ? 1 : v + 1);
// 【关键修复】无论引用计数是多少,都需要订阅无人机遥测数据(msg_alarm)
// 因为机库订阅(addEmitter)只订阅了 fire_alarm,不包括 msg_alarm
// 所以这里需要额外订阅 msg_alarm 主题
log.info("设备 {} 订阅无人机遥测数据,当前引用计数: {}", deviceSn, refCount);
// 【关键】使用Redis订阅池管理无人机遥测数据订阅
// 添加 msg_alarm 订阅到Redis池
boolean isFirstMsgAlarm = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.MSG_ALARM);
// 如果是首次订阅该设备(refCount == 1),需要先订阅基础主题
if (refCount == 1) {
log.info("设备 {} 首次订阅,触发WebSocket懒加载并订阅基础主题", deviceSn);
log.info("设备 {} 订阅无人机遥测数据: sessionId={}, isFirstSubscriber={}, localRefCount={}",
deviceSn, sessionId, isFirstMsgAlarm, refCount);
// 如果是首次订阅该设备的基础主题,需要先订阅基础主题
boolean isFirstOnline = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.ONLINE);
boolean isFirstOffline = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.OFFLINE);
if (isFirstOnline || isFirstOffline) {
log.info("设备 {} 首次订阅基础主题,触发WebSocket懒加载", deviceSn);
deviceSubscriptionManager.subscribeDevice(deviceSn, tenantId);
}
// 无论如何都要订阅无人机遥测数据主题(msg_alarm)
// 这是独立于机库订阅的,需要单独调用
log.info("设备 {} 订阅无人机遥测主题 msg_alarm", deviceSn);
deviceSubscriptionManager.subscribeDroneTelemetry(deviceSn);
// 只有当该设备的 msg_alarm 是首次被订阅时,才向WebSocket发送订阅
if (isFirstMsgAlarm) {
log.info("设备 {} 无人机遥测数据首次订阅(Redis池),向WebSocket发送订阅", deviceSn);
deviceSubscriptionManager.subscribeDroneTelemetry(deviceSn);
} else {
log.info("设备 {} 无人机遥测数据已有其他订阅者,复用现有WebSocket订阅, Redis订阅数: {}",
deviceSn, subscriptionPoolService.getSubscriberCount(deviceSn, TopicType.MSG_ALARM));
}
// 立即推送一次当前无人机数据(如果存在)
com.central.device.websocket.model.DeviceRealtimeData currentData = messageHandler.getDeviceData(deviceSn);
@@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONObject;
import com.central.device.websocket.config.WebSocketProperties;
import com.central.device.websocket.handler.DeviceMessageHandler;
import com.central.device.websocket.manager.DeviceCommandManager;
import com.central.device.websocket.manager.SubscriptionPoolService;
import com.central.device.websocket.manager.TokenManager;
import com.central.device.websocket.model.SubscriptionMessage;
import com.central.device.websocket.model.SubscriptionTopic;
@@ -95,6 +96,11 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
*/
private ScheduledExecutorService reconnectExecutor;
/**
* 订阅池服务(用于获取当前有效订阅状态)
*/
private SubscriptionPoolService subscriptionPoolService;
/**
* 构造函数
*/
@@ -107,6 +113,13 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
this.webSocketClient = new StandardWebSocketClient();
}
/**
* 设置订阅池服务(延迟注入,避免循环依赖)
*/
public void setSubscriptionPoolService(SubscriptionPoolService subscriptionPoolService) {
this.subscriptionPoolService = subscriptionPoolService;
}
/**
* 初始化(仅初始化线程池,不自动连接)
*/
@@ -435,6 +448,8 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
public void unsubscribeDevice(String deviceSn, SubscriptionTopic... topics) {
if (!isConnected()) {
log.warn("WebSocket未连接,无法取消订阅: {}", deviceSn);
// 即使未连接,也要清理本地状态
cleanupLocalState(deviceSn, topics);
return;
}
@@ -450,15 +465,37 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
unsubscribeTopic(topic, deviceSn);
}
// 检查是否所有设备的订阅都已取消,如果是则断开WebSocket连接以节省资源
// 注意:这里检查deviceSubscriptionCounts而不是subscribedTopics
// 因为一个设备可能有多个主题订阅(fire_alarm + msg_alarm)
if (deviceSubscriptionCounts.isEmpty()) {
log.info("所有设备的所有订阅已取消,自动断开WebSocket连接以节省资源");
// 【修复】基于 subscribedTopics(实际订阅列表)来判断是否断开连接
// 而不是依赖可能不同步的 deviceSubscriptionCounts
if (subscribedTopics.isEmpty()) {
log.info("所有主题订阅已取消,自动断开WebSocket连接以节省资源");
// 清空本地计数器
deviceSubscriptionCounts.clear();
closeConnection();
} else {
log.info("仍有{}个设备有活跃订阅,保持WebSocket连接: {}",
deviceSubscriptionCounts.size(), deviceSubscriptionCounts.keySet());
log.info("仍有{}个主题订阅,保持WebSocket连接: {}",
subscribedTopics.size(), subscribedTopics);
}
}
/**
* 清理设备的本地订阅状态(WebSocket未连接时使用)
*/
private void cleanupLocalState(String deviceSn, SubscriptionTopic... topics) {
if (topics == null) return;
for (SubscriptionTopic topicEnum : topics) {
String topic = topicEnum.getTopic(deviceSn);
subscribedTopics.remove(topic);
}
// 检查该设备是否还有其他主题订阅
boolean hasOtherTopics = subscribedTopics.stream()
.anyMatch(t -> t.contains("/" + deviceSn + "/"));
if (!hasOtherTopics) {
deviceSubscriptionCounts.remove(deviceSn);
log.info("设备 {} 本地订阅状态已清理", deviceSn);
}
}
@@ -468,6 +505,12 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
private void subscribeTopic(SubscriptionTopic topicEnum, String deviceSn) {
String topic = topicEnum.getTopic(deviceSn);
// 【修复】如果主题已经在订阅列表中,跳过重复订阅
if (subscribedTopics.contains(topic)) {
log.debug("主题已订阅,跳过重复订阅: topic={}, deviceSn={}", topic, deviceSn);
return;
}
SubscriptionMessage message = SubscriptionMessage.builder()
.type("sub")
.topic(topic)
@@ -478,12 +521,11 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
send(JSON.toJSONString(message));
subscribedTopics.add(topic);
// 更新设备订阅计数
// 更新设备订阅计数(只有实际发送订阅时才增加)
deviceSubscriptionCounts.computeIfAbsent(deviceSn, k -> new AtomicInteger(0)).incrementAndGet();
log.info("发送订阅消息: topic={}, id={}, message={}, 设备{}订阅计数: {}",
topic, message.getId(), JSON.toJSONString(message),
deviceSn, deviceSubscriptionCounts.get(deviceSn).get());
log.info("发送订阅消息: topic={}, 设备{}订阅计数: {}",
topic, deviceSn, deviceSubscriptionCounts.get(deviceSn).get());
}
/**
@@ -508,23 +550,29 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
send(JSON.toJSONString(message));
subscribedTopics.remove(topic);
// 更新设备订阅计数
AtomicInteger count = deviceSubscriptionCounts.get(deviceSn);
if (count != null) {
int newCount = count.decrementAndGet();
if (newCount <= 0) {
deviceSubscriptionCounts.remove(deviceSn);
log.info("设备{}所有订阅已取消,从订阅计数中移除", deviceSn);
// 【修复】检查该设备是否还有其他主题订阅(基于实际订阅列表)
boolean hasOtherTopics = subscribedTopics.stream()
.anyMatch(t -> t.contains("/" + deviceSn + "/"));
if (!hasOtherTopics) {
// 该设备没有其他订阅了,直接移除计数器
deviceSubscriptionCounts.remove(deviceSn);
log.info("设备 {} 所有主题订阅已取消,从计数器中移除", deviceSn);
} else {
// 更新设备订阅计数
AtomicInteger count = deviceSubscriptionCounts.get(deviceSn);
if (count != null) {
count.decrementAndGet();
}
}
log.info("取消订阅主题: topic={}, id={}, 剩余订阅数: {}, 剩余主题: {}, 设备{}剩余订阅计数: {}",
topic, message.getId(), subscribedTopics.size(), subscribedTopics,
deviceSn, count != null ? count.get() : 0);
log.info("取消订阅主题: topic={}, 剩余主题数: {}, 剩余主题: {}",
topic, subscribedTopics.size(), subscribedTopics);
}
/**
* 重新订阅所有主题
* 【P1优化】基于Redis订阅池状态决定订阅哪些主题,避免与实际订阅状态不同步
*/
private void resubscribeAll() {
if (subscribedTopics.isEmpty()) {
@@ -539,7 +587,7 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
// 清空设备订阅计数,重新订阅时会重新计算
deviceSubscriptionCounts.clear();
// 按设备分组重新订阅(订阅所有标准主题)
// 按设备分组重新订阅
Set<String> deviceSns = new HashSet<>();
topics.forEach(topic -> {
String deviceSn = extractDeviceSn(topic);
@@ -548,14 +596,55 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
}
});
// 为每个设备重新订阅标准主题(订阅关键主题)
// 【P1优化】根据Redis订阅池状态决定订阅哪些主题
// 如果有订阅池服务,则只订阅Redis中有记录的主题
deviceSns.forEach(deviceSn -> {
subscribeDevice(deviceSn,
SubscriptionTopic.ONLINE,
SubscriptionTopic.OFFLINE,
SubscriptionTopic.EVENT_FIRE_ALARM, // fire_alarm(机库状态数据)
SubscriptionTopic.EVENT_MSG_ALARM // msg_alarm(无人机遥测数据)
);
if (subscriptionPoolService != null) {
// 基于Redis订阅池状态重新订阅
boolean hasFireAlarm = subscriptionPoolService.hasSubscribers(deviceSn, SubscriptionPoolService.TopicType.FIRE_ALARM);
boolean hasMsgAlarm = subscriptionPoolService.hasSubscribers(deviceSn, SubscriptionPoolService.TopicType.MSG_ALARM);
boolean hasOnline = subscriptionPoolService.hasSubscribers(deviceSn, SubscriptionPoolService.TopicType.ONLINE);
boolean hasOffline = subscriptionPoolService.hasSubscribers(deviceSn, SubscriptionPoolService.TopicType.OFFLINE);
log.info("设备 {} Redis订阅状态: fire_alarm={}, msg_alarm={}, online={}, offline={}",
deviceSn, hasFireAlarm, hasMsgAlarm, hasOnline, hasOffline);
// 只有Redis中有订阅者的主题才重新订阅
java.util.List<SubscriptionTopic> topicsToSubscribe = new java.util.ArrayList<>();
// 基础主题(有任何SSE连接就需要订阅)
if (hasOnline || hasFireAlarm || hasMsgAlarm) {
topicsToSubscribe.add(SubscriptionTopic.ONLINE);
}
if (hasOffline || hasFireAlarm || hasMsgAlarm) {
topicsToSubscribe.add(SubscriptionTopic.OFFLINE);
}
// 机库数据主题
if (hasFireAlarm) {
topicsToSubscribe.add(SubscriptionTopic.EVENT_FIRE_ALARM);
}
// 无人机遥测数据主题(只有进入操控台才订阅)
if (hasMsgAlarm) {
topicsToSubscribe.add(SubscriptionTopic.EVENT_MSG_ALARM);
}
if (!topicsToSubscribe.isEmpty()) {
subscribeDevice(deviceSn, topicsToSubscribe.toArray(new SubscriptionTopic[0]));
log.info("设备 {} 基于Redis状态重新订阅: {}", deviceSn, topicsToSubscribe);
} else {
log.info("设备 {} 在Redis中没有订阅者,跳过重新订阅", deviceSn);
}
} else {
// 没有订阅池服务,回退到默认行为(订阅所有基础主题)
log.warn("订阅池服务未设置,使用默认重新订阅策略");
subscribeDevice(deviceSn,
SubscriptionTopic.ONLINE,
SubscriptionTopic.OFFLINE,
SubscriptionTopic.EVENT_FIRE_ALARM // 只订阅机库数据,不订阅msg_alarm
);
}
});
}
@@ -0,0 +1,405 @@
package com.central.device.websocket.manager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* 订阅池服务 - 使用Redis管理客户端订阅
*
* 核心功能:
* 1. 每个客户端(sessionId)有独立的订阅记录
* 2. 多个客户端订阅同一设备时互不影响
* 3. 只有当所有客户端都取消订阅后,才真正取消WebSocket订阅
* 4. 支持分布式部署(多实例共享Redis)
*
* Redis数据结构:
* - device:sub:{deviceSn}:{topicType} -> Set<sessionId>
* 记录每个设备的每个主题类型被哪些session订阅
*
* - device:sub:session:{sessionId} -> Set<deviceSn:topicType>
* 记录每个session订阅了哪些设备的哪些主题(用于快速清理)
*
* @author dzc
* @date 2025-01-20
*/
@Slf4j
@Service
public class SubscriptionPoolService {
private static final String KEY_PREFIX = "device:sub:";
private static final String SESSION_KEY_PREFIX = "device:sub:session:";
// 订阅记录过期时间(24小时,防止僵尸数据)
private static final long EXPIRE_HOURS = 24;
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 主题类型枚举
*/
public enum TopicType {
FIRE_ALARM("fire_alarm"), // 机库状态数据
MSG_ALARM("msg_alarm"), // 无人机遥测数据
ONLINE("online"), // 设备上线
OFFLINE("offline"); // 设备下线
private final String value;
TopicType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
/**
* 添加订阅
*
* @param sessionId 客户端会话ID
* @param deviceSn 设备SN
* @param topicType 主题类型
* @return true 如果是该设备该主题的第一个订阅者(需要向WebSocket发送订阅),false 表示已有其他人订阅
*/
public boolean addSubscription(String sessionId, String deviceSn, TopicType topicType) {
String topicKey = buildTopicKey(deviceSn, topicType);
String sessionKey = buildSessionKey(sessionId);
String subscriptionValue = deviceSn + ":" + topicType.getValue();
try {
// 1. 添加到主题订阅集合
Long addResult = redisTemplate.opsForSet().add(topicKey, sessionId);
// 2. 添加到session的订阅记录(用于快速清理)
redisTemplate.opsForSet().add(sessionKey, subscriptionValue);
// 3. 设置过期时间(防止僵尸数据)
redisTemplate.expire(topicKey, EXPIRE_HOURS, TimeUnit.HOURS);
redisTemplate.expire(sessionKey, EXPIRE_HOURS, TimeUnit.HOURS);
// 4. 获取当前订阅数
Long count = redisTemplate.opsForSet().size(topicKey);
boolean isFirstSubscriber = addResult != null && addResult > 0 && count != null && count == 1;
log.info("添加订阅: sessionId={}, deviceSn={}, topicType={}, isFirst={}, totalCount={}",
sessionId, deviceSn, topicType.getValue(), isFirstSubscriber, count);
return isFirstSubscriber;
} catch (Exception e) {
log.error("添加订阅失败: sessionId={}, deviceSn={}, topicType={}, error={}",
sessionId, deviceSn, topicType.getValue(), e.getMessage());
return true; // 出错时保守处理,返回true确保订阅
}
}
/**
* 移除订阅
*
* @param sessionId 客户端会话ID
* @param deviceSn 设备SN
* @param topicType 主题类型
* @return true 如果是该设备该主题的最后一个订阅者(需要向WebSocket发送取消订阅),false 表示还有其他人订阅
*/
public boolean removeSubscription(String sessionId, String deviceSn, TopicType topicType) {
String topicKey = buildTopicKey(deviceSn, topicType);
String sessionKey = buildSessionKey(sessionId);
String subscriptionValue = deviceSn + ":" + topicType.getValue();
try {
// 1. 从主题订阅集合移除
Long removeResult = redisTemplate.opsForSet().remove(topicKey, sessionId);
// 2. 从session的订阅记录移除
redisTemplate.opsForSet().remove(sessionKey, subscriptionValue);
// 3. 获取剩余订阅数
Long remainingCount = redisTemplate.opsForSet().size(topicKey);
// 4. 如果没有订阅者了,删除key
boolean isLastSubscriber = remainingCount == null || remainingCount == 0;
if (isLastSubscriber) {
redisTemplate.delete(topicKey);
}
log.info("移除订阅: sessionId={}, deviceSn={}, topicType={}, isLast={}, remainingCount={}",
sessionId, deviceSn, topicType.getValue(), isLastSubscriber, remainingCount);
return isLastSubscriber;
} catch (Exception e) {
log.error("移除订阅失败: sessionId={}, deviceSn={}, topicType={}, error={}",
sessionId, deviceSn, topicType.getValue(), e.getMessage());
return true; // 出错时保守处理,返回true确保取消订阅
}
}
/**
* 移除session的所有订阅
* 用于客户端断开连接时快速清理
*
* @param sessionId 客户端会话ID
* @return 需要真正取消WebSocket订阅的设备和主题列表
*/
public java.util.List<DeviceTopicPair> removeAllSubscriptions(String sessionId) {
String sessionKey = buildSessionKey(sessionId);
java.util.List<DeviceTopicPair> toUnsubscribe = new java.util.ArrayList<>();
try {
// 1. 获取该session的所有订阅
Set<String> subscriptions = redisTemplate.opsForSet().members(sessionKey);
if (subscriptions == null || subscriptions.isEmpty()) {
log.debug("Session {} 没有订阅记录", sessionId);
return toUnsubscribe;
}
log.info("清理session订阅: sessionId={}, subscriptionCount={}", sessionId, subscriptions.size());
// 2. 逐个移除订阅
for (String subscription : subscriptions) {
String[] parts = subscription.split(":", 2);
if (parts.length != 2) {
continue;
}
String deviceSn = parts[0];
String topicTypeStr = parts[1];
TopicType topicType = parseTopicType(topicTypeStr);
if (topicType != null) {
boolean isLast = removeSubscription(sessionId, deviceSn, topicType);
if (isLast) {
toUnsubscribe.add(new DeviceTopicPair(deviceSn, topicType));
}
}
}
// 3. 删除session的订阅记录key
redisTemplate.delete(sessionKey);
log.info("Session {} 订阅清理完成,需要取消WebSocket订阅的数量: {}", sessionId, toUnsubscribe.size());
} catch (Exception e) {
log.error("清理session订阅失败: sessionId={}, error={}", sessionId, e.getMessage());
}
return toUnsubscribe;
}
/**
* 检查设备的某个主题是否有订阅者
*/
public boolean hasSubscribers(String deviceSn, TopicType topicType) {
String topicKey = buildTopicKey(deviceSn, topicType);
try {
Long count = redisTemplate.opsForSet().size(topicKey);
return count != null && count > 0;
} catch (Exception e) {
log.error("检查订阅者失败: deviceSn={}, topicType={}, error={}",
deviceSn, topicType.getValue(), e.getMessage());
return false;
}
}
/**
* 获取设备某个主题的订阅者数量
*/
public long getSubscriberCount(String deviceSn, TopicType topicType) {
String topicKey = buildTopicKey(deviceSn, topicType);
try {
Long count = redisTemplate.opsForSet().size(topicKey);
return count != null ? count : 0;
} catch (Exception e) {
log.error("获取订阅者数量失败: deviceSn={}, topicType={}, error={}",
deviceSn, topicType.getValue(), e.getMessage());
return 0;
}
}
/**
* 获取设备某个主题的所有订阅者
*/
public Set<String> getSubscribers(String deviceSn, TopicType topicType) {
String topicKey = buildTopicKey(deviceSn, topicType);
try {
return redisTemplate.opsForSet().members(topicKey);
} catch (Exception e) {
log.error("获取订阅者列表失败: deviceSn={}, topicType={}, error={}",
deviceSn, topicType.getValue(), e.getMessage());
return java.util.Collections.emptySet();
}
}
/**
* 获取session的所有订阅
*/
public Set<String> getSessionSubscriptions(String sessionId) {
String sessionKey = buildSessionKey(sessionId);
try {
return redisTemplate.opsForSet().members(sessionKey);
} catch (Exception e) {
log.error("获取session订阅失败: sessionId={}, error={}", sessionId, e.getMessage());
return java.util.Collections.emptySet();
}
}
/**
* 刷新订阅的过期时间(心跳时调用)
*/
public void refreshSubscription(String sessionId, String deviceSn, TopicType topicType) {
String topicKey = buildTopicKey(deviceSn, topicType);
String sessionKey = buildSessionKey(sessionId);
try {
redisTemplate.expire(topicKey, EXPIRE_HOURS, TimeUnit.HOURS);
redisTemplate.expire(sessionKey, EXPIRE_HOURS, TimeUnit.HOURS);
} catch (Exception e) {
log.debug("刷新订阅过期时间失败: sessionId={}, deviceSn={}", sessionId, deviceSn);
}
}
/**
* 打印当前订阅状态(调试用)
*/
public void printSubscriptionStatus() {
try {
Set<String> keys = redisTemplate.keys(KEY_PREFIX + "*");
if (keys == null || keys.isEmpty()) {
log.info("当前没有任何订阅");
return;
}
log.info("========== 订阅池状态 ==========");
for (String key : keys) {
if (key.startsWith(SESSION_KEY_PREFIX)) {
continue; // 跳过session key
}
Set<String> members = redisTemplate.opsForSet().members(key);
log.info(" {} -> {} 个订阅者: {}", key, members != null ? members.size() : 0, members);
}
log.info("================================");
} catch (Exception e) {
log.error("打印订阅状态失败: {}", e.getMessage());
}
}
/**
* 获取所有有订阅记录的sessionId
* 用于孤儿订阅清理
*/
public Set<String> getAllSessionIds() {
try {
Set<String> sessionKeys = redisTemplate.keys(SESSION_KEY_PREFIX + "*");
if (sessionKeys == null || sessionKeys.isEmpty()) {
return java.util.Collections.emptySet();
}
// 从key中提取sessionId
Set<String> sessionIds = new java.util.HashSet<>();
for (String key : sessionKeys) {
String sessionId = key.substring(SESSION_KEY_PREFIX.length());
sessionIds.add(sessionId);
}
return sessionIds;
} catch (Exception e) {
log.error("获取所有sessionId失败: {}", e.getMessage());
return java.util.Collections.emptySet();
}
}
/**
* 清理孤儿订阅
* 检查Redis中记录的session是否在活跃session列表中
* 如果不在,则清理该session的所有订阅
*
* @param activeSessionIds 当前活跃的sessionId集合
* @return 清理的孤儿session数量
*/
public int cleanupOrphanSessions(Set<String> activeSessionIds) {
int cleanedCount = 0;
try {
Set<String> allSessionIds = getAllSessionIds();
if (allSessionIds.isEmpty()) {
return 0;
}
for (String sessionId : allSessionIds) {
// 如果session不在活跃列表中,说明是孤儿订阅
if (!activeSessionIds.contains(sessionId)) {
log.info("发现孤儿订阅: sessionId={}, 开始清理", sessionId);
// 清理该session的所有订阅
java.util.List<DeviceTopicPair> toUnsubscribe = removeAllSubscriptions(sessionId);
log.info("孤儿订阅清理完成: sessionId={}, 需要取消WebSocket订阅的数量: {}",
sessionId, toUnsubscribe.size());
cleanedCount++;
}
}
if (cleanedCount > 0) {
log.info("孤儿订阅清理完成,共清理 {} 个孤儿session", cleanedCount);
}
} catch (Exception e) {
log.error("清理孤儿订阅失败: {}", e.getMessage());
}
return cleanedCount;
}
// ========== 私有方法 ==========
private String buildTopicKey(String deviceSn, TopicType topicType) {
return KEY_PREFIX + deviceSn + ":" + topicType.getValue();
}
private String buildSessionKey(String sessionId) {
return SESSION_KEY_PREFIX + sessionId;
}
private TopicType parseTopicType(String value) {
for (TopicType type : TopicType.values()) {
if (type.getValue().equals(value)) {
return type;
}
}
return null;
}
/**
* 设备-主题对,用于返回需要取消订阅的列表
*/
public static class DeviceTopicPair {
private final String deviceSn;
private final TopicType topicType;
public DeviceTopicPair(String deviceSn, TopicType topicType) {
this.deviceSn = deviceSn;
this.topicType = topicType;
}
public String getDeviceSn() {
return deviceSn;
}
public TopicType getTopicType() {
return topicType;
}
@Override
public String toString() {
return deviceSn + ":" + topicType.getValue();
}
}
}