JiuMuMesParent/moduleService/DeviceInteractionModule/src/main/java/com/mes/job/MachineTask.java
@@ -1,29 +1,27 @@
package com.mes.job;
import cn.hutool.json.JSONObject;
import com.github.xingshuangs.iot.protocol.s7.enums.EPlcType;
import com.mes.common.S7objectFlipSlice;
import com.mes.common.S7objectMachine;
import com.mes.common.S7objectMarking;
import com.mes.device.PlcParameterInfo;
import com.mes.device.PlcParameterObject;
import com.mes.md.entity.Machine;
import com.mes.md.entity.Tasking;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.mes.md.entity.*;
import com.mes.md.mapper.GlassInfoMapper;
import com.mes.md.mapper.MachineMapper;
import com.mes.md.mapper.TaskingMapper;
import com.mes.md.service.TaskingService;
import com.mes.tools.WebSocketServer;
import com.mes.md.service.*;
import com.mes.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * 自动打标机
 *
 * @Author : yanzhxiin
 * @Date: 2024/8/20 11:19
 * @Description:
@@ -41,128 +39,287 @@
    @Autowired
    TaskingService taskingService;
    @Autowired
    ProjectService projectService;
    @Autowired
    PrimitiveTaskService primitiveTaskService;
    @Autowired
    KBBTJPDrawingBPService kBBTJPDrawingBPService;
    @Autowired
    LineConfigurationService lineConfigurationService;
    @Resource
    WebSocketServer webSocketServer;
    @Autowired
    private GlassInfoMapper glassInfoMapper;
    public int a =1;
    public S7objectMachine s7objectMachine;
    public List<Map> sendRecords = new ArrayList<>();
    private List<Machine> machineListLoad;
    private List<Machine> machineListEdging;
    private List<Machine> machineListFlipSlice;
    private List<Machine> machineListMarking;
    private List<Machine> machineListSilkScreen;
    private List<Machine> machineListRotate;
    private List<Machine> machineListGlueDispenser;
    private List<Machine> machineListScanQrCode;
    private List<Machine> machineListLamination;
    //@Scheduled(fixedDelay = 1000)
    public void plcMachineTask() {
        Long machineId=12L;
        Machine machine=machineMapper.selectById(machineId);
        if (s7objectMachine==null){
            s7objectMachine=new S7objectMachine(machine.getIp(),machine.getPort(),"PlcMarking", EPlcType.S1500);
            s7objectMachine.start();
        }
        PlcParameterObject plcParameterObject = s7objectMachine.PlcMesObject;
        PlcParameterInfo plcRequest =plcParameterObject.getPlcParameter("plcRequest");//请求字
        PlcParameterInfo plcRequestID =plcParameterObject.getPlcParameter("plcRequestID");//请求ID
        PlcParameterInfo mesSend =plcParameterObject.getPlcParameter("mesSend");//发送字
        PlcParameterInfo isMark =plcParameterObject.getPlcParameter("isMark");//发送ID【0 不打标,1标准模式,2定制模式】
        PlcParameterInfo drawingMark =plcParameterObject.getPlcParameter("drawingMark");//打标图纸地址
        PlcParameterInfo lengthOutOfService =plcParameterObject.getPlcParameter("length(OutOfService)");//长
        PlcParameterInfo widthOutOfService =plcParameterObject.getPlcParameter("width(OutOfService)");//宽
        PlcParameterInfo markingMode =plcParameterObject.getPlcParameter("markingMode");//
        PlcParameterInfo plcReport =plcParameterObject.getPlcParameter("plcReport");//汇报字
        PlcParameterInfo plcReportID =plcParameterObject.getPlcParameter("plcReportID");//汇报ID
        PlcParameterInfo mesConfirm =plcParameterObject.getPlcParameter("mesConfirm");//确认字
        PlcParameterInfo mesConfirmID =plcParameterObject.getPlcParameter("mesConfirmID");//确认ID
        String str=S7objectMarking.getinstance().plccontrol.readString("DB14.30");
        //String width=S7objectMarking.getinstance().plccontrol.readWord(widthOutOfService.getAddress());
        log.info("plcRequest:{},plcRequestID:{},mesSend:{},mesSendID:{},drawingMark:{}," +
                        "plcReport:{},plcReportID:{},mesConfirm:{},mesConfirmID:{}"
                ,plcRequest.getValue(),plcRequestID.getValue(),mesSend.getValue(),isMark.getValue(),drawingMark.getValue(),
                plcReport.getValue(),plcReportID.getValue(),mesConfirm.getValue(),mesConfirmID.getValue());
        if ("0".equals(plcRequest.getValue())&&"1".equals(mesSend.getValue())) {
            //发送字置0
            log.info("1.发送字置零,清除上次发送的数据{},{},{},{},{}"
                    ,markingMode.getValue()
                    ,isMark.getValue()
                    ,lengthOutOfService.getValue()
                    ,widthOutOfService.getValue()
                    ,mesSend.getValue());
            //S7objectMarking.getinstance().plccontrol.writeString(drawingMark.getAddress(),"");
            S7objectMarking.getinstance().plccontrol.writeWord(markingMode.getAddress(), 0);
            S7objectMarking.getinstance().plccontrol.writeWord(lengthOutOfService.getAddress(), 0);
            S7objectMarking.getinstance().plccontrol.writeWord(widthOutOfService.getAddress(), 0);
            S7objectMarking.getinstance().plccontrol.writeWord(isMark.getAddress(), 0);
            S7objectMarking.getinstance().plccontrol.writeWord(mesSend.getAddress(), 0);
            return;
        }
        if ("0".equals(plcReport.getValue())&&"1".equals(mesConfirm.getValue())) {
            log.info("2.确认字置零");
            //发送字置0
            S7objectMarking.getinstance().plccontrol.writeWord(mesConfirm.getAddress(), 0);
            return;
        }
        if("1".equals(plcReport.getValue())&&"0".equals(mesConfirm.getValue())){
            int finishCount=taskingService.finishMachineTask(machine);
            log.info("3、任务完成");
            if(finishCount>0){//有任务
                S7objectMarking.getinstance().plccontrol.writeWord(mesConfirm.getAddress(), 1);
                return;
    //机械手
    //@Scheduled(fixedDelay = 500)
    public void loadTasks() {
        try {
            machineListLoad = machineMapper.selectList(new QueryWrapper<Machine>().lambda().eq(Machine::getName, "上片"));
            JSONObject jsonObject = new JSONObject();
            jsonObject.append("sessionMapName", "loadTask");
            for (Machine machine : machineListLoad) {
                JSONObject jsonObjectItem = new JSONObject();
                //标准模式  找已领取未完成的第一条任务
                LineConfiguration lineConfiguration = lineConfigurationService.machineLineConfiguration(machine);
                //此线路已领取的任务
                List<PrimitiveTask> findPrimitiveTasking = primitiveTaskService.findPrimitiveTasking(machine, lineConfiguration.getLineId());
                //此线路未领取的任务  本地
                //List<PrimitiveTask> findPrimitiveTask=primitiveTaskService.findPrimitiveTaskNotFinish();
                //此线路未领取的任务  客户数据库
                List<KBBTJPDrawingBP> list = kBBTJPDrawingBPService.notReceiveKBBTJPDrawingBP();
                jsonObjectItem.append("findPrimitiveTask", list);
                jsonObjectItem.append("findPrimitiveTasking", findPrimitiveTasking);
                //jsonObject.append("findPrimitiveTask", findPrimitiveTask);
                jsonObjectItem.append("machine", machine);
                jsonObjectItem.append("sendRecords", sendRecords);
                jsonObject.append(machine.getId().toString(), jsonObjectItem);
            }
            this.webSocketServer(jsonObject);
        } catch (Exception exception) {
            log.info("MarkingTasks:{}", exception.getMessage());
        }
        if("1".equals(plcRequest.getValue())&&"0".equals(mesSend.getValue())&& !plcRequestID.getValue().isEmpty()&&"开工".equals(machine.getState())){
            Tasking tasking;
            if("0".equals(plcRequestID.getValue())){
                //标准模式
                tasking=taskingService.startMachineTask(machine);
            }else{
                //定制模式
                tasking=taskingService.startMachineTask(machine,plcRequestID.getValue());
    }
    //磨边机
    //@Scheduled(fixedDelay = 500)
    public void edgingTasks() {
        try {
            machineListEdging = machineMapper.selectList(new QueryWrapper<Machine>().lambda().eq(Machine::getName, "磨边"));
            JSONObject jsonObject = new JSONObject();
            jsonObject.append("sessionMapName", "edgingTask");
            for (Machine machine : machineListEdging) {
                JSONObject jsonObjectItem = new JSONObject();
                List<Tasking> taskingList = taskingService.findMachineTask(machine);
                jsonObjectItem.append("taskingList", taskingList);
                jsonObjectItem.append("machine", machine);
                jsonObjectItem.append("sendRecords", sendRecords);
                jsonObject.append(machine.getId().toString(), jsonObjectItem);
            }
            //log.info("4、发送任务  设备状态:{},  数据:{},",machine,tasking);
            if(tasking!=null){
                //模式:1定制  0 批量      是否打标:0不打标   1打标
                int isMark_=tasking.getDrawingMarking()==null?0:1;
                int isMarkingMode_="定制".equals(tasking.getTaskType()) ?1:0;
                log.info("4、发送数据:{},{},{},{},{},{}"
                        ,tasking.getProgramId()
                        ,tasking.getLength().intValue(),tasking.getWidth().intValue(),isMark_,isMarkingMode_,1);
                if(isMark_==1){
                    S7objectMarking.getinstance().plccontrol.writeString(drawingMark.getAddress(), tasking.getProgramId());
                }
                //S7objectMarking.getinstance().plccontrol.writeUInt32 (mesSendID.getAddress(), 2);
                S7objectMarking.getinstance().plccontrol.writeWord(lengthOutOfService.getAddress(), tasking.getLength().intValue());
                S7objectMarking.getinstance().plccontrol.writeWord(widthOutOfService.getAddress(), tasking.getWidth().intValue());
                S7objectMarking.getinstance().plccontrol.writeWord(isMark.getAddress(), isMark_);
                S7objectMarking.getinstance().plccontrol.writeWord(markingMode.getAddress(), isMarkingMode_);
                S7objectMarking.getinstance().plccontrol.writeWord(mesSend.getAddress(), 1);
                return;
            }
            this.webSocketServer(jsonObject);
        } catch (Exception exception) {
            log.info("edgingTasks:{}", exception.getMessage());
        }
        //log.info("无可执行的条件");
    }
    //翻片台
    //@Scheduled(fixedDelay = 500)
    public void flipSliceTasks() {
        try {
            machineListFlipSlice = machineMapper.selectList(new QueryWrapper<Machine>().lambda().eq(Machine::getName, "翻片"));
            JSONObject jsonObject = new JSONObject();
            jsonObject.append("sessionMapName", "flipSlice");
            for (Machine machine : machineListFlipSlice) {
                JSONObject jsonObjectItem = new JSONObject();
                List<Tasking> taskingList = taskingService.findMachineTask(machine);
                jsonObjectItem.append("taskingList", taskingList);
                jsonObjectItem.append("machine", machine);
                jsonObjectItem.append("sendRecords", sendRecords);
                jsonObject.append(machine.getId().toString(), jsonObjectItem);
            }
            this.webSocketServer(jsonObject);
        } catch (Exception exception) {
            log.info("flipSliceTasks:{}", exception.getMessage());
        }
    }
    //@Scheduled(fixedDelay = 1000)
    //打标机
    //@Scheduled(fixedDelay = 500)
    public void markingTasks() {
        JSONObject jsonObject = new JSONObject();
        Machine machine=machineMapper.selectById(11L);
        List<Tasking> taskingList=taskingService.findMachineTask(machine);
        jsonObject.append("taskingList", taskingList);
        jsonObject.append("machine", machine);
        ArrayList<WebSocketServer> sendwServer = WebSocketServer.sessionMap.get("marking");
        if (sendwServer != null) {
            for (WebSocketServer webserver : sendwServer) {
                if (webserver != null) {
                    try {
                        webserver.sendMessage(jsonObject.toString());
                        List<String> messages = webserver.getMessages();
                        if (!messages.isEmpty()) {
                            // // 将最后一个消息转换为整数类型的列表
                            webserver.clearMessages();
                        }
                    }catch (Exception e) {
        try {
            machineListMarking = machineMapper.selectList(new QueryWrapper<Machine>().lambda().eq(Machine::getName, "自动打标机"));
                    }
                } else {
                    log.info("Home is closed");
                }
            JSONObject jsonObject = new JSONObject();
            jsonObject.append("sessionMapName", "marking");
            for (Machine machine : machineListMarking) {
                JSONObject jsonObjectItem = new JSONObject();
                List<Tasking> taskingList = taskingService.findMachineTask(machine);
                jsonObjectItem.append("taskingList", taskingList);
                jsonObjectItem.append("machine", machine);
                jsonObjectItem.append("sendRecords", sendRecords);
                jsonObject.append(machine.getId().toString(), jsonObjectItem);
            }
            this.webSocketServer(jsonObject);
        } catch (Exception exception) {
            log.info("markingTasks:{}", exception.getMessage());
        }
    }
    //丝印机
    //@Scheduled(fixedDelay = 500)
    public void silkScreenTasks() {
        try {
            machineListSilkScreen = machineMapper.selectList(new QueryWrapper<Machine>().lambda().eq(Machine::getName, "自动丝印机"));
            JSONObject jsonObject = new JSONObject();
            jsonObject.append("sessionMapName", "silkScreenTask");
            for (Machine machine : machineListSilkScreen) {
                JSONObject jsonObjectItem = new JSONObject();
                List<Tasking> taskingList = taskingService.findMachineTask(machine);
                jsonObjectItem.append("taskingList", taskingList);
                jsonObjectItem.append("machine", machine);
                jsonObjectItem.append("sendRecords", sendRecords);
                jsonObject.append(machine.getId().toString(), jsonObjectItem);
            }
            this.webSocketServer(jsonObject);
        } catch (Exception exception) {
            log.info("silkScreenTasks:{}", exception.getMessage());
        }
    }
    //点胶机
    //@Scheduled(fixedDelay = 500)
    public void glueDispenserTasks() {
        try {
            machineListGlueDispenser = machineMapper.selectList(new QueryWrapper<Machine>().lambda().eq(Machine::getName, "自动点胶机"));
            JSONObject jsonObject = new JSONObject();
            jsonObject.append("sessionMapName", "glueDispenser");
            for (Machine machine : machineListGlueDispenser) {
                JSONObject jsonObjectItem = new JSONObject();
                List<Tasking> taskingList = taskingService.findMachineTask(machine);
                jsonObjectItem.append("taskingList", taskingList);
                jsonObjectItem.append("machine", machine);
                jsonObjectItem.append("sendRecords", sendRecords);
                jsonObject.append(machine.getId().toString(), jsonObjectItem);
            }
            this.webSocketServer(jsonObject);
        } catch (Exception exception) {
            log.info("glueDispenserTasks:{}", exception.getMessage());
        }
    }
    //旋转台
    //@Scheduled(fixedDelay = 500)
    public void rotateTasks() {
        try {
            machineListRotate = machineMapper.selectList(new QueryWrapper<Machine>().lambda().eq(Machine::getName, "旋转台"));
            JSONObject jsonObject = new JSONObject();
            jsonObject.append("sessionMapName", "rotate");
            for (Machine machine : machineListRotate) {
                JSONObject jsonObjectItem = new JSONObject();
                List<Tasking> taskingList = taskingService.findMachineTask(machine);
                jsonObjectItem.append("taskingList", taskingList);
                jsonObjectItem.append("machine", machine);
                jsonObjectItem.append("sendRecords", sendRecords);
                jsonObject.append(machine.getId().toString(), jsonObjectItem);
            }
            this.webSocketServer(jsonObject);
        } catch (Exception exception) {
            log.info("rotateTasks:{}", exception.getMessage());
        }
    }
    //贴膜机
    //@Scheduled(fixedDelay = 500)
    public void laminationTasks() {
        try {
            machineListLamination = machineMapper.selectList(new QueryWrapper<Machine>().lambda().eq(Machine::getName, "自动贴膜机"));
            JSONObject jsonObject = new JSONObject();
            jsonObject.append("sessionMapName", "lamination");
            for (Machine machine : machineListLamination) {
                JSONObject jsonObjectItem = new JSONObject();
                List<Tasking> taskingList = taskingService.findMachineTask(machine);
                jsonObjectItem.append("taskingList", taskingList);
                jsonObjectItem.append("machine", machine);
                jsonObjectItem.append("sendRecords", sendRecords);
                jsonObject.append(machine.getId().toString(), jsonObjectItem);
            }
            this.webSocketServer(jsonObject);
        } catch (Exception exception) {
            log.info("laminationTasks:{}", exception.getMessage());
        }
    }
    //报工页面查询
    //@Scheduled(fixedDelay = 1000)
    public void manualReporting() {
        try {
            machineListScanQrCode = machineMapper.selectList(new QueryWrapper<Machine>().lambda().eq(Machine::getName, "识别报工"));
            JSONObject jsonObject = new JSONObject();
            jsonObject.append("sessionMapName", "manualReporting");
            for (Machine machine : machineListScanQrCode) {
                JSONObject jsonObjectItem = new JSONObject();
                List<Tasking> taskingList = taskingMapper.selectJoinList(Tasking.class, new MPJLambdaWrapper<Tasking>()
                        .selectAll(Tasking.class)
                        .innerJoin(LineConfiguration.class, LineConfiguration::getId, Tasking::getLineConfigurationId)
                        .innerJoin(Machine.class, Machine::getId, LineConfiguration::getMachineId)
                        .eq(LineConfiguration::getMachineId, machine.getId())
                        .eq(Tasking::getGlassState, "正常")
                        .eq(Tasking::getState, "线上")
                        .ne(Tasking::getWorkState, "完工")
                        .orderByDesc(Tasking::getOperationRecordTime));
                jsonObjectItem.append("taskingList", taskingList);
                jsonObjectItem.append("machine", machine);
                jsonObject.append(machine.getId().toString(), jsonObjectItem);
            }
            this.webSocketServer(jsonObject);
        } catch (Exception exception) {
            log.info("manualReporting:{}", exception.getMessage());
        }
    }
    //线下玻璃查询
    //@Scheduled(fixedDelay = 1000)
    public void downLineTask() {
        try {
            JSONObject jsonObject = new JSONObject();
            List<Tasking> downLineTask = taskingService.findDownLineTask();
            jsonObject.append("sessionMapName", "downLineTask");
            jsonObject.append("downLineTask", downLineTask);
            this.webSocketServer(jsonObject);
        } catch (Exception exception) {
            log.info("downLineTask:{}", exception.getMessage());
        }
    }
    public void webSocketServer(JSONObject jsonObject) {
        try {
            log.info("发送数据:{}", jsonObject.getJSONArray("sessionMapName").get(0).toString());
            String sessionMapName = jsonObject.getJSONArray("sessionMapName").get(0).toString();
            webSocketServer.sendToWeb(sessionMapName, jsonObject.toString());
        } catch (Exception ex) {
            log.info("{}发送数据失败:{}", "rawGlassStorage", ex.getMessage());
        }
    }
//    public void webSocketServer(JSONObject jsonObject) {
//        try {
//            String sessionMapName=jsonObject.getJSONArray("sessionMapName").get(0).toString();
//            ArrayList<WebSocketServer> sendwServer = WebSocketServer.sessionMap.get(sessionMapName);
//            if (sendwServer != null) {
//                for (WebSocketServer webserver : sendwServer) {
//                    try {
//                        webserver.sendMessage(jsonObject.toString());
//                        List<String> messages = webserver.getMessages();
//                        if (!messages.isEmpty()) {
//                            // // 将最后一个消息转换为整数类型的列表
//                            webserver.clearMessages();
//                        }
//                    }catch (Exception e) {
//                        if (webserver != null) {
//
//                        } else {
//                            log.info("Home is closed");
//                        }
//                    }
//
//                }
//            }
//        }catch (Exception e) {
//
//        }
//
//    }
}