#
luxiaotao1123
2024-11-04 7f70cb15d035f0c233b9e62b9e43aa985317c908
zy-acs-manager/src/main/java/com/zy/acs/manager/core/service/MainService.java
@@ -18,6 +18,7 @@
import com.zy.acs.common.utils.Utils;
import com.zy.acs.manager.common.domain.TaskDto;
import com.zy.acs.manager.common.exception.BusinessException;
import com.zy.acs.manager.common.utils.CommonUtil;
import com.zy.acs.manager.core.domain.AgvBackpackDto;
import com.zy.acs.manager.core.domain.TaskPosDto;
import com.zy.acs.manager.core.service.astart.MapDataDispatcher;
@@ -67,6 +68,8 @@
    @Autowired
    private ValidService validService;
    @Autowired
    private AllocateService allocateService;
    @Autowired
    private CodeService codeService;
    @Autowired
    private MapService mapService;
@@ -88,23 +91,26 @@
    private TrafficService trafficService;
    @Autowired
    private AgvModelService agvModelService;
    @Autowired
    private MissionAssignService missionAssignService;
    @SuppressWarnings("all")
    @Transactional
    public void generateBusAndTask(OpenBusSubmitParam busSubmitParam, String memo) {
    public Bus generateBusAndTask(OpenBusSubmitParam busSubmitParam, String memo) {
        String errorMsg = busService.checkoutValid(busSubmitParam);
        if (!Cools.isEmpty(errorMsg)) {
            throw new BusinessException(errorMsg);
        }
        String batch = busSubmitParam.getBatch();
        List<TaskDto> taskDtoList = busSubmitParam.getTaskList();
        if (Cools.isEmpty(taskDtoList)) {
            throw new BusinessException("taskDtoList 不能为空");
            throw new BusinessException("taskList can't be empty!");
        }
        // 优先级排序
        taskDtoList.sort((o1, o2) -> o2.getPriority() - o1.getPriority());
        // 校验
        List<Task> taskList = validService.validBusDto(taskDtoList);
        List<Task> taskList = validService.validTaskDtoList(taskDtoList);
        // 保存总线
        Date now = new Date();
@@ -116,7 +122,7 @@
        bus.setMemo(memo);
        if (!busService.save(bus)) {
            throw new BusinessException("任务保存失败");
            throw new BusinessException("Internal Server Error!");
        }
        // 保存任务
@@ -124,7 +130,7 @@
            task.setBusId(bus.getId());
            task.setTaskSts(TaskStsType.INIT.val());
            if (!taskService.save(task)) {
                throw new BusinessException(task.getSeqNum() + "任务保存失败");
                throw new BusinessException("seqNum:" + task.getSeqNum() + " failed to save!");
            }
            // 修改库位状态
@@ -136,44 +142,44 @@
                case LOC_TO_LOC:
                    oriLoc = locService.getById(task.getOriLoc());
                    if (!oriLoc.getLocSts().equals(LocStsType.STOCK.val())) {
                        throw new BusinessException("oriLoc:" + task.getOriLoc$() + " 不是在库状态");
                        throw new BusinessException("oriLoc:" + task.getOriLoc$() + " is not in STOCK status");
                    }
                    oriLoc.setLocSts(LocStsType.PAKOUT.val());
                    oriLoc.setUpdateTime(now);
                    if (!locService.updateById(oriLoc)) {
                        throw new BusinessException("oriLoc:" + task.getOriLoc$() + " 修改库位状态失败");
                        throw new BusinessException("oriLoc:" + task.getOriLoc$() + " failed to update");
                    }
                    destLoc = locService.getById(task.getDestLoc());
                    if (!destLoc.getLocSts().equals(LocStsType.IDLE.val())) {
                        throw new BusinessException("destLoc:" + task.getDestLoc$() + " 不是空闲状态");
                        throw new BusinessException("destLoc:" + task.getDestLoc$() + " is not in IDLE status");
                    }
                    destLoc.setLocSts(LocStsType.PAKIN.val());
                    destLoc.setUpdateTime(now);
                    if (!locService.updateById(destLoc)) {
                        throw new BusinessException("destLoc:" + task.getDestLoc$() + " 修改库位状态失败");
                        throw new BusinessException("destLoc:" + task.getDestLoc$() + " failed to update");
                    }
                    break;
                case LOC_TO_STA:
                    oriLoc = locService.getById(task.getOriLoc());
                    if (!oriLoc.getLocSts().equals(LocStsType.STOCK.val())) {
                        throw new BusinessException("oriLoc:" + task.getOriLoc$() + " 不是在库状态");
                        throw new BusinessException("oriLoc:" + task.getOriLoc$() + " is not in STOCK status");
                    }
                    oriLoc.setLocSts(LocStsType.PAKOUT.val());
                    oriLoc.setUpdateTime(now);
                    if (!locService.updateById(oriLoc)) {
                        throw new BusinessException("oriLoc:" + task.getOriLoc$() + " 修改库位状态失败");
                        throw new BusinessException("oriLoc:" + task.getOriLoc$() + " failed to update");
                    }
                    break;
                case STA_TO_LOC:
                    destLoc = locService.getById(task.getDestLoc());
                    if (!destLoc.getLocSts().equals(LocStsType.IDLE.val())) {
                        throw new BusinessException("destLoc:" + task.getDestLoc$() + " 不是空闲状态");
                        throw new BusinessException("destLoc:" + task.getDestLoc$() + " is not in IDLE status");
                    }
                    destLoc.setLocSts(LocStsType.PAKIN.val());
                    destLoc.setUpdateTime(now);
                    if (!locService.updateById(destLoc)) {
                        throw new BusinessException("destLoc:" + task.getDestLoc$() + " 修改库位状态失败");
                        throw new BusinessException("destLoc:" + task.getDestLoc$() + " failed to update");
                    }
                    break;
                case STA_TO_STA:
@@ -183,14 +189,14 @@
            }
        }
        return bus;
    }
    /**
     * 任务分配给车辆 ( 车辆此时是空闲且静止的 )
     */
    @Transactional
    public synchronized void infuseAgvForTask(Bus bus) {
    public synchronized void allocateTask(Bus bus) {
        try {
            Date now = new Date();
            List<Task> taskList = taskService.list(new LambdaQueryWrapper<Task>()
@@ -203,39 +209,54 @@
                bus.setBusSts(BusStsType.PROGRESS.val());
                bus.setUpdateTime(now);
                if (!busService.updateById(bus)) {
                    log.error("Bus [{}] 更新失败 !!!", bus.getUuid());
                    log.error("Bus [{}] failed to Update !!!", bus.getUuid());
                }
                return;
            }
            List<Long> taskIds = taskList.stream().map(Task::getId).distinct().collect(Collectors.toList());
            Map<String, List<Long>> taskAllot = new HashMap<>();
            List<Long> taskIds = taskList.stream().map(Task::getId).distinct().collect(Collectors.toList());
            for (Task task : taskList) {
                Agv agv = missionAssignService.execute(task, taskAllot, taskIds);
                Agv agv = allocateService.execute(task);
                if (null == agv) {
                    log.warn("{}任务异常,无法检索空闲Agv...", task.getSeqNum());
                    log.warn("Task[{}] has an issue, because it failed to checkout agv which is idle...", task.getSeqNum());
                    continue;
                }
                task.setAgvId(agv.getId());
                task.setTaskSts(TaskStsType.WAITING.val());
                task.setIoTime(now);
                task.setUpdateTime(now);
                if (!taskService.updateById(task)) {
                    throw new BusinessException(task.getSeqNum() + "任务更新失败");
                }
                if (taskAllot.containsKey(agv.getUuid())) {
                    taskAllot.get(agv.getUuid()).add(task.getId());
                } else {
                    taskAllot.put(agv.getUuid(), Utils.singletonList(task.getId()));
                    throw new BusinessException("seqNum: " + task.getSeqNum() + " failed to update");
                }
            }
//            bus.setUpdateTime(now);
//            if (!busService.updateById(bus)) {
//                throw new BusinessException(bus.getSeqNum() + "总线更新失败");
            // ------------------------------------------
//
//            Map<String, List<Long>> taskAllot = new HashMap<>();
//            for (Task task : taskList) {
//                Agv agv = missionAssignService.execute(task, taskAllot, taskIds);
//                if (null == agv) {
//                    log.warn("Task[{}] has an issue, because it failed to checkout agv which is idle...", task.getSeqNum());
//                    continue;
//                }
//
//
//                task.setAgvId(agv.getId());
//                task.setTaskSts(TaskStsType.WAITING.val());
//                task.setIoTime(now);
//                task.setUpdateTime(now);
//                if (!taskService.updateById(task)) {
//                    throw new BusinessException("seqNum: " + task.getSeqNum() + " failed to update");
//                }
//
//                if (taskAllot.containsKey(agv.getUuid())) {
//                    taskAllot.get(agv.getUuid()).add(task.getId());
//                } else {
//                    taskAllot.put(agv.getUuid(), Utils.singletonList(task.getId()));
//                }
//            }
        } catch (Exception e) {
            log.error("mainService.infuseAgvForTask", e);
@@ -247,53 +268,49 @@
     * 解析取放货集合任务,进行最优的排列组合顺序 ( 车辆此时是空闲且静止的 )
     */
    @Transactional
    public synchronized void mergeMajorTask(Long agvId, List<Task> taskList) {
    public synchronized void buildMajorTask(Long agvId, List<Task> taskList) {
        if (Cools.isEmpty(taskList)) { return; }
        boolean lockAcquired = false;
        try {
            if (!(lockAcquired = this.lock.tryLock(LOCK_TIMEOUT, TimeUnit.SECONDS))) {
                throw new CoolException("generate [task] action fail, cause can not acquire lock ...");
            }
            Date now = new Date();
            final String sameGroupXy = configService.getVal( "sameGroupXy", String.class);
            // valid -----------------------------------------------
            Agv agv = agvService.getById(agvId);
            if (!agvService.judgeEnable(agv.getId(), agvDetail -> agvDetail.getVol() > agv.getChargeLine())) {
            if (!agvService.judgeEnable(agv.getId(), true)) {
                throw new CoolException("AGV[" + agv.getUuid() + "]当前不可用...");
            }
            if (!Cools.isEmpty(taskService.selectInSts(agvId, TaskStsType.ASSIGN, TaskStsType.PROGRESS))) {
                throw new CoolException("AGV[" + agv.getUuid() + "]分配任务失败,已存在执行任务...");
            }
            AgvDetail agvDetail = agvDetailService.selectByAgvId(agvId);
            assert agvDetail != null;
            if (agvDetail.getPos() == 0) {
                if (!agvDetail.getAgvStatus().equals(AgvStatusType.CHARGE)) {
                    throw new CoolException("AGV[" + agv.getUuid() + "]当前不在定位...");
                }
            }
            // execute ----------------------------------------------------
            Date now = new Date();
            // sort and sub
            taskList.sort(new Comparator<Task>() {
                @Override
                public int compare(Task o1, Task o2) {
                    return 0;
                    return o2.getPriority() - o1.getPriority();
                }
            });
            if (taskList.size() > agv.getStage()) {
                taskList = taskList.subList(0, agv.getStage());
            Integer backpack = agvService.getBackpack(agv);
            if (taskList.size() > backpack) {
                taskList = taskList.subList(0, backpack);
            }
            AgvDetail agvDetail = agvDetailService.selectByAgvId(agvId);
            List<AgvBackpackDto> backpackDtoList = new ArrayList<>();
            /**
             * single agvId
             * 同巷道归类
             * same lane for every single agvId
             *
             * key: y + TaskPosDto.PosType.ORI_LOC / ORI_STA / DEST_LOC / DEST_STA
             * key: y(val) + TaskPosDto.PosType.ORI_LOC / ORI_STA / DEST_LOC / DEST_STA
             * val: new TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType)
             */
            Map<String, List<TaskPosDto>> groups = new HashMap<>();
            List<AgvBackpackDto> backpackDtoList = new ArrayList<>();
            final String sameGroupXy = configService.getVal( "sameGroupXy", String.class);
            int backpackLev = 0;
            for (Task task : taskList) {
@@ -349,7 +366,7 @@
                }
                if (backpackLev > agv.getStage()) {
                if (backpackLev > backpack) {
                    throw new BusinessException("解析Task失败,AGV背篓已满......");
                }
@@ -357,7 +374,31 @@
            }
            /**
             *  List<TaskPosDto>: task list on the same channel
             * 1.Map<String, List<TaskPosDto>> groups
             *
             * key: 1000 + ORI_LOC
             * val: [TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType), TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType),...]
             *
             * key: 3000 + ORI_LOC
             * val: [TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType), TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType),...]
             *
             * key: 2000 + ORI_LOC
             * val: [TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType), TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType),...]
             *
             * ......
             *
             * 2.ArrayList<List<TaskPosDto>> list
             * [
             *  [TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType), TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType),...],
             *  [TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType), TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType),...],
             *  [TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType), TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType),...],
             *  ......
             * ]
             */
            /**
             * 对所有巷道进行有序排序,先是针对List为一个单位,对他们进行FirstWeight排序,相当于表1的key的数值进行有序排序
             *  List<TaskPosDto>: task list on the same lane
             *  ArrayList<List<TaskPosDto>>: all the task list by one agv
             */
            ArrayList<List<TaskPosDto>> list = new ArrayList<>(groups.values());
@@ -366,9 +407,53 @@
                double o2CompVal = (o2.get(0).getFirstWeight(sameGroupXy) * 100) + o2.get(0).getPosType().compOffset;
                return (int) (o1CompVal - o2CompVal);
            });
            // 针对Dto,按照SecondWeight进行排序
            for (List<TaskPosDto> taskPosDtoList : list) {
                taskPosDtoList.sort((o1, o2) -> (int) (o1.getSecondWeight(sameGroupXy) * 100 - o2.getSecondWeight(sameGroupXy) * 100));
            }
            // re-order by agv current position
            Code currCode = codeService.getById(agvDetail.getRecentCode());
            Double[] currPosition = new Double[] {currCode.getX(), currCode.getY()};
            List<TaskPosDto> theFirstOne = list.get(0);
            List<TaskPosDto> theLastOne = list.get(list.size() - 1);
            if (list.size() == 1) {
                TaskPosDto head = theFirstOne.get(0);
                TaskPosDto tail = theFirstOne.get(theFirstOne.size() - 1);
                int distanceByHead = CommonUtil.calcDistance(currPosition, head.getXy());
                int distanceByTail = CommonUtil.calcDistance(currPosition, tail.getXy());
                if (distanceByTail < distanceByHead) {
                    Collections.reverse(theFirstOne);
                }
            } else {
                TaskPosDto headOfFirst = theFirstOne.get(0);
                TaskPosDto tailOfFirst = theFirstOne.get(theFirstOne.size() - 1);
                TaskPosDto headOfLast = theLastOne.get(0);
                TaskPosDto tailOfLast = theLastOne.get(theLastOne.size() - 1);
                int distanceByHeadOfFirst = CommonUtil.calcDistance(currPosition, headOfFirst.getXy());
                int distanceByTailOfFirst = CommonUtil.calcDistance(currPosition, tailOfFirst.getXy());
                int distanceByHeadOfLast = CommonUtil.calcDistance(currPosition, headOfLast.getXy());
                int distanceByTailOfLast = CommonUtil.calcDistance(currPosition, tailOfLast.getXy());
                if (Math.min(distanceByHeadOfLast, distanceByTailOfLast) < Math.min(distanceByHeadOfFirst, distanceByTailOfFirst)) {
                    Collections.reverse(list);
                    if (distanceByTailOfLast < distanceByHeadOfLast) {
                        Collections.reverse(theLastOne);
                    }
                } else {
                    if (distanceByTailOfFirst < distanceByHeadOfFirst) {
                        Collections.reverse(theFirstOne);
                    }
                }
            }
            // generate travel
@@ -460,15 +545,13 @@
            switch (taskType) {
                case TO_CHARGE:
                case TO_STANDBY:
                    List<FuncSta> funcStaList = funcStaService.list(new LambdaQueryWrapper<FuncSta>()
                                    .eq(FuncSta::getType, FuncStaType.query(taskType).toString())
                                    .eq(FuncSta::getAgvId, agv.getId())
                                    .eq(FuncSta::getState, FuncStaStateType.IDLE.toString())
                                    .eq(FuncSta::getStatus, StatusType.ENABLE.val)
                    );
                    if (!Cools.isEmpty(funcStaList)) {
                        FuncSta funcSta = funcStaList.get(0);
                    List<FuncSta> idleFunStaList = funcStaService.findInIdleStatus(FuncStaType.query(taskType), agv.getId());
                    if (!Cools.isEmpty(idleFunStaList)) {
                        FuncSta funcSta = funcStaService.checkoutClosestFunSta(agvDetail.getRecentCode(), idleFunStaList);
                        endCode = codeService.getById(funcSta.getCode());
                    }
                    if (null == endCode) {
                        log.warn("AGV[{}] failed to search destination,there hadn't any idle funSta,TaskTypeType:{}", agv.getUuid(), taskType.toString());
                    }
                    break;
                case MOVE:
@@ -479,7 +562,6 @@
            }
            if (null == endCode) {
                log.error("{}号车辆建立功能任务失败,无法检索到目标定位,TaskTypeType:{}", agv.getUuid(), taskType.toString());
                return false;
            }
@@ -496,7 +578,7 @@
            task.setIoTime(now);
            task.setStartTime(now);
            if (!taskService.save(task)) {
                throw new BusinessException(task.getSeqNum() + "任务保存失败");
                throw new BusinessException(task.getSeqNum() + " failed to save");
            }
            // generate travel
@@ -508,7 +590,7 @@
            travel.setTaskIds(JSON.toJSONString(Collections.singletonList(task.getId())));
            travel.setState(TravelStateType.RUNNING.toString());
            if (!travelService.save(travel)) {
                throw new BusinessException("任务组保存失败");
                throw new BusinessException("travel failed to save");
            }
            // generate segment
@@ -547,7 +629,7 @@
                    next.setState(SegmentStateType.WAITING.toString());
                }
                if (!segmentService.save(next)) {
                    throw new BusinessException("任务组保存失败");
                    throw new BusinessException("segment failed to save");
                }
            }
@@ -559,7 +641,7 @@
                    destFuncSta.setState(FuncStaStateType.OCCUPIED.toString());
                    destFuncSta.setUpdateTime(now);
                    if (!funcStaService.updateById(destFuncSta)) {
                        log.error("FuncSta [{}] 更新状态失败 !!!", destFuncSta.getName());
                        log.error("FuncSta [{}] failed to update !!!", destFuncSta.getName());
                    }
                    break;
                case MOVE:
@@ -603,11 +685,6 @@
            AgvDetail agvDetail = agvDetailService.selectByAgvId(agvId);
            assert agvDetail != null;
            if (agvDetail.getPos() == 0) {
                if (!agvDetail.getAgvStatus().equals(AgvStatusType.CHARGE)) {
                    throw new CoolException("AGV[" + agv.getUuid() + "]当前不在定位...");
                }
            }
            List<Action> actionList = new ArrayList<>();
            // start node
@@ -994,6 +1071,7 @@
            }
            for (Action action : actionList) {
                action.setActionSts(ActionStsType.ISSUED.val());
                action.setStartTime(now);
                action.setUpdateTime(now);
                if (!actionService.updateById(action)) {
                    throw new BusinessException(action.getPriority() + " - " + action.getName() + "动作更新失败");
@@ -1143,6 +1221,7 @@
                            if (null != action) {
                                action.setActionSts(ActionStsType.FINISH.val());
                                action.setEndTime(now);
                                action.setUpdateTime(now);
                                if (!actionService.updateById(action)) {
                                    log.error("Action [{}] 更新失败 !!!", action.getPriority() + " - " + action.getName());
@@ -1175,6 +1254,7 @@
                            );
                            if (null != action) {
                                action.setActionSts(ActionStsType.FINISH.val());
                                action.setEndTime(now);
                                action.setUpdateTime(now);
                                if (!actionService.updateById(action)) {
                                    log.error("Action [{}] 更新失败 !!!", action.getPriority() + " - " + action.getName());
@@ -1249,6 +1329,7 @@
                );
                for (Action action : actionList) {
                    action.setActionSts(ActionStsType.FINISH.val());
                    action.setEndTime(now);
                    action.setUpdateTime(now);
                    if (!actionService.updateById(action)) {
                        log.error("Action [{}] 更新失败 !!!", action.getPriority() + " - " + action.getName());