guoshilong
2023-11-15 923a5e9fdfcfcc765606bce6fa7f99cb3717dcbe
src/main/java/com/dji/sample/wayline/service/impl/WaylineJobServiceImpl.java
@@ -1,10 +1,10 @@
package com.dji.sample.wayline.service.impl;
import com.alibaba.druid.stat.TableStat;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dji.sample.common.error.CommonErrorEnum;
@@ -22,6 +22,7 @@
import com.dji.sample.control.model.param.TakeoffToPointParam;
import com.dji.sample.control.service.IControlService;
import com.dji.sample.control.service.IDrcService;
import com.dji.sample.geo.entity.GeoJson;
import com.dji.sample.manage.model.dto.DeviceDTO;
import com.dji.sample.manage.model.enums.DeviceModeCodeEnum;
import com.dji.sample.manage.model.enums.DockModeCodeEnum;
@@ -34,7 +35,7 @@
import com.dji.sample.media.model.MediaFileCountDTO;
import com.dji.sample.media.model.MediaMethodEnum;
import com.dji.sample.media.service.IFileService;
import com.dji.sample.utils.GeoUtils;
import com.dji.sample.geo.utils.GeoUtils;
import com.dji.sample.wayline.dao.IWaylineJobMapper;
import com.dji.sample.wayline.model.dto.*;
import com.dji.sample.wayline.model.entity.WaylineJobEntity;
@@ -56,6 +57,7 @@
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.io.File;
import java.net.URL;
import java.sql.SQLException;
import java.time.*;
@@ -283,108 +285,6 @@
            return response;
        }
        //新增多条数据
        //开始日期
//        String parentId = "";
//        for (int i = 0; i < param.getExecuteStartTimeArr().size(); i++) {
//            List<Long> timeArr = param.getExecuteStartTimeArr().get(i);
//
//            long beginTimeLong = 0L;
//            long endTimeLong = 0L;
//            LocalDateTime beginTime = null;
//            if (i == 0) {
//                //父,开始-结束为整个区间
//                //开始日期
//                LocalDate startDate = LocalDate.ofInstant(Instant.ofEpochSecond(param.getTaskDays().get(0)), ZoneId.systemDefault());
//                beginTimeLong = LocalDateTime.of(startDate, LocalTime.ofInstant(Instant.ofEpochSecond(param.getExecuteStartTimeArr().get(0).get(0)), ZoneId.systemDefault()))
//                        .atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
//
//                //结束日期
//                LocalDate endDate = LocalDate.ofInstant(Instant.ofEpochSecond(param.getTaskDays().get(1)), ZoneId.systemDefault());
//                endTimeLong = LocalDateTime.of(endDate, LocalTime.ofInstant(Instant.ofEpochSecond(param.getExecuteStartTimeArr().get(param.getExecuteStartTimeArr().size() - 1).get(0)), ZoneId.systemDefault()))
//                        .atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
//            } else {
//                //子,开始-结束为当前区间
//                //开始日期
//                LocalDate date = LocalDate.ofInstant(Instant.ofEpochSecond(timeArr.get(0)), ZoneId.systemDefault());
//                //任务执行开始时间
//                beginTime = LocalDateTime.of(date, LocalTime.ofInstant(Instant.ofEpochSecond(timeArr.get(0)), ZoneId.systemDefault()));
//                //任务结束时间
//                LocalDateTime endTime = timeArr.size() > 1 && Objects.nonNull(timeArr.get(1)) ?
//                        LocalDateTime.of(date, LocalTime.ofInstant(Instant.ofEpochSecond(timeArr.get(1)), ZoneId.systemDefault())) : beginTime;
//
//                beginTimeLong = beginTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
//                endTimeLong = endTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
//            }
//
//
//            //保存数据
//            WaylineJobEntity waylineJobEntity = WaylineJobEntity.builder()
//                    .parentId(parentId.equals("") ? null : parentId)
//                    .jobId(UUID.randomUUID().toString())
//                    .name(param.getName())
//                    .dockSn(param.getDockSn())
//                    .fileId(param.getFileId())
//                    .username(customClaim.getUsername())
//                    .workspaceId(customClaim.getWorkspaceId())
//
//                    .beginTime(beginTimeLong)
//                    .endTime(endTimeLong)
//                    .status(WaylineJobStatusEnum.PENDING.getVal())
//                    .taskType(param.getTaskType().getVal())
//                    .waylineType(param.getWaylineType().getVal())
//                    .outOfControlAction(param.getOutOfControlAction())
//                    .batteryCapacity(param.getMinBatteryCapacity())
//                    .rthAltitude(param.getRthAltitude())
//                    .mediaCount(0)
//                    .repFreVal(param.getRepFreVal())
//                    .repFreType(param.getRepFreType())
//                    .repRuleType(param.getRepRuleType())
//                    .repRuleVal(param.getRepRuleVal())
//                    .executeTimeArr(param.getTaskPeriods())
//                    .executeStartTimeArr(param.getExecuteStartTimeArr())
//                    .build();
//
//            Optional<WaylineJobDTO> waylineJobOpt = insertWaylineJob(waylineJobEntity);
//
//            if (waylineJobOpt.isEmpty()) {
//                throw new SQLException("任务创建失败");
//            }
//
//
//            if (i == 0) {
//                //把第一个当作父
//                parentId = waylineJobEntity.getId().toString();
//            }
//            WaylineJobDTO waylineJob = waylineJobOpt.get();
//
//            //条件任务
//            if (param.getTaskType() == WaylineTaskTypeEnum.CONDITION) {
//                //如果是条件任务类型,需要在任务参数中添加条件。
//                waylineJob.setConditions(
//                        WaylineTaskConditionDTO.builder()
//                                .executableConditions(Objects.nonNull(param.getMinStorageCapacity()) ? WaylineTaskExecutableConditionDTO.builder().storageCapacity(param.getMinStorageCapacity()).build() : null)
//                                .readyConditions(WaylineTaskReadyConditionDTO.builder()
//                                        .batteryCapacity(param.getMinBatteryCapacity())
//                                        .beginTime(beginTimeLong)
//                                        .endTime(endTimeLong)
//                                        .build())
//                                .build());
//            } else {
//                waylineJob.setBeginTime(beginTime);
//            }
//
//            if (waylineJobOpt.isEmpty()) {
//                throw new SQLException("任务创建失败");
//            }
//
//            ResponseResult response = this.publishOneFlightTask(waylineJob);
//            if (ResponseResult.CODE_SUCCESS != response.getCode()) {
//                return response;
//            }
//        }
        return ResponseResult.success();
    }
@@ -592,13 +492,13 @@
    }
    @Override
    public Boolean updateJob(WaylineJobDTO dto){
    public Boolean updateJob(WaylineJobDTO dto) {
        try {
            if (dto.getStatus() == 3){
            if (dto.getStatus() == 3) {
                this.checkNextJob(dto);
            }
        }catch (SQLException e) {
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
@@ -610,19 +510,7 @@
    @Override
    public PaginationData<WaylineJobDTO> getJobsByWorkspaceId(String workspaceId, long page, long pageSize, WaylineJobQueryParam waylineJobQueryParam) {
//        Page<WaylineJobEntity> pageData = mapper.selectPage(
//                new Page<WaylineJobEntity>(page, pageSize),
//                new LambdaQueryWrapper<WaylineJobEntity>()
//                        .eq(WaylineJobEntity::getWorkspaceId, workspaceId)
//                        .eq(waylineJobDTO.getTaskType() !=null, WaylineJobEntity::getTaskType, waylineJobDTO.getTaskType())
//                        .eq(waylineJobDTO.getStatus()!=null, WaylineJobEntity::getStatus, waylineJobDTO.getStatus())
//                        .like(StringUtils.hasText(waylineJobDTO.getJobName()),WaylineJobEntity::getName,waylineJobDTO.getJobName())
//
//
//                        .orderByDesc(WaylineJobEntity::getId));
        Page<WaylineJobEntity> pageData = mapper.getPage(new Page<WaylineJobEntity>(page, pageSize), waylineJobQueryParam, workspaceId);
        List<WaylineJobDTO> records = pageData.getRecords()
                .stream()
@@ -630,6 +518,18 @@
                .collect(Collectors.toList());
        return new PaginationData<WaylineJobDTO>(records, new Pagination(pageData));
    }
    @Override
    public List<WaylineJobDTO> getChildrenJobs(String workspaceId, WaylineJobQueryParam waylineJobQueryParam) {
        List<WaylineJobEntity> list = mapper.getJobs(workspaceId, waylineJobQueryParam);
        List<WaylineJobDTO> records = list
                .stream()
                .map(this::entity2Dto)
                .collect(Collectors.toList());
        return records;
    }
@@ -796,54 +696,70 @@
    @Override
    public WaylineJobEntity getLatestJob(String workspaceId, WaylineJobQueryParam waylineJobQueryParam) {
//        List<WaylineJobEntity> waylineJobEntities = mapper.selectList(new LambdaQueryWrapper<>(WaylineJobEntity.class)
//                .eq(WaylineJobEntity::getWorkspaceId, workspaceId)
//                .eq(WaylineJobEntity::getDockSn, waylineJobQueryParam.getDockSn())
//                //获取状态为待执行
//                        .eq(WaylineJobEntity::getStatus,1)
//                .orderByDesc(WaylineJobEntity::getBeginTime)
//        );
        WaylineJobEntity waylineJobEntity = mapper.getLatest(workspaceId, waylineJobQueryParam);
        return waylineJobEntity;
    }
    @Override
    public ResponseResult flyByArea(String sn, FlyAreaParam flyAreaParam) {
    public ResponseResult flyByArea(String sn, FlyAreaParam flyAreaParam, String deviceSn) {
        List<List<PointPOJO>> areaList = flyAreaParam.getAreaList();
        //获取所有中心点
//        List<PointPOJO> targetList = GeoUtils.caculatePointList(flyAreaParam);
        PointPOJO dockPoint = flyAreaParam.getDockPoint();
        Double radius = flyAreaParam.getRadius();
        GeoJson geoJson = GeoUtils.readJsonFile(flyAreaParam.getJsonPath());
        List<PointPOJO> targetList = GeoUtils.caculatePointList(geoJson, dockPoint, flyAreaParam.getRadius());
        List<PointPOJO> centerPointList = new ArrayList<>();
        //一键起飞
        TakeoffToPointParam takeoffToPointParam = buildTakeoffToPointParam(dockPoint);
        //根据区域获取中心点
        areaList.forEach(area -> {
            PointPOJO centerPoint = GeoUtils.getCenterPoint(area);
            centerPointList.add(centerPoint);
        });
        ResponseResult takeoffToPointRes = controlService.takeoffToPoint(sn, takeoffToPointParam);
        //巡逻目标集合
        List<PointPOJO> targetList = new ArrayList<>();
        //获取所有中心点之后,
        centerPointList.forEach(centerPoint -> {
            //判断各个中心点和机场点的距离
            double distance = GeoUtils.distance(dockPoint.getLon(), dockPoint.getLat(), centerPoint.getLon(), centerPoint.getLat());
        //设置飞向第一个点
        while (takeoffToPointRes.getCode() == ResponseResult.CODE_SUCCESS) {
            //获取无人机状态
            DeviceModeCodeEnum deviceMode = deviceService.getDeviceMode(deviceSn);
            //当距离小于半径时,添加到目标集合中
            if (distance <= radius) {
                centerPoint.setDistance(distance);
                targetList.add(centerPoint);
            //当无人机状态为手动飞行
            if (deviceMode == DeviceModeCodeEnum.MANUAL) {
                //飞向目标点
                FlyToPointParam flyToPointParam = new FlyToPointParam();
                flyToPointParam.setMaxSpeed(14);
                List<PointDTO> pointDTOS = new ArrayList<>();
                PointDTO pointDTO = new PointDTO();
                pointDTO.setHeight(150.0);
                pointDTO.setLongitude(targetList.get(0).getLon());
                pointDTO.setLatitude(targetList.get(0).getLat());
                pointDTOS.add(pointDTO);
                flyToPointParam.setPoints(pointDTOS);
                ResponseResult flyToRes = controlService.flyToPoint(sn, flyToPointParam);
                if (flyToRes.getCode() == ResponseResult.CODE_SUCCESS) {
                    //第一个点指令飞行成功后,把数组存到redis中
                    /**
                     * {
                     *      targetList:[],
                     *      curIndex:
                     * }
                     */
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("targetList",targetList);
                    jsonObject.put("curIndex",0);
                    RedisOpsUtils.set("tuban:"+sn,jsonObject);
                }
                break;
            }
        });
        }
        //按距离从近到远排序
        targetList.sort(Comparator.comparing(PointPOJO::getDistance));
        return ResponseResult.success();
    }
        //后续为无人机操作逻辑
        //先飞到空中
    public TakeoffToPointParam buildTakeoffToPointParam(PointPOJO dockPoint) {
        TakeoffToPointParam takeoffToPointParam = new TakeoffToPointParam();
        takeoffToPointParam.setTargetLatitude(dockPoint.getLat());
@@ -860,47 +776,21 @@
        takeoffToPointParam.setMaxSpeed(10.0);
        takeoffToPointParam.setExitWaylineWhenRcLost(WaylineRcLostActionEnum.EXECUTE_RC_LOST_ACTION);
        //起飞
        ResponseResult responseResult = controlService.takeoffToPoint(sn, takeoffToPointParam);
        if (responseResult.getCode() != ResponseResult.CODE_SUCCESS) {
            return responseResult;
        }
        //向目标点飞行
        FlyToPointParam flyToPointParam = new FlyToPointParam();
        flyToPointParam.setMaxSpeed(14);
        List<PointDTO> pointDTOS = new ArrayList<>();
        targetList.forEach(pointPOJO -> {
            PointDTO pointDTO = new PointDTO();
            pointDTO.setHeight(150.0);
            pointDTO.setLongitude(pointPOJO.getLon());
            pointDTO.setLatitude(pointPOJO.getLat());
            pointDTOS.add(pointDTO);
        });
        flyToPointParam.setPoints(pointDTOS);
        ResponseResult responseResult1 = controlService.flyToPoint(sn, flyToPointParam);
        if (responseResult1.getCode() != ResponseResult.CODE_SUCCESS) {
            return responseResult1;
        }
        //返航
        //return_home
        return ResponseResult.success();
        return takeoffToPointParam;
    }
    @Override
    public ResponseResult checkNextJob(WaylineJobDTO job)  throws SQLException  {
    public ResponseResult checkNextJob(WaylineJobDTO job) throws SQLException {
        WaylineJobEntity params = new WaylineJobEntity();
        params.setJobId(job.getJobId());
        WaylineJobEntity currentJob = mapper.selectOne(Wrappers.query(params));
        WaylineJobEntity job1 = mapper.selectOne(Wrappers.query(params));
        WaylineJobEntity currentJob = JSON.parseObject(JSON.toJSONString(job1), WaylineJobEntity.class);
        if (currentJob == null) {
            return ResponseResult.error("该任务不存在");
        }
@@ -915,7 +805,7 @@
        long currentTime = System.currentTimeMillis();
        for (int i = 0; i < executeStartTimeArr.size(); i++) {
            Long startTime = Long.valueOf(executeStartTimeArr.get(i).get(0));
            Long startTime = executeStartTimeArr.get(i).get(0) * 1000;
            //如果当前时间小于开始时间
            if (currentTime < startTime) {
                //当前索引就是下一次要执行的时间
@@ -923,6 +813,11 @@
                break;
            }
        }
        if (indexTime == -1) {
            return ResponseResult.success();
        }
        List<Long> timeArr = currentJob.getExecuteStartTimeArr().get(indexTime);
        LocalDate date = LocalDate.ofInstant(Instant.ofEpochSecond(timeArr.get(0)), ZoneId.systemDefault());
@@ -1005,10 +900,10 @@
    @Override
    public WaylineJobCountDTO patrolStatistics(String workspaceId,String queryTime) {
    public WaylineJobCountDTO patrolStatistics(String workspaceId, String queryTime) {
        WaylineJobCountDTO waylineJobCountDTO = new WaylineJobCountDTO();
        List<WaylineJobEntity> list = mapper.patrolStatistics(workspaceId,queryTime);
        if (!CollectionUtils.isEmpty(list)){
        List<WaylineJobEntity> list = mapper.patrolStatistics(workspaceId, queryTime);
        if (!CollectionUtils.isEmpty(list)) {
            waylineJobCountDTO.setTotalNumber(list.size());
            long totalTime = list.stream().mapToLong(s -> s.getEndTime() - s.getBeginTime()).sum() / 1000;
            StringBuffer buffer = new StringBuffer();
@@ -1024,9 +919,9 @@
    @Override
    public void updateJobCollect(WaylineJobEntity waylineJob) {
        new LambdaUpdateChainWrapper<>(mapper)
                .eq(WaylineJobEntity::getJobId,waylineJob.getJobId())
                .set(WaylineJobEntity::getCollectStatus,waylineJob.getCollectStatus())
                .set(WaylineJobEntity::getUserId,waylineJob.getUserId())
                .eq(WaylineJobEntity::getJobId, waylineJob.getJobId())
                .set(WaylineJobEntity::getCollectStatus, waylineJob.getCollectStatus())
                .set(WaylineJobEntity::getUserId, waylineJob.getUserId())
                .update();
    }
@@ -1098,7 +993,8 @@
                .waylineType(WaylineTemplateTypeEnum.find(entity.getWaylineType()))
                .rthAltitude(entity.getRthAltitude())
                .outOfControlAction(entity.getOutOfControlAction())
                .mediaCount(entity.getMediaCount());
                .mediaCount(entity.getMediaCount())
                .hasChildren(entity.getHasChildren());
        if (Objects.nonNull(entity.getEndTime())) {
            builder.endTime(LocalDateTime.ofInstant(Instant.ofEpochMilli(entity.getEndTime()), ZoneId.systemDefault()));