From ab886689e2c4ef8db2b0767717d69ebbaf10326c Mon Sep 17 00:00:00 2001
From: luxiaotao1123 <t1341870251@163.com>
Date: 星期五, 29 十一月 2024 16:37:20 +0800
Subject: [PATCH] #

---
 zy-acs-manager/src/main/java/com/zy/acs/manager/core/service/MainService.java |  287 ++++++++++++++++++++++++++++++++++-----------------------
 1 files changed, 170 insertions(+), 117 deletions(-)

diff --git a/zy-acs-manager/src/main/java/com/zy/acs/manager/core/service/MainService.java b/zy-acs-manager/src/main/java/com/zy/acs/manager/core/service/MainService.java
index fa70bef..3b6ad34 100644
--- a/zy-acs-manager/src/main/java/com/zy/acs/manager/core/service/MainService.java
+++ b/zy-acs-manager/src/main/java/com/zy/acs/manager/core/service/MainService.java
@@ -3,9 +3,6 @@
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
-import com.zy.acs.framework.common.Cools;
-import com.zy.acs.framework.common.SnowflakeIdWorker;
-import com.zy.acs.framework.exception.CoolException;
 import com.zy.acs.common.domain.AgvAction;
 import com.zy.acs.common.domain.AgvActionItem;
 import com.zy.acs.common.domain.AgvProtocol;
@@ -14,11 +11,19 @@
 import com.zy.acs.common.domain.protocol.AGV_70_UP;
 import com.zy.acs.common.domain.protocol.IMessageBody;
 import com.zy.acs.common.domain.protocol.action.*;
-import com.zy.acs.common.enums.*;
+import com.zy.acs.common.enums.AgvBackpackType;
+import com.zy.acs.common.enums.AgvCompleteType;
+import com.zy.acs.common.enums.AgvDirectionType;
+import com.zy.acs.common.enums.AgvSpeedType;
 import com.zy.acs.common.utils.Utils;
+import com.zy.acs.framework.common.Cools;
+import com.zy.acs.framework.common.SnowflakeIdWorker;
+import com.zy.acs.framework.exception.CoolException;
 import com.zy.acs.manager.common.domain.TaskDto;
+import com.zy.acs.manager.common.domain.param.HandlerPublishParam;
 import com.zy.acs.manager.common.exception.BusinessException;
 import com.zy.acs.manager.core.domain.AgvBackpackDto;
+import com.zy.acs.manager.core.domain.Lane;
 import com.zy.acs.manager.core.domain.TaskPosDto;
 import com.zy.acs.manager.core.service.astart.MapDataDispatcher;
 import com.zy.acs.manager.manager.controller.param.OpenBusSubmitParam;
@@ -30,12 +35,11 @@
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Propagation;
 import org.springframework.transaction.annotation.Transactional;
 import org.springframework.transaction.interceptor.TransactionAspectSupport;
 
 import java.util.*;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.ReentrantLock;
 import java.util.stream.Collectors;
 
 /**
@@ -44,9 +48,6 @@
 @Slf4j
 @Component("mainService")
 public class MainService {
-
-    private static final int LOCK_TIMEOUT = 5;
-    private final ReentrantLock lock = new ReentrantLock(Boolean.TRUE);
 
     @Autowired
     private BusService busService;
@@ -66,6 +67,8 @@
     private ConfigService configService;
     @Autowired
     private ValidService validService;
+    @Autowired
+    private AllocateService allocateService;
     @Autowired
     private CodeService codeService;
     @Autowired
@@ -89,22 +92,27 @@
     @Autowired
     private AgvModelService agvModelService;
     @Autowired
-    private MissionAssignService missionAssignService;
+    private LaneService laneService;
+
 
     @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 +124,7 @@
         bus.setMemo(memo);
 
         if (!busService.save(bus)) {
-            throw new BusinessException("浠诲姟淇濆瓨澶辫触");
+            throw new BusinessException("Internal Server Error!");
         }
 
         // 淇濆瓨浠诲姟
@@ -124,7 +132,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 +144,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 +191,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,40 +211,26 @@
                 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("{}浠诲姟寮傚父锛屾棤娉曟绱㈢┖闂睞gv...", 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() + "鎬荤嚎鏇存柊澶辫触");
-//            }
         } catch (Exception e) {
             log.error("mainService.infuseAgvForTask", e);
             TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
@@ -245,55 +239,52 @@
 
     /**
      * 瑙f瀽鍙栨斁璐ч泦鍚堜换鍔�,杩涜鏈�浼樼殑鎺掑垪缁勫悎椤哄簭 ( 杞﹁締姝ゆ椂鏄┖闂蹭笖闈欐鐨� )
+     * todo: {@link com.zy.acs.manager.core.HandlerController#controlAgv(String, HandlerPublishParam)}
      */
-    @Transactional
-    public synchronized void mergeMajorTask(Long agvId, List<Task> taskList) {
-        if (Cools.isEmpty(taskList)) { return; }
-        boolean lockAcquired = false;
+    @Transactional(propagation = Propagation.REQUIRES_NEW)
+    public void buildMajorTask(Long agvId, List<Task> taskList) {
+        if (Cools.isEmpty(agvId, taskList)) { return; }
         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())) {
-                throw new CoolException("AGV[" + agv.getUuid() + "]褰撳墠涓嶅彲鐢�...");
+            if (!agvService.judgeEnable(agv.getId(), true)) {
+                return;
+//                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() + "]褰撳墠涓嶅湪瀹氫綅...");
-                }
+            if (!Cools.isEmpty(segmentService.getByAgvAndState(agv.getId(), SegmentStateType.WAITING.toString()))
+                    || !Cools.isEmpty(segmentService.getByAgvAndState(agv.getId(), SegmentStateType.RUNNING.toString()))) {
+                throw new CoolException("AGV[" + agv.getUuid() + "] failed to assign锛宐ecause already has the segment in running...");
             }
 
+            // 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 +340,7 @@
 
                 }
 
-                if (backpackLev > agv.getStage()) {
+                if (backpackLev > backpack) {
                     throw new BusinessException("瑙f瀽Task澶辫触,AGV鑳岀瘬宸叉弧......");
                 }
 
@@ -357,8 +348,40 @@
             }
 
             /**
-             *  List<TaskPosDto>: task list on the same channel
+             * 1.Map<String, List<TaskPosDto>> groups
+             *
+             * key: 1000 + ORIGIN
+             * val: [TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType), TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType),...]
+             *
+             * key: 3000 + ORIGIN
+             * val: [TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType), TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType),...]
+             *
+             * key: 2000 + ORIGIN
+             * val: [TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType), TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType),...]
+             *
+             * key: 1000 + DESTINATION
+             * val: [TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType), TaskPosDto(taskId, new Double[]{code.getX(), code.getY()}, posType),...]
+             *
+             * key: 2000 + DESTINATION
+             * 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涓轰竴涓崟浣嶏紝瀵逛粬浠繘琛孎irstWeight鎺掑簭锛岀浉褰撲簬琛�1鐨刱ey鐨勬暟鍊艰繘琛屾湁搴忔帓搴�
+             *  List<TaskPosDto>: task list on the same lane
              *  ArrayList<List<TaskPosDto>>: all the task list by one agv
+             *
+             *  tip: ORI 鍜� DEST 姘歌繙涓嶄細瀛樺湪鍚屼竴涓� List
              */
             ArrayList<List<TaskPosDto>> list = new ArrayList<>(groups.values());
             list.sort((o1, o2) -> {
@@ -366,10 +389,41 @@
                 double o2CompVal = (o2.get(0).getFirstWeight(sameGroupXy) * 100) + o2.get(0).getPosType().compOffset;
                 return (int) (o1CompVal - o2CompVal);
             });
-
+            // 閽堝Dto锛屾寜鐓econdWeight杩涜鎺掑簭
             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<List<TaskPosDto>> pickGroups = new ArrayList<>();
+            List<List<TaskPosDto>> dropGroups = new ArrayList<>();
+
+            for (List<TaskPosDto> group : list) {
+                // Assume 涓�涓换鍔$粍涓墍鏈塗askPosDto鐨凱osType.brief鐩稿悓
+                TaskPosDto.PosType posType = group.get(0).getPosType();
+                if (posType == TaskPosDto.PosType.ORI_LOC || posType == TaskPosDto.PosType.ORI_STA) {
+                    pickGroups.add(group);
+                } else if (posType == TaskPosDto.PosType.DEST_LOC || posType == TaskPosDto.PosType.DEST_STA) {
+                    dropGroups.add(group);
+                } else {
+                    // import tip: the list must only contain ORIGIN and DESTINATION
+                    log.error("the list must only contain ORIGIN and DESTINATION");
+                }
+            }
+
+            currPosition = allocateService.pac(currPosition, pickGroups);
+            currPosition = allocateService.pac(currPosition, dropGroups);
+
+            List<List<TaskPosDto>> reorderedList = new ArrayList<>();
+            reorderedList.addAll(pickGroups);
+            reorderedList.addAll(dropGroups);
+
+            list.clear();
+            list.addAll(reorderedList);
+
 
             // generate travel
             Travel travel = new Travel();
@@ -426,33 +480,29 @@
 
         } catch (Exception e) {
 
-            log.error("mainService.mergeMajorTask[task]", e);
+            log.error("mainService.buildMajorTask[task]", e);
             TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
-        } finally {
-
-            if (lockAcquired) {
-                this.lock.unlock();
-            }
         }
     }
+
 
     /**
      * 鍏呯數 鍥炲緟鏈轰綅浠诲姟
      */
-    @Transactional
-    public synchronized boolean buildMinorTask(Agv agv, AgvDetail agvDetail, TaskTypeType taskType, String destination) {
+    @Transactional(propagation = Propagation.REQUIRES_NEW) // although there is a Transactional here that the lock is isolated, but we can't join the caller's Transactional
+    public boolean buildMinorTask(Agv agv, TaskTypeType taskType, String destination, Jam jam) {
         if (Cools.isEmpty(agv, taskType)) { return false; }
-        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 ...");
-            }
-
-            if (null == agvDetail) {
-                agvDetail = agvDetailService.selectByAgvId(agv.getId());
-            }
+            AgvDetail agvDetail = agvDetailService.selectByAgvId(agv.getId());
             if (!agvService.judgeEnable(agv.getId())) {
                 return false;
+            }
+            if (!Cools.isEmpty(taskService.selectInSts(agv.getId(), TaskStsType.ASSIGN, TaskStsType.PROGRESS))) {
+                throw new CoolException("AGV[" + agv.getUuid() + "] failed to assign锛宐ecause already has the task in running...");
+            }
+            if (!Cools.isEmpty(segmentService.getByAgvAndState(agv.getId(), SegmentStateType.WAITING.toString()))
+                    || !Cools.isEmpty(segmentService.getByAgvAndState(agv.getId(), SegmentStateType.RUNNING.toString()))) {
+                throw new CoolException("AGV[" + agv.getUuid() + "] failed to assign锛宐ecause already has the segment in running...");
             }
 
             Date now = new Date();
@@ -460,15 +510,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锛宼here hadn't any idle funSta锛孴askTypeType锛歿}", agv.getUuid(), taskType.toString());
                     }
                     break;
                 case MOVE:
@@ -479,8 +527,10 @@
             }
 
             if (null == endCode) {
-                log.error("{}鍙疯溅杈嗗缓绔嬪姛鑳戒换鍔″け璐ワ紝鏃犳硶妫�绱㈠埌鐩爣瀹氫綅锛孴askTypeType锛歿}", agv.getUuid(), taskType.toString());
                 return false;
+            }
+            if (!allocateService.validCapacityOfLane(agv, endCode)) {
+                throw new BusinessException("the lane with code:" + endCode.getData() + " is full of AGV[" + agv.getUuid() + "]!!!");
             }
 
             Task task = new Task();
@@ -490,13 +540,18 @@
             task.setSeqNum(Utils.generateSeqNum(Cools.isEmpty(lastTasks)?null:lastTasks.get(0).getSeqNum()));
             task.setOriCode(agvDetail.getCode());
             task.setDestCode(endCode.getId());
+            // lane
+            Lane destLane = laneService.search(endCode.getData());
+            if (null != destLane) {
+                task.setDestLaneHash(destLane.getHashCode());
+            }
             task.setPriority(taskType.equals(TaskTypeType.TO_CHARGE)?2:1);
             task.setTaskSts(TaskStsType.ASSIGN.val());
             task.setTaskType(taskType.val());
             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 +563,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 +602,11 @@
                     next.setState(SegmentStateType.WAITING.toString());
                 }
                 if (!segmentService.save(next)) {
-                    throw new BusinessException("浠诲姟缁勪繚瀛樺け璐�");
+                    throw new BusinessException("segment failed to save");
+                } else {
+                    if (null != jam && i == 0) {
+                        jam.setAvoSeg(next.getId());
+                    }
                 }
             }
 
@@ -559,7 +618,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:
@@ -574,11 +633,6 @@
             TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
 
             return false;
-        } finally {
-
-            if (lockAcquired) {
-                this.lock.unlock();
-            }
         }
     }
 
@@ -603,22 +657,16 @@
 
             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
             Code lastCode = codeService.getById(agvDetail.getRecentCode());
+            Double lastDirection = agvDetail.getAgvAngle();
             if (!lastCode.getData().equals(pathList.get(0))) {
                 throw new CoolException("AGV[" + agv.getUuid() + "]瀹氫綅鍋忕Щ...");
             }
 
-            Double lastDirection = agvDetail.getAgvAngle();
             boolean first = true;
-
             for (Segment segment : segmentList) {
 
                 // 鍒嗘鎵�灞炵殑Task
@@ -850,7 +898,7 @@
                         break;
                     case TO_CHARGE:
                         // 妫�楠屾柟鍚�
-                        FuncSta chargeFuncSta = funcStaService.query(agvId, lastCode.getId(), FuncStaType.CHARGE.toString());
+                        FuncSta chargeFuncSta = funcStaService.query(lastCode.getId(), FuncStaType.CHARGE.toString());
                         Double chargeDirection = Double.parseDouble(chargeFuncSta.getAngle());
                         if (!lastDirection.equals(chargeDirection)) {
                             actionList.add(new Action(
@@ -994,6 +1042,8 @@
             }
             for (Action action : actionList) {
                 action.setActionSts(ActionStsType.ISSUED.val());
+                action.setStartTime(now);
+                action.setIoTime(now);
                 action.setUpdateTime(now);
                 if (!actionService.updateById(action)) {
                     throw new BusinessException(action.getPriority() + " - " + action.getName() + "鍔ㄤ綔鏇存柊澶辫触");
@@ -1143,6 +1193,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 +1226,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 +1301,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());
@@ -1265,7 +1318,7 @@
                 }
 
                 // segment call back
-                trafficService.callback(segmentList);
+                segmentService.processNext(segmentList);
 
                 log.info("Agv [{}] {}浣滀笟瀹屾瘯 ==========>> ", protocol.getAgvNo(), serialNo);
 

--
Gitblit v1.9.1