| package com.zy.core.thread; | 
|   | 
| import HslCommunication.Core.Types.OperateResult; | 
| import HslCommunication.Core.Types.OperateResultExOne; | 
| import HslCommunication.Profinet.Siemens.SiemensPLCS; | 
| import HslCommunication.Profinet.Siemens.SiemensS7Net; | 
| import com.alibaba.fastjson.JSON; | 
| import com.core.common.Cools; | 
| import com.core.common.DateUtils; | 
| import com.core.common.SpringUtils; | 
| import com.zy.asrs.entity.BasDevp; | 
| import com.zy.asrs.entity.CommandInfo; | 
| import com.zy.asrs.service.BasDevpService; | 
| import com.zy.asrs.service.CommandInfoService; | 
| import com.zy.asrs.service.DeviceErrorService; | 
| import com.zy.core.DevpThread; | 
| import com.zy.core.cache.MessageQueue; | 
| import com.zy.core.cache.OutputQueue; | 
| import com.zy.core.cache.SlaveConnection; | 
| import com.zy.core.enums.IoModeType; | 
| import com.zy.core.enums.SlaveType; | 
| import com.zy.core.model.DevpSlave; | 
| import com.zy.core.model.Task; | 
| import com.zy.core.model.protocol.StaProtocol; | 
| import lombok.Data; | 
| import lombok.extern.slf4j.Slf4j; | 
|   | 
| import java.text.MessageFormat; | 
| import java.util.ArrayList; | 
| import java.util.Date; | 
| import java.util.List; | 
| import java.util.Map; | 
| import java.util.concurrent.ConcurrentHashMap; | 
|   | 
| /** | 
|  * 输送线线程 | 
|  * Created by vincent on 2020/8/4 | 
|  */ | 
| @Data | 
| @Slf4j | 
| public class SiemensDevpThread implements Runnable, DevpThread { | 
|   | 
|     private DevpSlave slave; | 
|     private SiemensS7Net siemensS7Net; | 
|     private Map<Integer, StaProtocol> station = new ConcurrentHashMap<>(); | 
|     private short heartBeatVal = 1; | 
|     public static final ArrayList<Integer> staNos = new ArrayList<Integer>() {{ | 
|         add(101);add(102);add(103);add(104);add(105);add(106);add(107);add(108);add(109);add(110);add(111);add(112); | 
|         add(201);add(202);add(203);add(204);add(205);add(206);add(207);add(208);add(209);add(210);add(211);add(212); | 
|     }}; | 
|   | 
|     /** | 
|      * 条码数量 | 
|      */ | 
|     private int barcodeSize = 3; | 
|   | 
|     /** | 
|      * 入出库模式 | 
|      * 0:未知 | 
|      * 1:入库启动中 | 
|      * 2.入库模式 | 
|      * 3.出库启动中 (不能生成入库工作档) | 
|      * 4.出库模式 | 
|      */ | 
|     public IoModeType ioModeOf2F = IoModeType.NONE; | 
| //    public IoModeType ioMode = IoModeType.NONE; | 
|   | 
|     public SiemensDevpThread(DevpSlave slave) { | 
|         this.slave = slave; | 
|     } | 
|   | 
|     @Override | 
|     @SuppressWarnings("InfiniteLoopStatement") | 
|     public void run() { | 
|         connect(); | 
|         while (true) { | 
|             try { | 
|                 int step = 1; | 
|                 Task task = MessageQueue.poll(SlaveType.Devp, slave.getId()); | 
|                 if (task != null) { | 
|                     step = task.getStep(); | 
|                 } | 
|                 switch (step) { | 
|                     // 读数据 | 
|                     case 1: | 
|                         read(); | 
|                         break; | 
|                     // 写数据 ID+目标站 | 
|                     case 2: | 
|                         write((StaProtocol)task.getData()); | 
|                         break; | 
|                     default: | 
|                         break; | 
|                 } | 
|                 // 心跳 | 
| //                heartbeat(); | 
|                 Thread.sleep(400); | 
|             } catch (Exception e) { | 
|                 e.printStackTrace(); | 
|             } | 
|   | 
|         } | 
|     } | 
|   | 
|     @Override | 
|     public boolean connect() { | 
|         boolean result = false; | 
|         siemensS7Net = new SiemensS7Net(SiemensPLCS.S1200, slave.getIp()); | 
|         siemensS7Net.setRack(slave.getRack().byteValue()); | 
|         siemensS7Net.setSlot(slave.getSlot().byteValue()); | 
|         OperateResult connect = siemensS7Net.ConnectServer(); | 
|         if(connect.IsSuccess){ | 
|             result = true; | 
|             OutputQueue.DEVP.offer(MessageFormat.format( "【{0}】输送线plc连接成功 ===>> [id:{1}] [ip:{2}] [port:{3}] [rack:{4}] [slot:{5}]", DateUtils.convert(new Date()), slave.getId(), slave.getIp(), slave.getPort(), slave.getRack(), slave.getSlot())); | 
|             log.info("输送线plc连接成功 ===>> [id:{}] [ip:{}] [port:{}]", slave.getId(), slave.getIp(), slave.getPort()); | 
|         } else { | 
|             OutputQueue.DEVP.offer(MessageFormat.format( "【{0}】输送线plc连接失败!!! ===>> [id:{1}] [ip:{2}] [port:{3}]  [rack:{4}] [slot:{5}]", DateUtils.convert(new Date()), slave.getId(), slave.getIp(), slave.getPort(), slave.getRack(), slave.getSlot())); | 
|             log.error("输送线plc连接失败!!! ===>> [id:{}] [ip:{}] [port:{}]", slave.getId(), slave.getIp(), slave.getPort()); | 
|             DeviceErrorService deviceErrorService = SpringUtils.getBean(DeviceErrorService.class); | 
|             deviceErrorService.addDeviceError("devp", slave.getId(), "输送线plc连接失败"); | 
|         } | 
|         siemensS7Net.ConnectClose(); | 
|         return result; | 
|     } | 
|   | 
|     /** | 
|      * 读取状态 ====> 整块plc | 
|      */ | 
|     private void read() throws InterruptedException { | 
| //        // 更新入出库模式 | 
| //        updateIoMode(); | 
|         int staNoSize = staNos.size(); | 
|         OperateResultExOne<byte[]> result = siemensS7Net.Read("DB100.0", (short) (staNoSize*4)); | 
|         if (result.IsSuccess) { | 
|             for (int i = 0; i < staNoSize; i++) { | 
|                 Integer siteId = staNos.get(i); // 站点编号 | 
|                 StaProtocol staProtocol = station.get(siteId); | 
|                 if (null == staProtocol) { | 
|                     staProtocol = new StaProtocol(); | 
|                     staProtocol.setSiteId(siteId); | 
|                     station.put(siteId, staProtocol); | 
|                 } | 
|                 staProtocol.setWorkNo(siemensS7Net.getByteTransform().TransInt16(result.Content, i*4));     // 工作号 | 
|   | 
|                 staProtocol.setStaNo(siemensS7Net.getByteTransform().TransInt16(result.Content, i*4 + 2));   // 目标站 | 
|             } | 
|         } | 
|   | 
|         Thread.sleep(200); | 
|         OperateResultExOne<byte[]> result1 = siemensS7Net.Read("DB100.100", (short) (staNoSize*2)); | 
|         if (result1.IsSuccess) { | 
|             for (int i = 0; i < staNoSize; i++) { | 
|                 Integer siteId = staNos.get(i); // 站点编号 | 
|                 boolean[] status = siemensS7Net.getByteTransform().TransBool(result1.Content, i*2, 1); | 
|                 StaProtocol staProtocol = station.get(siteId); | 
|                 staProtocol.setAutoing(status[0]);  // 自动 | 
|                 staProtocol.setLoading(status[1]);  // 有物 | 
|                 staProtocol.setInEnable(status[2]); // 可入 | 
|                 staProtocol.setOutEnable(status[3]);// 可出 | 
|                 staProtocol.setEmptyMk(status[4]);  // 空板信号 | 
|                 staProtocol.setFullPlt(status[5]);  // 满托盘 | 
|                 staProtocol.setHigh(status[6]);     // 高库位 | 
|                 staProtocol.setLow(status[7]);      // 低库位 | 
|   | 
|                 if (!staProtocol.isPakMk() && !staProtocol.isLoading()) { | 
|                     staProtocol.setPakMk(true); | 
|                 } | 
|             } | 
|         } | 
|   | 
| //            //条码 | 
| //            Thread.sleep(200); | 
| //            OperateResultExOne<byte[]> result2 = siemensS7Net.Read("DB100.160",(short)4); | 
| //            if (result2.IsSuccess) { | 
| //                for (int i = 0; i < barcodeSize; i++) { | 
| //                    String barcode = siemensS7Net.getByteTransform().TransString(result2.Content,i*8,8, "UTF-8"); | 
| //                    BarcodeThread barcodeThread = (BarcodeThread) SlaveConnection.get(SlaveType.Barcode, i + 1); | 
| //                    if(!Cools.isEmpty(barcodeThread) && !barcodeThread.getBarcode().equals(barcode)) { | 
| //                        barcodeThread.setBarcode(barcode); | 
| //                    } | 
| //                } | 
| // | 
| //            } | 
|   | 
|         //RGV台车位置 | 
|         Thread.sleep(200); | 
|         OperateResultExOne<byte[]> result3 = siemensS7Net.Read("DB100.160",(short)4); | 
|         if (result3.IsSuccess) { | 
|             for (int i = 0; i < 2; i++) { | 
|                 Integer siteId = i==0 ? 112 : 212; // 站点编号 | 
|                 StaProtocol staProtocol = station.get(siteId); | 
|                 if (null == staProtocol) { | 
|                     staProtocol = new StaProtocol(); | 
|                     staProtocol.setSiteId(siteId); | 
|                     station.put(siteId, staProtocol); | 
|                 } | 
|                 staProtocol.setNearbySta(String.valueOf(siemensS7Net.getByteTransform().TransInt16(result3.Content, i*2))); | 
| //                String aa = staProtocol.getNearbySta(); | 
| //                System.out.println(siteId + "===>>" + staProtocol.getNearbySta()); | 
|             } | 
|         } | 
|   | 
| //        OperateResultExOne<Short> result2 = siemensS7Net.ReadInt16("DB200.0"); | 
| //        if (result2.IsSuccess) { | 
| //            this.ioMode = IoModeType.get(result2.Content); | 
| //        } | 
|   | 
|         if (result.IsSuccess && result1.IsSuccess) { | 
|   | 
|             OutputQueue.DEVP.offer(MessageFormat.format("【{0}】[id:{1}] <<<<< 实时数据更新成功",DateUtils.convert(new Date()), slave.getId())); | 
|   | 
|             // 根据实时信息更新数据库 | 
|             try { | 
|                 List<BasDevp> basDevps = new ArrayList<>(); | 
|                 for (Integer siteId : staNos) { | 
|                     StaProtocol staProtocol = station.get(siteId); | 
|                     basDevps.add(staProtocol.toSqlModel()); | 
|                 } | 
|   | 
|                 BasDevpService basDevpService = SpringUtils.getBean(BasDevpService.class); | 
|                 if (null != basDevpService && !basDevpService.updateBatchById(basDevps)) { | 
|                     throw new Exception("更新数据库数据失败"); | 
|                 } | 
|             } catch (Exception e) { | 
|                 e.printStackTrace(); | 
|                 OutputQueue.DEVP.offer(MessageFormat.format("【{0}】更新数据库数据失败 ===>> [id:{1}] [ip:{2}] [port:{3}] [rack:{4}] [slot:{5}]", DateUtils.convert(new Date()), slave.getId(), slave.getIp(), slave.getPort(), slave.getRack(), slave.getSlot())); | 
|                 log.error("更新数据库数据失败 ===>> [id:{}] [ip:{}] [port:{}] [rack:{}] [slot:{}]", slave.getId(), slave.getIp(), slave.getPort(), slave.getRack(), slave.getSlot()); | 
|             } | 
|   | 
|             DeviceErrorService deviceErrorService = SpringUtils.getBean(DeviceErrorService.class); | 
|             deviceErrorService.deleteDeviceError("devp", slave.getId()); | 
|         } else { | 
|             OutputQueue.DEVP.offer(MessageFormat.format("【{0}】读取输送线plc状态信息失败 ===>> [id:{1}] [ip:{2}] [port:{3}] [rack:{4}] [slot:{5}]", DateUtils.convert(new Date()), slave.getId(), slave.getIp(), slave.getPort(), slave.getRack(), slave.getSlot())); | 
| //            log.error("读取输送线plc状态信息失败 ===>> [id:{}] [ip:{}] [port:{}] [rack:{}] [slot:{}]", slave.getId(), slave.getIp(), slave.getPort(), slave.getRack(), slave.getSlot()); | 
|             DeviceErrorService deviceErrorService = SpringUtils.getBean(DeviceErrorService.class); | 
|             deviceErrorService.addDeviceError("devp", slave.getId(), "读取输送线plc状态信息失败"); | 
|         } | 
|     } | 
|   | 
|     /** | 
|      * 写入 ID+目标站 =====> 单站点写入 | 
|      */ | 
|     private void write(StaProtocol staProtocol) throws InterruptedException { | 
|         if (null == staProtocol) { | 
|             return; | 
|         } | 
|         int index = staNos.indexOf(staProtocol.getSiteId()); | 
|         short[] array = new short[2]; | 
|         array[0] = staProtocol.getWorkNo(); | 
|         array[1] = staProtocol.getStaNo(); | 
| //        OperateResult write = siemensS7Net.Write("DB100." + index*4, array); | 
|   | 
|         CommandInfoService commandInfoService = SpringUtils.getBean(CommandInfoService.class); | 
|         CommandInfo commandInfo = new CommandInfo(); | 
|         commandInfo.setWrkNo(staProtocol.getWorkNo().intValue()); | 
|         commandInfo.setCommandStatus(1); | 
|         commandInfo.setStartTime(new Date()); | 
|         commandInfo.setDevice("devp"); | 
|         commandInfo.setCommand(JSON.toJSONString(staProtocol)); | 
|         commandInfoService.insert(commandInfo); | 
|   | 
|         OperateResult writeResult; | 
|         //任务下发次数 | 
|         int writeCount = 0; | 
|         //任务下发成功标识 | 
|         boolean writeFlag = false; | 
|         while(writeCount < 5){ | 
|             writeResult = siemensS7Net.Write("DB100." + index*4, array);    // 工作号、目标站 | 
|             if(writeResult.IsSuccess){ | 
|                 Thread.sleep(200); | 
|                 OperateResultExOne<byte[]> readResult = siemensS7Net.Read("DB100." + index*4, (short)4); | 
|                 if(readResult.IsSuccess){ | 
|                     short workNo = siemensS7Net.getByteTransform().TransInt16(readResult.Content, 0); | 
|                     short staNo = siemensS7Net.getByteTransform().TransInt16(readResult.Content, 2); | 
|                     if(staProtocol.getWorkNo().equals(workNo) && staProtocol.getStaNo().equals(staNo)){ | 
|                         //任务命令写入成功 | 
|                         writeFlag = true; | 
|                         log.info("写入输送线命令后返回成功,并且回读成功。输送线plc编号={},{},写入次数={}", slave.getId(), JSON.toJSON(staProtocol), writeCount); | 
|                         break; | 
|                     } else {//返回结果是成功了,但是真实值不相同 | 
|                         writeCount++; | 
|                         OutputQueue.DEVP.offer(MessageFormat.format("【{0}】写入输送线命令后返回成功,但是读取任务值不一致。输送线plc编号={1},站点数据={2},写入次数={3}", | 
|                                 slave.getId(), JSON.toJSON(staProtocol),writeCount)); | 
|                         log.error("写入输送线命令后返回成功,但是读取任务值不一致。输送线plc编号={},{},写入次数={}", slave.getId(), JSON.toJSON(staProtocol), writeCount); | 
|                     } | 
|                 } else { | 
|                     writeCount++; | 
|                     OutputQueue.DEVP.offer(MessageFormat.format("【{0}】写入输送线命令后读取失败。输送线plc编号={1},站点数据={2},写入次数={3}", | 
|                             slave.getId(), JSON.toJSON(staProtocol), writeCount)); | 
|                     log.error("写入输送线命令后读取失败。输送线plc编号={},站点数据={},写入次数={}", slave.getId(), JSON.toJSON(staProtocol), writeCount); | 
|                 } | 
|             } else { | 
|                 writeCount++; | 
|                 OutputQueue.DEVP.offer(MessageFormat.format("【{0}】写入输送线命令失败。输送线plc编号={1},站点数据={2},写入次数={3}", | 
|                         slave.getId(), JSON.toJSON(staProtocol),writeCount)); | 
|                 log.error("写入输送线命令失败。输送线plc编号={},站点数据={},写入次数={}", slave.getId(), JSON.toJSON(staProtocol), writeCount); | 
|             } | 
|             Thread.sleep(200); | 
|         } | 
|   | 
|         //写命令尝试了5次还是失败了 | 
|         if(!writeFlag){ | 
|             staProtocol = station.get(staProtocol.getSiteId()); | 
|             if (staProtocol.getWorkNo() == 0 && staProtocol.getStaNo() ==0) { | 
|                 staProtocol.setPakMk(true); | 
|             } | 
|             OutputQueue.DEVP.offer(MessageFormat.format("【{0}】写入输送线命令尝试5次失败。输送线plc编号={1},站点数据={2}", slave.getId(), JSON.toJSON(staProtocol))); | 
|             log.error("写入输送线命令尝试5次失败。输送线plc编号={},站点数据={}", slave.getId(), JSON.toJSON(staProtocol)); | 
|   | 
|             //重新添加数据到任务队列 | 
|             boolean result = MessageQueue.offer(SlaveType.Devp, slave.getId(), new Task(2, staProtocol)); | 
|             read();//读取1次设备状态 | 
|             return; | 
|         } else { | 
|             OutputQueue.DEVP.offer(MessageFormat.format("【{0}】 输送线命令下发成功 [id:{1}] >>>>> {2}", DateUtils.convert(new Date()), slave.getId(), JSON.toJSON(staProtocol))); | 
|             log.info("输送线命令下发 [id:{}] >>>>> 命令下发成功: {}",  slave.getId(), JSON.toJSON(staProtocol)); | 
|   | 
|             Integer siteId = staProtocol.getSiteId(); | 
|             staProtocol = station.get(siteId); | 
|             if ((siteId == 101 || siteId == 201)&&(staProtocol.getWorkNo() == 0 && staProtocol.getStaNo() ==0)) { | 
|                 staProtocol.setPakMk(true); | 
|             } | 
|         } | 
|   | 
|     } | 
|   | 
| //    /** | 
| //     * 写入 ID+目标站 =====> 单站点写入 | 
| //     */ | 
| //    private void write(StaProtocol staProtocol) throws InterruptedException { | 
| //        if (null == staProtocol) { | 
| //            return; | 
| //        } | 
| //        int index = staNos.indexOf(staProtocol.getSiteId()); | 
| //        short[] array = new short[2]; | 
| //        array[0] = staProtocol.getWorkNo(); | 
| //        array[1] = staProtocol.getStaNo(); | 
| //        OperateResult write = siemensS7Net.Write("DB100." + index*4, array); | 
| // | 
| ////        OperateResult write = siemensS7Net.Write("DB100." + index*2, staProtocol.getWorkNo());    // 工作号 | 
| ////        Thread.sleep(500); | 
| ////        OperateResult write1 = siemensS7Net.Write("DB101." + index*2, staProtocol.getStaNo());    // 目标站 | 
| // | 
| //        if (!write.IsSuccess) { | 
| //            staProtocol = station.get(staProtocol.getSiteId()); | 
| //            if (staProtocol.getWorkNo() == 0 && staProtocol.getStaNo() ==0) { | 
| //                staProtocol.setPakMk(true); | 
| //            } | 
| //            OutputQueue.DEVP.offer(MessageFormat.format("【{0}】写入输送线站点数据失败。输送线plc编号={1},站点数据={2}", slave.getId(), JSON.toJSON(staProtocol))); | 
| //            log.error("写入输送线站点数据失败。输送线plc编号={},站点数据={}", slave.getId(), JSON.toJSON(staProtocol)); | 
| //        } else { | 
| //            OutputQueue.DEVP.offer(MessageFormat.format("【{0}】 输送线命令下发 [id:{1}] >>>>> {2}", DateUtils.convert(new Date()), slave.getId(), JSON.toJSON(staProtocol))); | 
| //            log.info("输送线命令下发 [id:{}] >>>>> 命令下发: {}",  slave.getId(), JSON.toJSON(staProtocol)); | 
| // | 
| //            Integer siteId = staProtocol.getSiteId(); | 
| //            staProtocol = station.get(siteId); | 
| //            if ((siteId == 101 || siteId == 201)&&(staProtocol.getWorkNo() == 0 && staProtocol.getStaNo() ==0)) { | 
| //                staProtocol.setPakMk(true); | 
| //            } | 
| //        } | 
| //    } | 
|   | 
|     // 更新入出库模式 | 
|     private void updateIoMode() throws InterruptedException { | 
|         if (this.ioModeOf2F != IoModeType.NONE) { | 
|             if (!siemensS7Net.Write("DB100.180", this.ioModeOf2F.id).IsSuccess) { | 
|                 OutputQueue.DEVP.offer(MessageFormat.format("【{0}】写入输送线2F入出库模式失败。输送线plc编号={1}", slave.getId())); | 
|                 log.error("写入输送线2F入出库模式失败。输送线plc编号={}", slave.getId()); | 
|             } | 
|         } | 
|     } | 
|   | 
|     /** | 
|      * 心跳 | 
|      */ | 
|     private void heartbeat(){ | 
|         if (heartBeatVal == 1) { | 
|             heartBeatVal = 2; | 
|         } else { | 
|             heartBeatVal = 1; | 
|         } | 
|         OperateResult write = siemensS7Net.Write("DB100.50", heartBeatVal); | 
|         if (!write.IsSuccess) { | 
|             log.error("输送线plc编号={} 心跳失败", slave.getId()); | 
|         } | 
|     } | 
|   | 
|     /** | 
|      * 设置入库标记 | 
|      */ | 
|     @Override | 
|     public void setPakMk(Integer siteId, boolean pakMk) { | 
|         StaProtocol staProtocol = station.get(siteId); | 
|         if (null != staProtocol) { | 
|             staProtocol.setPakMk(pakMk); | 
|         } | 
|     } | 
|   | 
|     @Override | 
|     public void close() { | 
|         siemensS7Net.ConnectClose(); | 
|     } | 
|   | 
|     public static void main(String[] args) { | 
|         System.out.println(staNos.indexOf(129)); | 
|         System.out.println(staNos.size()); | 
|         for (int i = 0; i<staNos.size(); i++) { | 
| //            System.out.println(i*2); | 
| //            System.out.println(i*2 + 200); | 
| //            System.out.println(i); | 
|         } | 
|         int index = staNos.indexOf(128); | 
|         System.out.println(index*2); | 
|         System.out.println(index*2 + 200); | 
|     } | 
|   | 
| //    public static void main(String[] args) throws Exception { | 
| //        DevpSlave slave = new DevpSlave(); | 
| //        slave.setIp("192.168.2.125"); | 
| //        SiemensDevpThread devpThread = new SiemensDevpThread(slave); | 
| //        devpThread.connect(); | 
| //        devpThread.read(); | 
| //        // 写 | 
| //        StaProtocol staProtocol = devpThread.getStation().get(1); | 
| //        staProtocol.setWorkNo((short) 232); | 
| //        staProtocol.setStaNo((short) 6); | 
| //        staProtocol.setAutoing(true); | 
| //        staProtocol.setEmptyMk(true); | 
| //        staProtocol.setInEnable(true); | 
| //        devpThread.write(staProtocol); | 
| //        System.out.println("----------------------------------------"); | 
| //        // 读 | 
| //        devpThread.read(); | 
| //        System.out.println(JSON.toJSONString(devpThread.station)); | 
| // | 
| //    } | 
|   | 
| } |