1
zhang
2025-09-10 58bb9d3e0a8d8c385085f8cce3492eccf5448ec4
src/main/java/com/zy/asrs/service/impl/CtuMainServiceImpl.java
@@ -1,10 +1,15 @@
package com.zy.asrs.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zy.asrs.entity.WrkMast;
import com.zy.asrs.mapper.*;
import com.zy.asrs.service.*;
import com.zy.common.service.CommonService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.core.common.DateUtils;
import com.core.exception.CoolException;
import com.zy.asrs.domain.param.OpenBusSubmitParam;
import com.zy.asrs.domain.param.TaskDto;
import com.zy.asrs.mapper.WrkMastMapper;
import com.zy.asrs.service.LocMastService;
import com.zy.asrs.service.WrkMastService;
import com.zy.common.utils.HttpHandler;
import com.zy.common.utils.News;
import com.zy.core.cache.MessageQueue;
import com.zy.core.cache.SlaveConnection;
@@ -14,76 +19,164 @@
import com.zy.core.model.protocol.StaProtocol;
import com.zy.core.properties.SlaveProperties;
import com.zy.core.thread.SiemensDevpThread;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
 * 立体仓库WCS系统主流程业务
 * Created by vincent on 2020/8/6
 */
@Slf4j
@Service("mainService")
@Service("ctuMainService")
@Transactional
@Data
public class CtuMainServiceImpl {
    public static final long COMMAND_TIMEOUT = 5 * 1000;
    @Value("${ctu.url}")
    private String ctuUrl;
    @Value("${ctu.sendTask}")
    private String sendTask;
    @Value("${ctu.getLoc}")
    private String getLoc;
    @Value("${ctu.update}")
    private String updateSta;
    @Autowired
    private SlaveProperties slaveProperties;
    @Autowired
    private WrkMastMapper wrkMastMapper;
    @Autowired
    private LocMastService locMastService;
    @Autowired
    private WrkMastService wrkMastService;
    private boolean flag1001 = false;
    public Integer wrkNo = 10000;
    private boolean flag1007 = false;
    private Map<Integer, Long> staNoSet = new HashMap<>();
    public Map<Integer, Long> getStaNoSet() {
        return staNoSet;
    }
    public void setStaNoSet(Map<Integer, Long> staNoSet) {
        this.staNoSet = staNoSet;
    }
    /**
     * 入库,从拣料站到入库站(CTU取货站)
     */
    public synchronized void generateStoreWrkFile(Integer mark) {
        // 根据输送线plc遍历
        for (DevpSlave devp : slaveProperties.getDevp()) {
            // 遍历入库口
            for (DevpSlave.Sta inSta : devp.getInSta()) {
                // 获取入库站信息
                SiemensDevpThread devpThread = (SiemensDevpThread) SlaveConnection.get(SlaveType.Devp, devp.getId());
                StaProtocol staProtocol = devpThread.getStation().get(inSta.getStaNo());
                if (staProtocol == null) {
                    continue;
                } else {
                    staProtocol = staProtocol.clone();
                }
                // 判断是否满足条件
                if (!staProtocol.isLoading()) {
                    continue;
                }
                if (staProtocol.isAutoing() && staProtocol.isInEnable()
                        && !staProtocol.isEmptyMk() && (staProtocol.getWorkNo() == 0 || staProtocol.getWorkNo() == 9999)
                        && staProtocol.isPakMk()) {
                    WrkMast wrkMast = wrkMastMapper.selectByWrkNo(staProtocol.getWorkNo());
                    if (wrkMast.getWrkSts() == 106) {
                        //下发移动任务,并生成入库工作档
                    } else {
                        log.info("" + mark + " - " + staProtocol.getWorkNo() + " - 找不到对应的工作档");
                    }
                }
        for (Map.Entry<Integer, Long> entry : staNoSet.entrySet()) {
            if (entry.getValue() != null && System.currentTimeMillis() - entry.getValue() > 1000 * 60 * 5) {
                log.info("超时:{}", entry.getKey());
                staNoSet.remove(entry.getKey());
            }
        }
        // 根据输送线plc遍历
        SiemensDevpThread devpThread = (SiemensDevpThread) SlaveConnection.get(SlaveType.Devp, 1);
        StaProtocol staProtocol = devpThread.getStation().get(1004);
        if (staProtocol == null) {
            return;
        } else {
            staProtocol = staProtocol.clone();
        }
        // 判断是否满足条件
        if (!staProtocol.isLoading()) {
            return;
        }
        Long i = staNoSet.get(staProtocol.getWorkNo());
        if (i != null) {
            return;
        }
        // && staProtocol.isInEnable()
        if (staProtocol.getWorkNo() > 0 && staProtocol.isAutoing() && !staProtocol.isEmptyMk() && staProtocol.isPakMk()) {
            if (staProtocol.getStaNo() == 1004) {
                try {
                    Thread.sleep(8000L);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                staProtocol.setStaNo((short) 1007);
                boolean result = MessageQueue.offer(SlaveType.Devp, 1, new Task(2, staProtocol));
                staNoSet.put(staProtocol.getWorkNo(), System.currentTimeMillis());
                log.info("入库输送线下发:{},{}", staProtocol.getWorkNo(), 1007);
            }
//                    WrkMast wrkMast = wrkMastMapper.selectByWrkNo(staProtocol.getWorkNo());
//                    if (wrkMast != null) {
//                        //下发移动任务,并生成入库工作档
//                        WrkMast in = new WrkMast();
//                        wrkMast.setWrkSts(223L);
//                        wrkMast.setModiTime(new Date());
//                        wrkMastService.updateById(wrkMast);
//                        in.setSourceLocNo("1007");
//                        in.setLocNo(wrkMast.getSourceLocNo());
//                        in.setIoType(10);
//                        in.setIoTime(new Date());
//                        in.setWrkSts(1L); // 工作状态:11.生成出库ID
//                        in.setIoPri(13D); // 优先级:13
//                        in.setFullPlt("Y"); // 满板:Y
//                        in.setPicking("N"); // 拣料
//                        in.setExitMk("N"); // 退出
//                        in.setEmptyMk("Y"); // 空板
//                        in.setLinkMis("N");
//                        in.setAppeTime(new Date());
//                        in.setModiTime(new Date());
//                        in.setBarcode(wrkMast.getBarcode());
//                        in.setPlcWrkNo(wrkMast.getPlcWrkNo());
//                        wrkMastService.insert(in);
//                        LocMast locMast = locMastService.selectById(wrkMast.getSourceLocNo());
//                        locMast.setLocSts("S");
//                        locMast.setModiTime(new Date());
//                        locMastService.updateById(locMast);
//                    }
        }
    }
    public synchronized void outToPlc(Integer mark) {
        // 根据输送线plc遍历
        SiemensDevpThread devpThread = (SiemensDevpThread) SlaveConnection.get(SlaveType.Devp, 1);
        StaProtocol staProtocol = devpThread.getStation().get(1007);
        if (staProtocol == null) {
            return;
        } else {
            staProtocol = staProtocol.clone();
        }
        // 判断是否满足条件
        if (!staProtocol.isLoading()) {
            return;
        }
        if (flag1007 && staProtocol.getWorkNo() > 0 && staProtocol.isAutoing() && !staProtocol.isEmptyMk() && staProtocol.isPakMk()) {
            staProtocol.setWorkNo(0);
            staProtocol.setStaNo((short) 0);
            boolean result = MessageQueue.offer(SlaveType.Devp, 1, new Task(2, staProtocol));
            log.info("取走写入确认位:{},{}", staProtocol.getWorkNo(), 1007);
        }
    }
    /**
     * 出库站到拣料站
     * 出库
     */
    public synchronized void generateStoreWrkFile0(Integer mark) {
    public synchronized void out(Integer mark) {
        // 根据输送线plc遍历
        for (DevpSlave devp : slaveProperties.getDevp()) {
            // 遍历入库口
@@ -100,43 +193,280 @@
                if (!staProtocol.isLoading()) {
                    continue;
                }
                if (staProtocol.isAutoing() && staProtocol.isOutEnable()
                        && !staProtocol.isEmptyMk() && (staProtocol.getWorkNo() == 0 || staProtocol.getWorkNo() == 9999)
                        && staProtocol.isPakMk()) {
                //&& staProtocol.isOutEnable()
                if (staProtocol.isAutoing() && !staProtocol.isEmptyMk() && (staProtocol.getWorkNo() == 0 || staProtocol.getWorkNo() == 9999) && staProtocol.isPakMk()) {
                    News.warnNoLog("" + mark + " - 0" + " - 开始执行");
                    // 判断重复工作档
                    WrkMast wrkMast = wrkMastService.selectOne(new EntityWrapper<WrkMast>().eq("source_sta_no", staProtocol.getSiteId()).eq("wrk_sts", 105));
                    if (wrkMast == null) {
                        continue;
                    }
                    // 106也算上,以后106-》107用于更新库存
//                    WrkMast wrkMast = wrkMastService.selectOne(new EntityWrapper<WrkMast>().eq("loc_no", "1001").in("wrk_sts", 106, 107));
//                    if (wrkMast == null) {
//                        continue;
//                    }
                    // 命令下发区 --------------------------------------------------------------------------
                    // 更新站点信息 且 下发plc命令
                    staProtocol.setWorkNo(wrkMast.getWrkNo());
                    staProtocol.setStaNo(wrkMast.getStaNo().shortValue());
                    staProtocol.setWorkNo((int) (Math.random() * 10000));
                    staProtocol.setStaNo((short) 1004);
                    devpThread.setPakMk(staProtocol.getSiteId(), false);
                    boolean result = MessageQueue.offer(SlaveType.Devp, devp.getId(), new Task(2, staProtocol));
                    log.info("输送线下发3:{},{}", wrkMast.getWrkNo(), wrkMast.getStaNo());
                    log.info("输送线下发3:{},{}", staProtocol.getWorkNo(), 1004);
                    if (result) {
                        // 更新工作主档
                        wrkMast.setWrkSts(106L);
                        wrkMast.setModiTime(new Date());
                        if (wrkMastMapper.updateById(wrkMast) == 0) {
                            News.error("" + mark + " - 1" + " - 更新工作档失败!!! [工作号:{}]", wrkMast.getWrkNo());
                        try {
                            Thread.sleep(8000L);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        setFlag1001(false);
                    } else {
                        News.error("" + mark + " - 2" + " - 发布命令至输送线队列失败!!! [plc编号:{}]", devp.getId());
                    }
                } else {
                    News.errorNoLog("" + mark + " - 6" + " - 站点信息不符合入库条件!!!" + " 自动信号:" + staProtocol.isLoading() + "、可入信号:" + staProtocol.isInEnable()
                            + "、空板信号:" + staProtocol.isEmptyMk() + "、工作号:" + staProtocol.getWorkNo()
                            + "、锁定标记" + staProtocol.isPakMk() + "、入库印记:" + staProtocol.getStamp());
                    News.errorNoLog("" + mark + " - 6" + " - 站点信息不符合入库条件!!!" + " 自动信号:" + staProtocol.isLoading() + "、可入信号:" + staProtocol.isInEnable() + "、空板信号:" + staProtocol.isEmptyMk() + "、工作号:" + staProtocol.getWorkNo() + "、锁定标记" + staProtocol.isPakMk() + "、入库印记:" + staProtocol.getStamp());
                }
            }
        }
    }
    public static final ArrayList<Integer> staNos1 = new ArrayList<Integer>() {{
        add(1001);
        add(1002);
        add(1003);
        add(1004);
        add(1005);
        add(1006);
        add(1007);
    }};
    public static final ArrayList<Integer> staNos2 = new ArrayList<Integer>() {{
        add(101);
        add(102);
        add(103);
        add(104);
        add(105);
        add(106);
        add(107);
        add(108);
    }};
    public synchronized void in(Integer mark) {
        // 遍历入库口
        for (Integer inSta : staNos2) {
            // 获取入库站信息
            SiemensDevpThread devpThread = (SiemensDevpThread) SlaveConnection.get(SlaveType.Devp, 1);
            StaProtocol staProtocol = devpThread.getStation().get(inSta);
            if (staProtocol == null) {
                continue;
            } else {
                staProtocol = staProtocol.clone();
            }
            // 判断是否满足条件
            if (!staProtocol.isAutoing() && !staProtocol.isLoading()) {
                continue;
            }
            // && staProtocol.isInEnable()
            if (staProtocol.isInEnable()) {
                OpenBusSubmitParam openBusSubmitParam = new OpenBusSubmitParam();
                openBusSubmitParam.setBatch(DateUtils.convert(new Date()));
                List<TaskDto> taskList = new ArrayList<>();
                TaskDto taskDto = new TaskDto();
                Random rand = new Random();
                taskDto.setSeqNum(rand.nextInt(10000) + "");
                taskDto.setDestLoc(getFLoc(staProtocol.getSiteId() + "-2", "15"));
                taskDto.setOriSta(staProtocol.getSiteId() + "-2");
                taskDto.setPriority(123);
                taskList.add(taskDto);
                openBusSubmitParam.setTaskList(taskList);
                sendTask(openBusSubmitParam, staProtocol);
            }
            if (staProtocol.isOutEnable()) {
                OpenBusSubmitParam openBusSubmitParam = new OpenBusSubmitParam();
                openBusSubmitParam.setBatch(DateUtils.convert(new Date()));
                List<TaskDto> taskList = new ArrayList<>();
                TaskDto taskDto = new TaskDto();
                Random rand = new Random();
                taskDto.setSeqNum(rand.nextInt(10000) + "");
                taskDto.setDestLoc(getFLoc(staProtocol.getSiteId() + "-3", "15"));
                taskDto.setOriSta(staProtocol.getSiteId() + "-3");
                taskDto.setPriority(123);
                taskList.add(taskDto);
                openBusSubmitParam.setTaskList(taskList);
                sendTask(openBusSubmitParam, staProtocol);
            }
        }
    }
    public synchronized void autoOut(Integer mark) {
        int i = 0;
        for (Integer staNo : staNos1) {
            SiemensDevpThread devpThread = (SiemensDevpThread) SlaveConnection.get(SlaveType.Devp, 1);
            StaProtocol staProtocol = devpThread.getStation().get(staNo);
            if (staProtocol == null) {
                continue;
            } else {
                staProtocol = staProtocol.clone();
            }
            // 判断是否满足条件
            if (!staProtocol.isAutoing()) {
                continue;
            }
            if (staProtocol.isLoading()) {
                continue;
            }
            if (staProtocol.getStaNo() != 0) {
                continue;
            }
            i++;
        }
        SiemensDevpThread devpThread = (SiemensDevpThread) SlaveConnection.get(SlaveType.Devp, 1);
        StaProtocol staProtocol = devpThread.getStation().get(1001);
        if (i >= 7) {
            OpenBusSubmitParam openBusSubmitParam = new OpenBusSubmitParam();
            openBusSubmitParam.setBatch(DateUtils.convert(new Date()));
            List<TaskDto> taskList = new ArrayList<>();
            TaskDto taskDto = new TaskDto();
            Random rand = new Random();
            taskDto.setSeqNum("SSX-CK" + rand.nextInt() * 10000);
            taskDto.setOriLoc(getFLoc("1001", "16"));
            taskDto.setDestSta("1001");
            taskDto.setPriority(123);
            taskList.add(taskDto);
            openBusSubmitParam.setTaskList(taskList);
            sendTask(openBusSubmitParam, staProtocol);
        }
    }
    /**
     * 1007入库
     *
     * @param mark
     */
    public synchronized void autoIn(Integer mark) {
        SiemensDevpThread devpThread = (SiemensDevpThread) SlaveConnection.get(SlaveType.Devp, 1);
        StaProtocol staProtocol = devpThread.getStation().get(1007);
        if (staProtocol == null) {
            return;
        } else {
            staProtocol = staProtocol.clone();
        }
        // 判断是否满足条件
        if (!staProtocol.isAutoing()) {
            return;
        }
        if (!staProtocol.isLoading()) {
            return;
        }
        if (staProtocol.getStaNo() <= 0) {
            return;
        }
        OpenBusSubmitParam openBusSubmitParam = new OpenBusSubmitParam();
        openBusSubmitParam.setBatch(DateUtils.convert(new Date()));
        List<TaskDto> taskList = new ArrayList<>();
        TaskDto taskDto = new TaskDto();
        taskDto.setSeqNum("SSX-RK" + staProtocol.getWorkNo());
        taskDto.setDestLoc(getFLoc("1007", "15"));
        taskDto.setOriSta("1007");
        taskDto.setPriority(123);
        taskList.add(taskDto);
        openBusSubmitParam.setTaskList(taskList);
        sendTask(openBusSubmitParam, staProtocol);
    }
    public void updateSta(Integer mark) {
        SiemensDevpThread devpThread = (SiemensDevpThread) SlaveConnection.get(SlaveType.Devp, 1);
        StaProtocol staProtocol1 = devpThread.getStation().get(1001);
        StaProtocol staProtocol7 = devpThread.getStation().get(1007);
        if (staProtocol1 == null) {
            return;
        }
        if (staProtocol7 == null) {
            return;
        }
        updateSta("1001", staProtocol1.isLoading() ? "16" : "15");
        updateSta("1007", staProtocol7.isLoading() ? "16" : "15");
    }
    @Transactional
    public boolean sendTask(OpenBusSubmitParam openBusSubmitParam, StaProtocol staProtocol) {
        String response = "";
        try {
            response = new HttpHandler.Builder()
                    .setUri(ctuUrl)
                    .setPath(sendTask)
                    .setTimeout(1200, TimeUnit.SECONDS)
                    .setJson(JSON.toJSONString(openBusSubmitParam))
                    .build()
                    .doPost();
            JSONObject jsonObject = JSON.parseObject(response);
            if (jsonObject.getInteger("code").equals(200)) {
                log.info("下发任务返回数据:{}", response);
                return true;
            } else {
                log.error("请求接口失败!!!url:{};request:{};response:{}", ctuUrl + sendTask, JSON.toJSONString(openBusSubmitParam), response);
                throw new CoolException("调用下发任务接口报错");
            }
        } catch (Exception e) {
            //log.error("fail", e);
        }
        return false;
    }
    @Transactional
    public void updateSta(String staNo, String sts) {
        Map<String, String> data = new HashMap<String, String>();
        data.put("staNo", staNo);
        data.put("sts", sts);
        String response = "";
        try {
            response = new HttpHandler.Builder()
                    .setUri(ctuUrl)
                    .setPath(updateSta)
                    .setTimeout(1200, TimeUnit.SECONDS)
                    .setJson(JSON.toJSONString(data))
                    .build()
                    .doPost();
            JSONObject jsonObject = JSON.parseObject(response);
            if (jsonObject.getInteger("code").equals(200)) {
                //log.info("下发任务返回数据:{}", response);
            } else {
                //log.error("请求接口失败!!!url:{};request:{};response:{}", ctuUrl + sendTask, JSON.toJSONString(data), response);
                //throw new CoolException("调用下发任务接口报错");
            }
        } catch (Exception e) {
            log.error("fail", e);
        }
    }
    @Transactional
    public String getFLoc(String staNo, String sts) {
        Map<String, String> data = new HashMap<String, String>();
        data.put("staNo", staNo);
        data.put("sts", sts);
        String response = "";
        try {
            response = new HttpHandler.Builder()
                    .setUri(ctuUrl)
                    .setPath(getLoc)
                    .setTimeout(1200, TimeUnit.SECONDS)
                    .setJson(JSON.toJSONString(data))
                    .build()
                    .doPost();
            JSONObject jsonObject = JSON.parseObject(response);
            if (jsonObject.getInteger("code").equals(200)) {
                //log.info("下发任务返回数据:{}", response);
                JSONObject loc = JSON.parseObject(jsonObject.getString("data"));
                return loc.getString("locNo");
            } else {
                log.error("请求接口失败!!!url:{};request:{};response:{}", ctuUrl + sendTask, JSON.toJSONString(data), response);
                throw new CoolException("调用下发任务接口报错");
            }
        } catch (Exception e) {
            log.error("fail", e);
        }
        return null;
    }
}