From 2927bb498574a0e30bcbb3a9f7ee9468636cf0d8 Mon Sep 17 00:00:00 2001
From: rain <167982779@qq.com>
Date: Thu, 15 Aug 2024 11:31:33 +0800
Subject: [PATCH] 优化无人机状态更新,更新照片角度附属信息

---
 src/main/java/com/dji/sample/droneairport/service/impl/RegistServiceImpl.java |  296 ++++++++++++++++++++++++++++++++++++++++------------------
 1 files changed, 202 insertions(+), 94 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..feb0af2 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;
@@ -20,6 +20,9 @@
 import com.dji.sample.droneairport.utils.SM4Util;
 import com.dji.sample.manage.dao.IDeviceMapper;
 import com.dji.sample.manage.model.entity.DeviceEntity;
+import com.dji.sample.manage.model.enums.DeviceModeCodeEnum;
+import com.dji.sample.manage.model.enums.DockModeCodeEnum;
+import com.dji.sample.manage.model.receiver.OsdDockReceiver;
 import com.dji.sample.manage.model.receiver.OsdSubDeviceReceiver;
 import com.dji.sample.manage.service.IDeviceRedisService;
 import com.dji.sample.patches.dao.GetPatchesMapper;
@@ -31,6 +34,7 @@
 import com.dji.sample.wayline.dao.IWaylineJobMapper;
 import com.dji.sample.wayline.model.entity.WaylineFileEntity;
 import com.dji.sample.wayline.model.entity.WaylineJobEntity;
+import com.dji.sample.wayline.model.enums.WaylineJobStatusEnum;
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import org.bouncycastle.crypto.InvalidCipherTextException;
@@ -46,6 +50,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 +60,7 @@
     @Autowired
     private IDeviceRedisService redisService;
     @Autowired
-    private DeviceExpanSionDao expanSionDao;
+    private DeviceExpanSionMapper expanSionMapper;
     @Autowired
     private TaskInfoMapper taskInfoMapper;
     @Autowired
@@ -96,7 +101,7 @@
 
         } catch (Exception e) {
             // 异常处理
-            throw new IllegalArgumentException("Request failed: " + e.getMessage(), e);
+            throw new IllegalArgumentException("无人机机场注册失败: " + e.getMessage());
         }
     }
 
@@ -111,10 +116,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);
@@ -142,17 +147,16 @@
 
         } catch (Exception e) {
             // 异常处理
-            throw new IllegalArgumentException("Request failed: " + e.getMessage(), e);
+            throw new IllegalArgumentException("无人机机场设备注册失败: " + e.getMessage());
         }
     }
 
     @Override
-    public ResponseResult getDroneState(String deviceId) throws Exception {
+    public String getDroneState(String deviceId) throws Exception {
         DroneStateDto data = getAirportFromCache(deviceId);
         String json = JSON.toJSONString(data);
         String SM4Screct = SM4Util.encrypt("jsimjrby3wqb7dbq", json);
-        String SM2Screct = enSM2(SM4Screct, "23E57DA1E4AB865CCBC325B668762207DEF74345B782237808AE0BABDF26734D");
-        return ResponseResult.success(SM2Screct);
+        return SM4Screct;
     }
 
     @Override
@@ -179,8 +183,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 +190,53 @@
         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.setJobId(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 +247,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.setJobId(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 +353,7 @@
         }
         return null;
     }
+
     private static final String BASE_DIR = "src/main/resources/tmp";
 
     /**
@@ -322,7 +362,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 +394,10 @@
         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);
@@ -366,6 +410,11 @@
         DeviceEntity entity = deviceMapper.selectOne(new LambdaQueryWrapper<DeviceEntity>()
                 .eq(DeviceEntity::getDeviceSn, devicesn));
         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 {
@@ -397,7 +446,7 @@
                     .latitude(entity.getLatitude())
                     .radius(entity.getRadius())
                     .regioncode(entity.getRegioncode())
-                    .deviceid(entity.getDeviceId())
+                    .deviceid(entity.getDeviceSn())
                     .model(entity.getModel())
                     .build();
         }
@@ -421,29 +470,67 @@
         return (OsdSubDeviceReceiver) RedisOpsUtils.get(key);
     }
 
-
-    public DroneStateDto getAirportFromCache(String deviceId) {
-        OsdSubDeviceReceiver receiver = getDroneFromCache(deviceId);
-
-        if (receiver == null) {
-            throw new IllegalArgumentException("Receiver data not found for device ID: " + deviceId);
-        }
-
-        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);
-
-        return builder.build();
+    public void delWaylineJob(String taskId) {
+        waylineJobMapper.delete(new LambdaQueryWrapper<WaylineJobEntity>().like(WaylineJobEntity::getJobId, taskId));
     }
 
+    public DroneStateDto getAirportFromCache(String deviceId) {
+        Optional<OsdSubDeviceReceiver> deviceOsdOpt = redisService.getDeviceOsd(deviceId, OsdSubDeviceReceiver.class);
+        boolean result = deviceOsdOpt.isPresent();
+        if (!result) {
+            String sn = deviceMapper.selectOne(new LambdaQueryWrapper<DeviceEntity>().eq(DeviceEntity::getChildSn, deviceId)).getDeviceSn();
+            Optional<OsdDockReceiver> dockOsdOpt = redisService.getDeviceOsd(sn, OsdDockReceiver.class);
+            boolean results = dockOsdOpt.isPresent();
+            if (!results){
+                DroneStateDto.DroneStateDtoBuilder builder = DroneStateDto.builder();
+                builder.gimbalYaw(0.0)
+                        .gimbalPitch(0.0)
+                        .batteryCapacityPercent(0)
+                        .height(0)
+                        .latitude(0)
+                        .longitude(0)
+                        .modeCode(1)
+                        .elevation(0.0)
+                        .gpsState(0)
+                        .build();
+                return builder.build();
+            }
+            OsdDockReceiver osdDockReceiver = objectMapper.convertValue(dockOsdOpt.get(), OsdDockReceiver.class);
+            int mode;
+            int sne = osdDockReceiver.getModeCode().getVal();
+            if (sne==0){
+                mode=1;
+            }
+            else {
+                mode=2;
+            }
+            DroneStateDto.DroneStateDtoBuilder builder = DroneStateDto.builder();
+            builder.gimbalYaw(0.0)
+                    .gimbalPitch(0.0)
+                    .batteryCapacityPercent(osdDockReceiver.getDroneChargeState().getCapacityPercent())
+                    .height(osdDockReceiver.getHeight())
+                    .latitude(osdDockReceiver.getLatitude())
+                    .longitude(osdDockReceiver.getLongitude())
+                    .modeCode(mode)
+                    .elevation(0.0)
+                    .gpsState(2)
+                    .build();
+            return builder.build();
+        }
+        OsdSubDeviceReceiver receiver = objectMapper.convertValue(deviceOsdOpt.get(), OsdSubDeviceReceiver.class);
+        DroneStateDto.DroneStateDtoBuilder builder = DroneStateDto.builder();
+        builder.gimbalYaw(receiver.getPayloads().get(0).getGimbalYaw())
+                .gimbalPitch(receiver.getPayloads().get(0).getGimbalPitch())
+                .batteryCapacityPercent(receiver.getBattery().getCapacityPercent())
+                .height(receiver.getHeight())
+                .latitude(receiver.getLatitude())
+                .longitude(receiver.getLongitude())
+                .modeCode(2)
+                .elevation(receiver.getElevation())
+                .gpsState(2)
+                .build();
+        return builder.build();
+    }
 
     public static AddTaskDto jsonToDto(JSONObject jsonObject) {
         AddTaskDto dto = new AddTaskDto();
@@ -523,6 +610,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);
@@ -548,10 +661,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 +669,4 @@
         // 调用 update 方法进行更新操作
         waylineJobMapper.update(null, updateWrapper);
     }
-
-}
\ No newline at end of file
+}

--
Gitblit v1.9.3