From 75e6eea8cd3fac9cc888e2ffc9cdb126fab8429d Mon Sep 17 00:00:00 2001
From: rain <167982779@qq.com>
Date: Wed, 14 Aug 2024 15:45:55 +0800
Subject: [PATCH] 任务下发、更新、取消,优化图斑逻辑

---
 src/main/java/com/dji/sample/droneairport/service/impl/RegistServiceImpl.java |  256 +++++++++++++++++++++++++++++++++-----------------
 1 files changed, 169 insertions(+), 87 deletions(-)

diff --git a/src/main/java/com/dji/sample/droneairport/service/impl/RegistServiceImpl.java b/src/main/java/com/dji/sample/droneairport/service/impl/RegistServiceImpl.java
index 03f14e6..89d632e 100644
--- a/src/main/java/com/dji/sample/droneairport/service/impl/RegistServiceImpl.java
+++ b/src/main/java/com/dji/sample/droneairport/service/impl/RegistServiceImpl.java
@@ -10,7 +10,7 @@
 import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
 import com.dji.sample.common.model.ResponseResult;
 import com.dji.sample.component.redis.RedisOpsUtils;
-import com.dji.sample.droneairport.dao.DeviceExpanSionDao;
+import com.dji.sample.droneairport.dao.DeviceExpanSionMapper;
 import com.dji.sample.droneairport.model.Entity.DeviceExpanSionEntity;
 import com.dji.sample.droneairport.model.dto.*;
 import com.dji.sample.droneairport.model.param.ReturnTaskParam;
@@ -46,6 +46,7 @@
 import java.util.*;
 import java.util.stream.Collectors;
 
+import static com.dji.sample.droneairport.utils.TaskAllocator.assignTasks;
 import static com.dji.sample.patches.utils.TimerUtil.getCurrentTimestampPlus8Hours;
 
 @Service
@@ -55,7 +56,7 @@
     @Autowired
     private IDeviceRedisService redisService;
     @Autowired
-    private DeviceExpanSionDao expanSionDao;
+    private DeviceExpanSionMapper expanSionMapper;
     @Autowired
     private TaskInfoMapper taskInfoMapper;
     @Autowired
@@ -111,10 +112,10 @@
     @Override
     public String addDrone(String workspaceId) {
         try {
-            DeviceExpanSionEntity airport = expanSionDao.selectOne(new LambdaQueryWrapper<DeviceExpanSionEntity>()
+            DeviceExpanSionEntity airport = expanSionMapper.selectOne(new LambdaQueryWrapper<DeviceExpanSionEntity>()
                     .eq(DeviceExpanSionEntity::getWorkspaceId, workspaceId)
                     .eq(DeviceExpanSionEntity::getType, 0));
-            DeviceExpanSionEntity drone = expanSionDao.selectOne(new LambdaQueryWrapper<DeviceExpanSionEntity>()
+            DeviceExpanSionEntity drone = expanSionMapper.selectOne(new LambdaQueryWrapper<DeviceExpanSionEntity>()
                     .eq(DeviceExpanSionEntity::getWorkspaceId, workspaceId)
                     .eq(DeviceExpanSionEntity::getType, 1));
             AddDeviceDto dto = deviceEntityToDto(drone);
@@ -179,8 +180,6 @@
         AddTaskDto addTaskDto = jsonToDto(jsonObject);
         TaskInfo taskInfo = new TaskInfo();
         List<String> listx = convertStringToList(addTaskDto.getDeviceid());
-        String sn = listx.get(0);
-        String workspaceId = getWorkspaceId(sn);
         taskInfo.setId(traceid);
         taskInfo.setTaskId(taskId);
         taskInfo.setName(addTaskDto.getBizidname());
@@ -188,47 +187,54 @@
         taskInfo.setCreateUser(username);
         param.setTraceId(traceid);
         taskInfoMapper.insert(taskInfo);
+
+        // 转换 TaskListDto 为 LotInfo
+        List<LotInfo> lotInfos = new ArrayList<>();
         List<TaskListDto> tasklist = addTaskDto.getTasklist();
         for (TaskListDto taskListDto : tasklist) {
-            LotInfo lotInfo = new LotInfo();
-            lotInfo = convertToLotInfo(taskListDto);
+            LotInfo lotInfo = convertToLotInfo(taskListDto);
             lotInfo.setTaskId(taskId);
             lotInfo.setType(0);
             lotInfo.setTaskName(addTaskDto.getBizidname());
             lotInfo.setUserName(username);
-            lotInfo.setWorkspaceId(workspaceId);
+            lotInfos.add(lotInfo);
             patchesMapper.insert(lotInfo);
         }
-        Long time = getCurrentTimestampPlus8Hours(14);
 
-//        获取未规划的图斑集合
-        List<List<LotInfo>> lists = timerUtil.getNoPlan(workspaceId);
-        List<List<LotInfo>> convertedLists = TimerUtil.convertToLists(lists);
-        for (List<LotInfo> list : convertedLists) {
-            String waylineName = TimerUtil.getTimeName();
-            //根据获取的图斑集合获得kmz航线文件
-            MultipartFile multipartFile = null;
-            try {
-                multipartFile = timerUtil.getFile(waylineName, list, 28.62452712442823, 115.85666327144976);
-            } catch (IOException e) {
-                throw new RuntimeException(e);
+        // 获取机场信息
+        List<Airport> airports = getAirportsBySn(listx);
+        List<AirportTasks> airportTasks = assignTasks(airports, lotInfos);
+
+        // 处理并插入图斑到数据库
+        processAndInsertTasks(airportTasks);
+
+        // 根据机场位置生成航线任务
+        for (AirportTasks airportTask : airportTasks) {
+            Airport airport = airportTask.getAirport();
+            List<LotInfo> lotInfosForAirport = airportTask.getTasks();
+
+            if (!lotInfosForAirport.isEmpty()) {
+                String waylineName = TimerUtil.getTimeName();
+                MultipartFile multipartFile = timerUtil.getFile(waylineName, lotInfosForAirport, airport.getLat(), airport.getLon());
+                WaylineFileEntity waylineFile = timerUtil.backWayline(multipartFile, waylineName, airport.getWorkspaceId(), username);
+                Long time = getCurrentTimestampPlus8Hours(14);
+                List<List<Long>> listOfLists = new ArrayList<>();
+                List<Long> sublist = new ArrayList<>();
+                sublist.add(time);
+                listOfLists.add(sublist);
+                List<Long> lists1 = new ArrayList<>();
+                lists1.add(time);
+                String times = TimerUtil.convertTimestampToFormattedString(time);
+                param.setWaylineId(taskId);
+                timerUtil.sendPostWithParameters(waylineName, waylineFile.getWaylineId(), times, lists1, listOfLists, taskId+"~"+airport.getWorkspaceId(),airport.getDockSn());
+                timerUtil.updatePatchesStatu(lotInfosForAirport);
             }
-            //上传航线文件
-            WaylineFileEntity waylineFile = timerUtil.backWayline(multipartFile, waylineName, workspaceId, username);
-            //将为规划的图斑状态更新为已规划
-            List<List<Long>> listOfLists = new ArrayList<>();
-            List<Long> sublist = new ArrayList<>();
-            sublist.add(time); // 添加整数值
-            listOfLists.add(sublist);
-            List<Long> lists1 = new ArrayList<>();
-            lists1.add(time);
-            String times = TimerUtil.convertTimestampToFormattedString(time);
-            param.setWaylineId(taskId);
-            TimerUtil.sendPostWithParameters(waylineName, waylineFile.getWaylineId(), times, lists1, listOfLists, taskId);
-            timerUtil.updatePatchesStatu(list);
         }
+
         return param;
     }
+
+
 
     @Override
     public ReturnTaskParam updateTask(String base64, String Secret, String username) throws Exception {
@@ -239,57 +245,88 @@
         JSONObject jsonObject = new JSONObject(decryptedJson);
         UpdataTaskDto addTaskDto = UpjsonToDto(jsonObject);
         String taskId = addTaskDto.getTaskid();
+        String Bizidname=getBizidnameByTask(taskId);
         delPatchesByTaskId(taskId);
-//        delWaylineJob(taskId);
+        delTaskInfo(taskId);
+        delWaylineJob(taskId);
         TaskInfo taskInfo = new TaskInfo();
         List<String> listx = convertStringToList(addTaskDto.getDeviceid());
-        String sn = listx.get(0);
-        String workspaceId = getWorkspaceId(sn);
         taskInfo.setId(traceid);
         taskInfo.setTaskId(taskId);
+        taskInfo.setName(Bizidname);
         taskInfo.setDeviceIds(addTaskDto.getDeviceid());
         taskInfo.setCreateUser(username);
         param.setTraceId(traceid);
-        updateTaskInfo(traceid, taskId, addTaskDto.getDeviceid(), username);
+        taskInfoMapper.insert(taskInfo);
+
+        // 转换 TaskListDto 为 LotInfo
+        List<LotInfo> lotInfos = new ArrayList<>();
         List<TaskListDto> tasklist = addTaskDto.getTasklist();
         for (TaskListDto taskListDto : tasklist) {
-            LotInfo lotInfo = new LotInfo();
-            lotInfo = convertToLotInfo(taskListDto);
-            lotInfo.setUserName(username);
+            LotInfo lotInfo = convertToLotInfo(taskListDto);
             lotInfo.setTaskId(taskId);
-            lotInfo.setWorkspaceId(workspaceId);
+            lotInfo.setType(0);
+            lotInfo.setTaskName(Bizidname);
+            lotInfo.setUserName(username);
+            lotInfos.add(lotInfo);
             patchesMapper.insert(lotInfo);
         }
-        Long time = getCurrentTimestampPlus8Hours(14);
 
-//        获取未规划的图斑集合
-        List<List<LotInfo>> lists = timerUtil.getNoPlan(workspaceId);
-        List<List<LotInfo>> convertedLists = TimerUtil.convertToLists(lists);
-        for (List<LotInfo> list : convertedLists) {
-            String waylineName = TimerUtil.getTimeName();
-            //根据获取的图斑集合获得kmz航线文件
-            MultipartFile multipartFile = null;
-            try {
-                multipartFile = timerUtil.getFile(waylineName, list, 28.62452712442823, 115.85666327144976);
-            } catch (IOException e) {
-                throw new RuntimeException(e);
+        // 获取机场信息
+        List<Airport> airports = getAirportsBySn(listx);
+        List<AirportTasks> airportTasks = assignTasks(airports, lotInfos);
+
+        // 处理并插入图斑到数据库
+        processAndInsertTasks(airportTasks);
+
+        // 根据机场位置生成航线任务
+        for (AirportTasks airportTask : airportTasks) {
+            Airport airport = airportTask.getAirport();
+            List<LotInfo> lotInfosForAirport = airportTask.getTasks();
+
+            if (!lotInfosForAirport.isEmpty()) {
+                String waylineName = TimerUtil.getTimeName();
+                MultipartFile multipartFile = timerUtil.getFile(waylineName, lotInfosForAirport, airport.getLat(), airport.getLon());
+                WaylineFileEntity waylineFile = timerUtil.backWayline(multipartFile, waylineName, airport.getWorkspaceId(), username);
+
+                // 将为规划的图斑状态更新为已规划
+                Long time = getCurrentTimestampPlus8Hours(14);
+                List<List<Long>> listOfLists = new ArrayList<>();
+                List<Long> sublist = new ArrayList<>();
+                sublist.add(time);
+                listOfLists.add(sublist);
+                List<Long> lists1 = new ArrayList<>();
+                lists1.add(time);
+                String times = TimerUtil.convertTimestampToFormattedString(time);
+                param.setWaylineId(taskId);
+                timerUtil.sendPostWithParameters(waylineName, waylineFile.getWaylineId(), times, lists1, listOfLists, airport.getWorkspaceId()+"~"+taskId,airport.getDockSn());
+                timerUtil.updatePatchesStatu(lotInfosForAirport);
             }
-            //上传航线文件
-            WaylineFileEntity waylineFile = timerUtil.backWayline(multipartFile, waylineName, workspaceId, username);
-            updateJob(taskId, waylineFile.getWaylineId());
-            param.setWaylineId(taskId);
-            timerUtil.updatePatchesStatu(list);
         }
+
         return param;
     }
 
     @Override
     public ResponseResult cancelTask(String taskId) {
         LambdaUpdateWrapper<WaylineJobEntity> updateWrapper = new LambdaUpdateWrapper<>();
-        updateWrapper.eq(WaylineJobEntity::getJobId, taskId)
+        updateWrapper.like(WaylineJobEntity::getJobId, taskId)
                 .set(WaylineJobEntity::getStatus, 4);
         waylineJobMapper.update(null, updateWrapper);
         return null;
+    }
+
+    public  void processAndInsertTasks(List<AirportTasks> airportTasks) {
+        for (AirportTasks airportTasksEntry : airportTasks) {
+            Airport airport = airportTasksEntry.getAirport();
+            List<LotInfo> tasks = airportTasksEntry.getTasks();
+
+            // 处理每个任务
+            for (LotInfo lotInfo : tasks) {
+                lotInfo.setWorkspaceId(airport.getWorkspaceId()); // 设置 workspaceId
+                patchesMapper.updateById(lotInfo);
+            }
+        }
     }
 
     @Override
@@ -314,6 +351,7 @@
         }
         return null;
     }
+
     private static final String BASE_DIR = "src/main/resources/tmp";
 
     /**
@@ -322,7 +360,7 @@
      * @param taskId 任务 ID
      * @return 匹配的 DB 文件路径列表
      */
-    public  List<String> findDbFilesByTaskId(String taskId) {
+    public List<String> findDbFilesByTaskId(String taskId) {
         List<String> dbFilePaths = new ArrayList<>();
         File baseDir = new File(BASE_DIR);
 
@@ -354,6 +392,9 @@
         patchesMapper.delete(new LambdaUpdateWrapper<LotInfo>().eq(LotInfo::getTaskId, taskId));
     }
 
+    public void delTaskInfo(String taskId){
+        taskInfoMapper.delete(new LambdaUpdateWrapper<TaskInfo>().eq(TaskInfo::getTaskId, taskId));
+    }
     private String buildRequestBody(AddDeviceDto dto) {
         try {
             return objectMapper.writeValueAsString(dto);
@@ -368,6 +409,10 @@
         return entity.getWorkspaceId();
     }
 
+    public String getBizidnameByTask(String taskId){
+       TaskInfo taskInfo= taskInfoMapper.selectOne(new LambdaQueryWrapper<TaskInfo>().eq(TaskInfo::getTaskId, taskId));
+        return taskInfo.getName();
+    }
     public static String enSM2(String data, String pubKey) throws InvalidCipherTextException, IOException {
         String encrypt = Utils.encrypt(data, pubKey);
         encrypt = Utils.hexToBase64(encrypt);
@@ -378,6 +423,8 @@
         String hex = Utils.convertBase64ToHex(Base64);
         return Utils.decrypt(hex, priKey);
     }
+
+
 
 
     public static Map<String, String> createKey() throws NoSuchAlgorithmException {
@@ -397,7 +444,7 @@
                     .latitude(entity.getLatitude())
                     .radius(entity.getRadius())
                     .regioncode(entity.getRegioncode())
-                    .deviceid(entity.getDeviceId())
+                    .deviceid(entity.getDeviceSn())
                     .model(entity.getModel())
                     .build();
         }
@@ -416,30 +463,45 @@
         return builder.build();
     }
 
-    public OsdSubDeviceReceiver getDroneFromCache(String sn) {
+    public String getDroneFromCache(String sn) {
         String key = "osd:" + sn;
-        return (OsdSubDeviceReceiver) RedisOpsUtils.get(key);
+        return  RedisOpsUtils.get(key).toString();
     }
-
-
+    public void delWaylineJob(String taskId) {
+        waylineJobMapper.delete(new LambdaQueryWrapper<WaylineJobEntity>().like(WaylineJobEntity::getJobId, taskId));
+    }
     public DroneStateDto getAirportFromCache(String deviceId) {
-        OsdSubDeviceReceiver receiver = getDroneFromCache(deviceId);
-
-        if (receiver == null) {
-            throw new IllegalArgumentException("Receiver data not found for device ID: " + deviceId);
+        String  receiver = getDroneFromCache(deviceId);
+        double gimbalYaw =0.0;
+        double gimbalPitch=0.0;
+        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(receiver);
+        double latitude = jsonObject.getDoubleValue("latitude");
+        double longitude = jsonObject.getDoubleValue("longitude");
+        int modeCode = jsonObject.getInteger("mode_code");
+        double elevation = jsonObject.getDoubleValue("elevation");
+        double height = jsonObject.getDoubleValue("height");
+        com.alibaba.fastjson.JSONArray payloads = jsonObject.getJSONArray("payloads");
+        if (payloads != null && payloads.size() > 1) {
+            com.alibaba.fastjson.JSONArray payloadArray = payloads.getJSONArray(1);
+            for (int i = 0; i < payloadArray.size(); i++) {
+                com.alibaba.fastjson.JSONObject payload = payloadArray.getJSONObject(i);
+                 gimbalYaw = payload.getDoubleValue("gimbal_yaw");
+                 gimbalPitch = payload.getDoubleValue("gimbal_pitch");
+            }
         }
-
+        com.alibaba.fastjson.JSONObject battery = jsonObject.getJSONObject("battery");
+        int batteryCapacityPercent = battery.getInteger("capacity_percent");
         DroneStateDto.DroneStateDtoBuilder builder = DroneStateDto.builder();
 
-        builder.gimbalYal(receiver.getAttitudeHead() != null ? receiver.getAttitudeHead() : 0.0)
-                .gimbalPitch(receiver.getAttitudePitch() != null ? receiver.getAttitudePitch() : 0.0)
-                .batteryCapacityPercent(receiver.getBattery() != null ? receiver.getBattery().getCapacityPercent() : 0)
-                .height(receiver.getHeight() != null ? receiver.getHeight() : 0.0)
-                .latitude(receiver.getLatitude() != null ? receiver.getLatitude() : 0.0)
-                .longitude(receiver.getLongitude() != null ? receiver.getLongitude() : 0.0)
-                .modeCode(receiver.getModeCode() != null ? receiver.getModeCode().getVal() : 0)
-                .elevation(receiver.getElevation() != null ? receiver.getElevation() : 0.0)
-                .gpsState(2);
+        builder.gimbalYal(gimbalYaw)
+                .gimbalPitch(gimbalPitch)
+                .batteryCapacityPercent(batteryCapacityPercent)
+                .height(height)
+                .latitude(latitude)
+                .longitude(longitude)
+                .modeCode(modeCode)
+                .elevation(elevation)
+                .gpsState(3);
 
         return builder.build();
     }
@@ -523,6 +585,32 @@
     }
 
 
+    public List<Airport> getAirportsBySn(List<String> snList) {
+        List<Airport> airports = new ArrayList<>();
+        // 查询所有设备
+        List<DeviceExpanSionEntity> entities = expanSionMapper.selectList(
+                new LambdaQueryWrapper<DeviceExpanSionEntity>().in(DeviceExpanSionEntity::getDeviceSn, snList)
+        );
+
+        // 使用一个Map来存储SN和经纬度的对应关系
+        Map<String, DeviceExpanSionEntity> entityMap = new HashMap<>();
+        for (DeviceExpanSionEntity entity : entities) {
+            entityMap.put(entity.getDeviceSn(), entity);
+        }
+
+        // 遍历SN列表,创建Airport对象
+        for (String sn : snList) {
+            DeviceExpanSionEntity entity = entityMap.get(sn);
+            if (entity != null) {
+                DeviceEntity deviceEntity = deviceMapper.selectOne(new LambdaQueryWrapper<DeviceEntity>().eq(DeviceEntity::getChildSn,sn));
+                Airport airport = new Airport(entity.getWorkspaceId(),deviceEntity.getDeviceSn(),entity.getLatitude(), entity.getLongitude());
+                airports.add(airport);
+            }
+        }
+
+        return airports;
+    }
+
     public static List<String> convertStringToList(String input) {
         // 使用 Hutool 解析字符串
         JSONArray jsonArray = JSONUtil.parseArray(input);
@@ -547,11 +635,6 @@
         // 执行更新操作
         taskInfoMapper.update(taskInfo, updateWrapper);
     }
-
-    public void delWaylineFile(String waylineId) {
-        fileMapper.delete(new LambdaUpdateWrapper<WaylineFileEntity>().eq(WaylineFileEntity::getWaylineId, waylineId));
-    }
-
     public void updateJob(String jobid, String waylineId) {
         LambdaUpdateWrapper<WaylineJobEntity> updateWrapper = new LambdaUpdateWrapper<>();
         updateWrapper.eq(WaylineJobEntity::getJobId, jobid)
@@ -560,5 +643,4 @@
         // 调用 update 方法进行更新操作
         waylineJobMapper.update(null, updateWrapper);
     }
-
-}
\ No newline at end of file
+}

--
Gitblit v1.9.3