#
luxiaotao1123
2 小时以前 80f5003a640db7795d69c5e3a73caa685c289b80
zy-acs-manager/src/main/java/com/zy/acs/manager/core/service/AllocateService.java
@@ -3,17 +3,18 @@
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zy.acs.framework.common.Cools;
import com.zy.acs.manager.common.utils.CommonUtil;
import com.zy.acs.manager.core.domain.Lane;
import com.zy.acs.manager.core.domain.AgvCntDto;
import com.zy.acs.manager.core.domain.FilterLaneDto;
import com.zy.acs.manager.core.domain.LaneDto;
import com.zy.acs.manager.core.domain.TaskPosDto;
import com.zy.acs.manager.manager.entity.*;
import com.zy.acs.manager.manager.enums.StatusType;
import com.zy.acs.manager.manager.enums.TaskStsType;
import com.zy.acs.manager.manager.enums.TaskTypeType;
import com.zy.acs.manager.manager.enums.*;
import com.zy.acs.manager.manager.service.*;
import com.zy.acs.manager.system.service.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;
@@ -24,6 +25,8 @@
@Slf4j
@Service
public class AllocateService {
    public static final Integer OUTBOUND_TASKS_ALLOCATE_LIMIT = 5;
    @Autowired
    private AgvService agvService;
@@ -42,43 +45,34 @@
    @Autowired
    private LocService locService;
    @Autowired
    private LaneService laneService;
    private LaneBuilder laneBuilder;
    @Autowired
    private AgvAreaDispatcher agvAreaDispatcher;
    @Autowired
    private SegmentService segmentService;
    /**
     * get available agv list which is idle
     */
    private List<String> getAvailableAgvNos(List<Long> agvIds) {
//        List<Agv> agvList = new ArrayList<>();
//        if (Cools.isEmpty(agvNos)) {
//            // global
//            agvList = agvService.list(new LambdaQueryWrapper<Agv>().eq(Agv::getStatus, StatusType.ENABLE.val));
//        } else {
//            // local
//            for (String agvNo : agvNos) {
//                Agv agv = agvService.selectByUuid(agvNo);
//                if (agv.getStatusBool()) {
//                    agvList.add(agv);
//                }
//            }
//        }
    private List<String> getAvailableAgvNos(List<Long> agvIds, boolean hasRunning) {
        List<Agv> agvList = Cools.isEmpty(agvIds)
                ? agvService.list(new LambdaQueryWrapper<Agv>().eq(Agv::getStatus, StatusType.ENABLE.val))
                : agvIds.stream().map(agvService::getById).filter(Agv::getStatusBool).collect(Collectors.toList());
        List<String> result = new ArrayList<>();
        for (Agv agv : agvList) {
            // 1. without running tasks
            if (0 < taskService.count(new LambdaQueryWrapper<Task>()
                    .eq(Task::getAgvId, agv.getId())
                    .and(i ->
                            i.eq(Task::getTaskSts, TaskStsType.ASSIGN.val())
                            .or().eq(Task::getTaskSts, TaskStsType.PROGRESS.val())
                    )
            )) {
                continue;
            if (!hasRunning) {
                // 1. without running tasks
                if (0 < taskService.count(new LambdaQueryWrapper<Task>()
                        .eq(Task::getAgvId, agv.getId())
                        .and(i -> i
                                .eq(Task::getTaskSts, TaskStsType.ASSIGN.val())
                                .or()
                                .eq(Task::getTaskSts, TaskStsType.PROGRESS.val())
                        )
                )) {
                    continue;
                }
            }
            // 2. in idle status
            if (!agvService.judgeEnable(agv.getId(), true)) {
@@ -89,11 +83,66 @@
        }
        if (!Cools.isEmpty(result)) {
            // todo: 轮询权重
            Collections.shuffle(result);
        }
        return result;
    }
    @Transactional(rollbackFor = Exception.class)
    public synchronized String execute(Task task, AllocateSupport inbound, AllocateSupport normal) {
        // inbound roller station
        Sta rollerOriSta = getInboundRollerSta(task);
        String inboundAgv = tryAllocateForRoller(task, rollerOriSta, true);
        if (!Cools.isEmpty(inboundAgv)) {
            inbound.success(task, inboundAgv, rollerOriSta);
            return inboundAgv;
        }
        // outbound roller station
        Sta rollerDestSta = getOutboundRollerSta(task);
        String outboundAgv = tryAllocateForRoller(task, rollerDestSta, false);
        if (!Cools.isEmpty(outboundAgv)) {
            normal.success(task, outboundAgv, rollerDestSta);
            return outboundAgv;
        }
        String normalAgv = this.normalExecute(task);
        if (!Cools.isEmpty(normalAgv)) {
            normal.success(task, normalAgv, null);
            return normalAgv;
        }
        return null;
    }
    private String tryAllocateForRoller(Task task, Sta rollerSta, boolean inbound) {
        if (rollerSta == null) {
            return null;
        }
        List<String> availableAgvNos = this.getAvailableAgvNos(agvAreaDispatcher.getAgvNosByTask(task), true);
        FilterLaneDto filterLaneDto = this.filterThroughLane(task, availableAgvNos);
        if (filterLaneDto == null) {
            return null;
        }
        String agvNo = inbound
                ? this.checkoutAgvForInboundRoller(task, rollerSta, filterLaneDto.getActualAvailableAgvNos())
                : this.checkoutAgvForOutboundRoller(task, rollerSta, filterLaneDto.getActualAvailableAgvNos());
        if (Cools.isEmpty(agvNo)) {
            return null;
        }
        // record lane hash for later dispatch/traffic-control logic
        if (filterLaneDto.getOriginLaneDto() != null) {
            task.setOriLaneHash(filterLaneDto.getOriginLaneDto().getHashCode());
        }
        if (filterLaneDto.getDestinationLaneDto() != null) {
            task.setDestLaneHash(filterLaneDto.getDestinationLaneDto().getHashCode());
        }
        return agvNo;
    }
    /**
@@ -105,23 +154,150 @@
     *
     *      it can break the limit of the number of agv backpack
     */
    public synchronized Agv execute(Task task) {
        List<String> availableAgvNos = this.getAvailableAgvNos(agvAreaDispatcher.getAgvNosByTask(task));
    public synchronized String normalExecute(Task task) {
        List<String> availableAgvNos = this.getAvailableAgvNos(agvAreaDispatcher.getAgvNosByTask(task), false);
//        List<String> availableAgvNos = this.getAvailableAgvNos(null);
        if (Cools.isEmpty(availableAgvNos)) {
//            log.warn("No available agv to assign the task[{}]", task.getSeqNum());
            return null;
        }
        // calc lane
        FilterLaneDto filterLaneDto = this.filterThroughLane(task, availableAgvNos);
        if (null == filterLaneDto) {
            return null;
        }
        LaneDto originLaneDto = filterLaneDto.getOriginLaneDto();
        LaneDto destinationLaneDto = filterLaneDto.getDestinationLaneDto();
        List<String> actualAvailableAgvNos = filterLaneDto.getActualAvailableAgvNos();
        if (Cools.isEmpty(actualAvailableAgvNos)) {
            return null;
        }
        // choose min number of running task
        actualAvailableAgvNos.sort((o1, o2) -> Integer.compare(
                calcAllocateWeight(o2, task),
                calcAllocateWeight(o1, task)
        ));
        if (null != originLaneDto) {
            task.setOriLaneHash(originLaneDto.getHashCode());
        }
        if (null != destinationLaneDto) {
            task.setDestLaneHash(destinationLaneDto.getHashCode());
        }
        return actualAvailableAgvNos.get(0);
    }
    private String checkoutAgvForInboundRoller(Task task, Sta sta, List<String> availableAgvNos) {
        if (Cools.isEmpty(availableAgvNos, task, sta)) {
            return null;
        }
        for (String agvNo : availableAgvNos) {
            Long agvId = agvService.getAgvId(agvNo);
            Code currentCode = agvDetailService.getCurrentCode(agvId);
            if (null == currentCode) {
                continue;
            }
            // only checkout the agv which at sta code position
            if (!sta.getCode().equals(currentCode.getId())) {
                continue;
            }
            // has running task and within oriSta
//            int taskCnt = taskService.count(new LambdaQueryWrapper<Task>()
//                    .eq(Task::getAgvId, agvId)
//                    .eq(Task::getOriSta, sta.getId())
//                    .and(wrapper -> wrapper
//                            .eq(Task::getTaskSts, TaskStsType.ASSIGN.val())
//                            .or()
//                            .eq(Task::getTaskSts, TaskStsType.PROGRESS.val())
//                    )
//            );
//            if (taskCnt == 0) {
//                continue;
//            }
            // in TransferStationHandler.hasDelayAtSta
            Segment currSeg = segmentService.getRollerWaiting(agvId, sta.getCode(), TaskPosDto.PosType.ORI_STA);
            if (null == currSeg) {
                continue;
            }
            // has enough backpack space to load
            Integer backpack = agvService.getBackpack(agvId);
            List<Integer> usedBackpacks = segmentService.selectUsedBackpacks(null, agvId);
            if (usedBackpacks.size() >= backpack) {
                continue;
            }
            return agvNo;
        }
        return null;
    }
    private String checkoutAgvForOutboundRoller(Task task, Sta sta, List<String> availableAgvNos) {
        if (Cools.isEmpty(availableAgvNos, task, sta)) {
            return null;
        }
        List<Task> taskList = taskService.list(new LambdaQueryWrapper<Task>()
                .eq(Task::getDestSta, sta.getId())
                .eq(Task::getTaskSts, TaskStsType.WAITING.val())
                .isNotNull(Task::getAgvId)
        );
        if (Cools.isEmpty(taskList)) {
            return null;
        }
        List<AgvCntDto> cntDtoList = new ArrayList<>();
        for (Task t : taskList) {
            AgvCntDto cntDto = new AgvCntDto(t.getAgvId());
            if (AgvCntDto.has(cntDtoList, cntDto)) {
                AgvCntDto dto = AgvCntDto.find(cntDtoList, cntDto);
                assert null != dto;
                dto.setCount(dto.getCount() + 1);
            } else {
                cntDtoList.add(cntDto);
            }
        }
        cntDtoList.sort(new Comparator<AgvCntDto>() {
            @Override
            public int compare(AgvCntDto o1, AgvCntDto o2) {
                return o1.getCount() - o2.getCount();
            }
        });
        for (AgvCntDto cntDto : cntDtoList) {
            if (cntDto.getAgvId() >= OUTBOUND_TASKS_ALLOCATE_LIMIT) {
                continue;
            }
            return agvService.getAgvNo(cntDto.getAgvId());
        }
        return null;
    }
    public FilterLaneDto filterThroughLane(Task task, List<String> availableAgvNos) {
        if (Cools.isEmpty(availableAgvNos, task)) {
            return null;
        }
        Integer maxAgvCountInLane = configService.getVal("maxAgvCountInLane", Integer.class);
        // checkout lane
        Lane originLane = taskService.checkoutOriginLane(task);
        Lane destinationLane = taskService.checkoutDestinationLane(task);
        LaneDto originLaneDto = taskService.checkoutOriginLane(task);
        LaneDto destinationLaneDto = taskService.checkoutDestinationLane(task);
        // allocate about origin
        List<String> availableAgvNosByOriLane = new ArrayList<>(availableAgvNos);
        if (null != originLane) {
            List<String> agvNosByOriLane = findAgvNosByLane(originLane);    // the agv list that had tasks in this lane
        if (null != originLaneDto) {
            List<String> agvNosByOriLane = findAgvNosByLane(originLaneDto);    // the agv list that had tasks in this lane
            // if full lane
            if (agvNosByOriLane.size() >= maxAgvCountInLane) {
@@ -134,8 +310,8 @@
        // allocate about destination
        List<String> availableAgvNosByDestLane = new ArrayList<>(availableAgvNos);
        if (null != destinationLane) {
            List<String> agvNosByDestLane = findAgvNosByLane(destinationLane);
        if (null != destinationLaneDto) {
            List<String> agvNosByDestLane = findAgvNosByLane(destinationLaneDto);
            if (agvNosByDestLane.size() >= maxAgvCountInLane) {
                availableAgvNosByDestLane = Cools.getIntersection(agvNosByDestLane, availableAgvNos);
@@ -158,30 +334,14 @@
            return null;
        }
        // choose min number of running task
        actualAvailableAgvNos.sort(new Comparator<String>() {
            @Override
            public int compare(String agvNo1, String agvNo2) {
                return calcAllocateWeight(agvNo1, task) - calcAllocateWeight(agvNo2, task);
            }
        });
        if (null != originLane) {
            task.setOriLaneHash(originLane.getHashCode());
        }
        if (null != destinationLane) {
            task.setDestLaneHash(destinationLane.getHashCode());
        }
        return agvService.selectByUuid(actualAvailableAgvNos.stream().findFirst().orElse(null));
        return new FilterLaneDto(originLaneDto, destinationLaneDto, actualAvailableAgvNos);
    }
    public List<String> findAgvNosByLane(Lane lane) {
        if (null == lane) {
    public List<String> findAgvNosByLane(LaneDto laneDto) {
        if (null == laneDto) {
            return new ArrayList<>();
        }
        List<Task> taskList = taskService.findRunningTasksByLaneHash(lane.getHashCode());
        List<Task> taskList = taskService.findRunningTasksByLaneHash(laneDto.getHashCode());
        if (Cools.isEmpty(taskList)) {
            return new ArrayList<>();
        }
@@ -252,11 +412,11 @@
    }
    public Boolean validCapacityOfLane(String agvNo, Code code) {
        Lane lane = laneService.search(code.getData());
        if (null != lane) {
        LaneDto laneDto = laneBuilder.search(code.getData());
        if (null != laneDto) {
            Integer maxAgvCountInLane = configService.getVal("maxAgvCountInLane", Integer.class);
            List<String> agvNosByLane = this.findAgvNosByLane(lane);
            List<String> agvNosByLane = this.findAgvNosByLane(laneDto);
            agvNosByLane.remove(agvNo);
            if (agvNosByLane.size() >= maxAgvCountInLane) {
                return false;
@@ -314,4 +474,52 @@
        return theLastOne.get(theLastOne.size() - 1).getXy();
    }
    // about roller --------------------------------------------
    private Sta getInboundRollerSta(Task task) {
        TaskTypeType type = TaskTypeType.get(task.getTaskTypeEl());
        switch (Objects.requireNonNull(type)) {
            case STA_TO_LOC:
            case STA_TO_STA:
                Long oriStaId = task.getOriSta();
                if (null == oriStaId) {
                    return null;
                }
                Sta oriSta = staService.getById(oriStaId);
                if (oriSta == null || Cools.isEmpty(oriSta.getStaType())) {
                    return null;
                }
                if (StaTypeType.ROLLER.val() != oriSta.getStaType()) {
                    return null;
                }
                return oriSta;
            default:
                return null;
        }
    }
    private Sta getOutboundRollerSta(Task task) {
        TaskTypeType type = TaskTypeType.get(task.getTaskTypeEl());
        switch (Objects.requireNonNull(type)) {
            case LOC_TO_STA:
            case STA_TO_STA:
                Long destStaId = task.getDestSta();
                if (null == destStaId) {
                    return null;
                }
                Sta destSta = staService.getById(destStaId);
                if (destSta == null || Cools.isEmpty(destSta.getStaType())) {
                    return null;
                }
                if (StaTypeType.ROLLER.val() != destSta.getStaType()) {
                    return null;
                }
                return destSta;
            default:
                return null;
        }
    }
}