Browse Source

130与135分离

liuwei 2 weeks ago
parent
commit
1b2e0023d4

+ 196 - 14
src/com/mes/component/DirectScanHandshake.java

@@ -12,11 +12,12 @@ import org.slf4j.LoggerFactory;
 import java.nio.charset.StandardCharsets;
 import java.util.Timer;
 import java.util.TimerTask;
+import java.util.concurrent.atomic.AtomicReference;
 
 /**
  * OP135 入口独立扫码握手。
  *
- * PLC 请求后触发新扫码枪,MES 校验通过后依次更新 PLC 工件码和允许信号。
+ * PLC 请求后触发新扫码枪,MES 校验通过后依次更新 PLC 工件码、交付登记 CNC、写允许信号。
  * 交付成功 33 秒后清理允许和本次写入的工件码,不再等待请求变为 0 后立即清理。
  */
 public class DirectScanHandshake {
@@ -30,6 +31,7 @@ public class DirectScanHandshake {
     private static final int SN_MAX_LENGTH = 24;
     private static final long RETRY_SCAN_MS = 10000;
     private static final long CLEAN_DELAY_MS = 33000;
+    private static final long OWNER_TIMEOUT_MS = 60000;
     private static final String OPRNO = "OP135";
 
     private enum State {
@@ -43,14 +45,21 @@ public class DirectScanHandshake {
     private final S7PLC plc;
     private final TCPClient scanner;
 
-    private State state = State.IDLE;
-    private Boolean lastRequest = null;
+    private volatile State state = State.IDLE;
+    private volatile Boolean lastRequest = null;
     private long nextScanAt = 0;
     private long clearAt = 0;
-    private String validatedSn = "";
-    private String plcOwnedSn = "";
-    private String lastStatus = "";
+    private volatile String validatedSn = "";
+    private volatile String plcOwnedSn = "";
+    private volatile boolean cncDelivered = false;
+    private volatile String lastStatus = "";
+    private volatile int lastStatusError = 0;
     private Timer timer;
+    private final AtomicReference<WorkJPanelCnc> pendingCnc = new AtomicReference<>();
+    private volatile String lastScannedSn = "";
+    private volatile String lastPlcWrittenSn = "";
+    private volatile String lastDeliveredCnc = "";
+    private volatile long ownerRegisteredAt = 0;
 
     public DirectScanHandshake(String plcIp, TCPClient scanner) {
         this.plc = new S7PLC(EPlcType.S1500, plcIp);
@@ -79,6 +88,120 @@ public class DirectScanHandshake {
         }, 1000, 1000);
     }
 
+    /**
+     * 登记刚刚请求上料的 OP135 CNC。PLC 保证同一时间只有一台,
+     * 若旧归属尚未交付则保留原归属,防止扫码结果串到其他工位。
+     */
+    public boolean registerScanOwner(WorkJPanelCnc panel) {
+        if (panel == null) {
+            return false;
+        }
+        if (state == State.WAIT_CLEAR) {
+            return false;
+        }
+        WorkJPanelCnc current = pendingCnc.get();
+        if (current == panel) {
+            ownerRegisteredAt = System.currentTimeMillis();
+            return true;
+        }
+        if (current != null) {
+            log.warn("OP135 已有待交付扫码归属 {},拒绝登记 {}",
+                    current.oprno + current.pos, panel.oprno + panel.pos);
+            return false;
+        }
+        if (pendingCnc.compareAndSet(current, panel)) {
+            cncDelivered = false;
+            ownerRegisteredAt = System.currentTimeMillis();
+            log.info("OP135 登记扫码归属工位:{}{}", panel.oprno, panel.pos);
+            return true;
+        }
+        return false;
+    }
+
+    /** 上料请求撤销且当前没有进行中的扫码时,释放尚未使用的归属。 */
+    public void releaseScanOwner(WorkJPanelCnc panel) {
+        if (state == State.IDLE || state == State.WAIT_REQUEST_RISE) {
+            if (pendingCnc.compareAndSet(panel, null)) {
+                ownerRegisteredAt = 0;
+                log.info("OP135 释放扫码归属工位:{}{}", panel.oprno, panel.pos);
+            }
+        }
+    }
+
+    /** 只读监控数据,不参与握手判断。 */
+    public String getScannerEndpoint() {
+        return scanner.serverIP + ":" + scanner.serverPort;
+    }
+
+    public String getScanRequestAddress() {
+        return REQUEST_ADDR;
+    }
+
+    public String getScanAllowAddress() {
+        return ALLOW_ADDR;
+    }
+
+    public Boolean readScanRequestSignal() {
+        return readBoolean(REQUEST_ADDR);
+    }
+
+    public Boolean readScanAllowSignal() {
+        return readBoolean(ALLOW_ADDR);
+    }
+
+    /** 仅供监控页人工修改允许扫码信号。 */
+    public boolean writeScanAllowSignal(boolean value) {
+        return writeBoolean(ALLOW_ADDR, value);
+    }
+
+    public Boolean getRequestSignal() {
+        return lastRequest;
+    }
+
+    public String getStateText() {
+        switch (state) {
+            case WAITING_SCAN:
+                return "等待扫码/校验";
+            case VALIDATED:
+                return "已校验,等待写码/交付";
+            case WAIT_CLEAR:
+                return "已允许,等待33秒清理";
+            case WAIT_REQUEST_RISE:
+                return "清理完成,等待下一请求";
+            default:
+                return "空闲";
+        }
+    }
+
+    public String getLastScannedSn() {
+        return lastScannedSn;
+    }
+
+    public String getValidatedSn() {
+        return validatedSn;
+    }
+
+    public String getPlcWrittenSn() {
+        return plcOwnedSn.isEmpty() ? lastPlcWrittenSn : plcOwnedSn;
+    }
+
+    public String getPendingOwner() {
+        WorkJPanelCnc owner = pendingCnc.get();
+        return owner == null ? "" : owner.oprno + owner.pos;
+    }
+
+    public String getLastDeliveredCnc() {
+        return lastDeliveredCnc;
+    }
+
+    public String getLastStatus() {
+        return lastStatus;
+    }
+
+    public int getLastStatusError() {
+        return lastStatusError;
+    }
+
     private void cycle() {
         Boolean request = readBoolean(REQUEST_ADDR);
         if (request == null) {
@@ -94,6 +217,7 @@ public class DirectScanHandshake {
         }
 
         if (!request) {
+            expirePendingOwnerIfNeeded();
             handleRequestOff(previous);
             return;
         }
@@ -105,10 +229,11 @@ public class DirectScanHandshake {
             }
             state = State.WAITING_SCAN;
             validatedSn = "";
+            cncDelivered = false;
             nextScanAt = 0;
             clearAt = 0;
-            showStatus("OP135 收到请求,准备扫码", 0);
-            log.info("OP135 收到扫码请求,开始处理");
+            showStatus("OP135 收到扫码请求,准备校验", 0);
+            log.info("OP135 收到扫码请求,校验和写码成功前不允许");
         }
 
         if (state == State.WAITING_SCAN) {
@@ -125,6 +250,10 @@ public class DirectScanHandshake {
         if (previous && state != State.WAIT_CLEAR && state != State.WAIT_REQUEST_RISE) {
             validatedSn = "";
             nextScanAt = 0;
+            if (!cncDelivered && pendingCnc.getAndSet(null) != null) {
+                ownerRegisteredAt = 0;
+                log.info("OP135 扫码请求结束,释放尚未交付的CNC归属");
+            }
             if (!plcOwnedSn.isEmpty()) {
                 scheduleDelayedCleanup();
             } else {
@@ -135,12 +264,29 @@ public class DirectScanHandshake {
             return;
         }
 
-        // 程序启动时若残留允许但请求为 false,只清允许,不动 130 已下发的工件码。
+        // 程序启动时若残留允许但请求为 false,只清允许,不清理未知来源的工件码。
         if (state == State.IDLE) {
             ensureAllowOff();
         }
     }
 
+    private void expirePendingOwnerIfNeeded() {
+        WorkJPanelCnc owner = pendingCnc.get();
+        if (owner == null || ownerRegisteredAt == 0) {
+            return;
+        }
+        boolean waitingForFirstScanRequest = state == State.IDLE
+                || state == State.WAIT_REQUEST_RISE;
+        if (waitingForFirstScanRequest
+                && System.currentTimeMillis() - ownerRegisteredAt >= OWNER_TIMEOUT_MS) {
+            if (pendingCnc.compareAndSet(owner, null)) {
+                ownerRegisteredAt = 0;
+                showStatus("OP135 等待扫码请求超时,已释放CNC归属", -1);
+                log.warn("OP135 等待扫码请求超时,释放归属 {}{}", owner.oprno, owner.pos);
+            }
+        }
+    }
+
     private void scanAndValidate() {
         showStatus("OP135 扫码中...", 0);
         String sn = scanQrCode();
@@ -148,6 +294,7 @@ public class DirectScanHandshake {
             retryAfterFailure("OP135 扫码失败,10 秒后重试");
             return;
         }
+        lastScannedSn = sn;
         if (sn.getBytes(StandardCharsets.US_ASCII).length > SN_MAX_LENGTH) {
             retryAfterFailure("OP135 工件码超过 " + SN_MAX_LENGTH + " 字节,10 秒后重试");
             return;
@@ -198,6 +345,23 @@ public class DirectScanHandshake {
             return;
         }
 
+        Boolean request = readBoolean(REQUEST_ADDR);
+        if (request == null) {
+            showStatus("OP135 写码前读取请求失败,稍后重试", -1);
+            return;
+        }
+        if (!request) {
+            state = State.IDLE;
+            showStatus("OP135 扫码请求已撤销,不写码和允许", 0);
+            return;
+        }
+
+        WorkJPanelCnc owner = pendingCnc.get();
+        if (owner == null) {
+            showStatus("OP135 校验已通过,等待请求上料的CNC", -1);
+            return;
+        }
+
         if (!sn.equals(plcOwnedSn)) {
             try {
                 plc.writeString(SN_ADDR, sn);
@@ -208,6 +372,7 @@ public class DirectScanHandshake {
                     return;
                 }
                 plcOwnedSn = sn;
+                lastPlcWrittenSn = sn;
                 log.info("OP135 写入工件码 {} -> {} 成功", SN_ADDR, sn);
             } catch (Exception e) {
                 log.error("OP135 写入工件码 {} -> {} 失败:{}", SN_ADDR, sn, e.getMessage());
@@ -216,7 +381,19 @@ public class DirectScanHandshake {
             }
         }
 
-        Boolean request = readBoolean(REQUEST_ADDR);
+        if (!cncDelivered) {
+            if (!owner.acceptScannedSn(sn)) {
+                showStatus("OP135 工件码交付CNC失败,保持不允许并重试", -1);
+                return;
+            }
+            cncDelivered = true;
+            pendingCnc.compareAndSet(owner, null);
+            ownerRegisteredAt = 0;
+            lastDeliveredCnc = owner.oprno + owner.pos;
+            log.info("OP135 工件码 {} 已交付 {}{}", sn, owner.oprno, owner.pos);
+        }
+
+        request = readBoolean(REQUEST_ADDR);
         if (request == null) {
             showStatus("OP135 放行前读取请求失败,稍后重试", -1);
             return;
@@ -233,14 +410,15 @@ public class DirectScanHandshake {
 
         state = State.WAIT_CLEAR;
         clearAt = System.currentTimeMillis() + CLEAN_DELAY_MS;
-        showStatus("OP135 工件码已发送,允许加工", 0);
-        log.info("OP135 工件码 {} 已发送,{} 已置 true,33 秒后清理", sn, ALLOW_ADDR);
+        showStatus("OP135 校验、写码和CNC交付完成,允许加工", 0);
+        log.info("OP135 工件码 {} 校验、写码和CNC交付完成,{} 已置 true,33 秒后清理",
+                sn, ALLOW_ADDR);
     }
 
     private void scheduleDelayedCleanup() {
         state = State.WAIT_CLEAR;
         clearAt = System.currentTimeMillis() + CLEAN_DELAY_MS;
-        showStatus("OP135 已达上传条件,33 秒后清理工件码和允许", 0);
+        showStatus("OP135 请求已结束,33 秒后清理工件码和允许", 0);
     }
 
     private void handleDelayedCleanup() {
@@ -252,10 +430,13 @@ public class DirectScanHandshake {
             return;
         }
         validatedSn = "";
+        cncDelivered = false;
+        pendingCnc.set(null);
+        ownerRegisteredAt = 0;
         clearAt = 0;
         state = State.WAIT_REQUEST_RISE;
         showStatus("OP135 33 秒清理完成,等待下一次请求", 0);
-        log.info("OP135 上传后 33 秒清理完成");
+        log.info("OP135 33 秒清理完成");
     }
 
     private void retryAfterFailure(String message) {
@@ -382,6 +563,7 @@ public class DirectScanHandshake {
             return;
         }
         lastStatus = message;
+        lastStatusError = error;
         MesClient.setMenuStatus(message, error);
     }
 }

+ 238 - 0
src/com/mes/component/DirectScanMonitorPanel.java

@@ -0,0 +1,238 @@
+package com.mes.component;
+
+import com.mes.ui.MesClient;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.util.Timer;
+import java.util.TimerTask;
+
+/**
+ * OP135 独立扫码枪 64 的监控页。
+ * 展示握手状态;除人工切换“允许扫码”外,不触发扫码或其他 PLC 写入。
+ */
+public class DirectScanMonitorPanel extends JPanel {
+
+    private static final int WORK_WIDTH = 470;
+    private static final int WORK_HEIGHT = 300;
+
+    private final DirectScanHandshake handshake;
+
+    private JButton statusMenu;
+    private JLabel subtitleLabel;
+    private JLabel requestScanLight;
+    private JLabel allowScanLight;
+    private JTextField scannedSnField;
+    private JTextField validatedSnField;
+    private JTextField plcSnField;
+    private JTextField ownerField;
+    private JTextField stageField;
+    private ImageIcon imageGreen;
+    private ImageIcon imageGray;
+    private Timer refreshTimer;
+
+    public DirectScanMonitorPanel(DirectScanHandshake handshake) {
+        this.handshake = handshake;
+        setLayout(null);
+        setBackground(Color.WHITE);
+        setPreferredSize(new Dimension(WORK_WIDTH, WORK_HEIGHT));
+
+        initUI();
+        refresh();
+        startRefreshTimer();
+    }
+
+    private void initUI() {
+        JLabel title = new JLabel("OP135");
+        title.setHorizontalAlignment(SwingConstants.CENTER);
+        title.setForeground(Color.BLACK);
+        title.setFont(new Font("微软雅黑", Font.PLAIN, 20));
+        title.setBounds(0, 0, WORK_WIDTH / 5, 40);
+        add(title);
+
+        subtitleLabel = new JLabel("独立扫码64");
+        subtitleLabel.setHorizontalAlignment(SwingConstants.CENTER);
+        subtitleLabel.setForeground(Color.BLACK);
+        subtitleLabel.setFont(new Font("微软雅黑", Font.PLAIN, 13));
+        subtitleLabel.setBounds(0, 18, WORK_WIDTH / 5, 35);
+        add(subtitleLabel);
+
+        statusMenu = new JButton("");
+        statusMenu.setBounds(WORK_WIDTH / 5, 0, WORK_WIDTH * 4 / 5, 40);
+        statusMenu.setFont(new Font("微软雅黑", Font.PLAIN, 16));
+        statusMenu.setBackground(Color.BLACK);
+        statusMenu.setFocusable(false);
+        add(statusMenu);
+
+        imageGreen = scaledIcon("/bg/green_dot.png");
+        imageGray = scaledIcon("/bg/grey_dot.png");
+        requestScanLight = createLight("请求扫码", 0, 50);
+        allowScanLight = createLight("允许扫码", WORK_WIDTH / 3, 50);
+        allowScanLight.addMouseListener(toggleAllowScan());
+
+        scannedSnField = createField("原始扫码", 90);
+        validatedSnField = createField("校验通过", 130);
+        plcSnField = createField("PLC最近写码", 170);
+        ownerField = createField("CNC归属", 210);
+
+        JLabel stageLabel = new JLabel("流转阶段");
+        stageLabel.setHorizontalAlignment(SwingConstants.CENTER);
+        stageLabel.setForeground(Color.BLACK);
+        stageLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
+        stageLabel.setBounds(0, 250, WORK_WIDTH / 5, 35);
+        add(stageLabel);
+
+        stageField = new JTextField("");
+        stageField.setHorizontalAlignment(SwingConstants.CENTER);
+        stageField.setForeground(Color.BLACK);
+        stageField.setFont(new Font("微软雅黑", Font.PLAIN, 13));
+        stageField.setEditable(false);
+        stageField.setBounds(WORK_WIDTH / 5, 250, WORK_WIDTH * 4 / 5, 35);
+        add(stageField);
+
+        scannedSnField.addMouseListener(new MouseAdapter() {
+            @Override
+            public void mouseClicked(MouseEvent e) {
+                String sn = handshake == null ? "" : handshake.getLastScannedSn();
+                if (!sn.isEmpty()) {
+                    MesClient.createQRCode(sn, "OP135独立扫码64");
+                }
+            }
+        });
+    }
+
+    private JLabel createLight(String text, int x, int y) {
+        JLabel label = new JLabel(text);
+        label.setHorizontalAlignment(SwingConstants.LEFT);
+        label.setIcon(imageGray);
+        label.setForeground(Color.BLACK);
+        label.setFont(new Font("微软雅黑", Font.PLAIN, 14));
+        label.setBounds(x, y, WORK_WIDTH / 3, 30);
+        add(label);
+        return label;
+    }
+
+    private MouseAdapter toggleAllowScan() {
+        return new MouseAdapter() {
+            @Override
+            public void mouseClicked(MouseEvent e) {
+                if (handshake == null) {
+                    JOptionPane.showMessageDialog(null, "独立扫码枪64未配置");
+                    return;
+                }
+                Boolean current = handshake.readScanAllowSignal();
+                if (current == null) {
+                    JOptionPane.showMessageDialog(null, "读取允许扫码信号失败");
+                    return;
+                }
+                boolean target = !current;
+                if (!confirm("确定修改允许扫码(" + handshake.getScanAllowAddress()
+                        + ")为" + target + "吗?")) {
+                    return;
+                }
+                if (!handshake.writeScanAllowSignal(target)) {
+                    JOptionPane.showMessageDialog(null, "写入允许扫码信号失败");
+                    return;
+                }
+                refresh();
+            }
+        };
+    }
+
+    private JTextField createField(String labelText, int y) {
+        JLabel label = new JLabel(labelText);
+        label.setHorizontalAlignment(SwingConstants.CENTER);
+        label.setForeground(Color.BLACK);
+        label.setFont(new Font("微软雅黑", Font.PLAIN, 14));
+        label.setBounds(0, y, WORK_WIDTH / 5, 35);
+        add(label);
+
+        JTextField field = new JTextField("");
+        field.setHorizontalAlignment(SwingConstants.CENTER);
+        field.setForeground(Color.BLACK);
+        field.setFont(new Font("微软雅黑", Font.PLAIN, 13));
+        field.setEditable(false);
+        field.setBounds(WORK_WIDTH / 5, y, WORK_WIDTH * 4 / 5, 35);
+        add(field);
+        return field;
+    }
+
+    private static boolean confirm(String msg) {
+        return JOptionPane.showConfirmDialog(null, msg, "操作确认",
+                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION;
+    }
+
+    private static ImageIcon scaledIcon(String path) {
+        ImageIcon icon = new ImageIcon(MesClient.class.getResource(path));
+        icon.setImage(icon.getImage().getScaledInstance(20, 20, Image.SCALE_SMOOTH));
+        return icon;
+    }
+
+    private ImageIcon light(boolean on) {
+        return on ? imageGreen : imageGray;
+    }
+
+    private void startRefreshTimer() {
+        refreshTimer = new Timer("OP135-direct-scan-64-monitor", true);
+        refreshTimer.schedule(new TimerTask() {
+            @Override
+            public void run() {
+                SwingUtilities.invokeLater(DirectScanMonitorPanel.this::refresh);
+            }
+        }, 0, 1000);
+    }
+
+    private void refresh() {
+        if (handshake == null) {
+            statusMenu.setForeground(Color.RED);
+            statusMenu.setText("未配置独立扫码枪64");
+            subtitleLabel.setToolTipText(null);
+            requestScanLight.setIcon(imageGray);
+            allowScanLight.setIcon(imageGray);
+            scannedSnField.setText("-");
+            validatedSnField.setText("-");
+            plcSnField.setText("-");
+            ownerField.setText("-");
+            stageField.setText("-");
+            return;
+        }
+
+        String lastStatus = handshake.getLastStatus();
+        String stateText = handshake.getStateText();
+        statusMenu.setForeground(handshake.getLastStatusError() == 0 ? Color.GREEN : Color.RED);
+        statusMenu.setText(emptyToDash(lastStatus).equals("-") ? stateText : lastStatus);
+
+        subtitleLabel.setToolTipText(handshake.getScannerEndpoint());
+        Boolean requestScan = handshake.readScanRequestSignal();
+        Boolean allowScan = handshake.readScanAllowSignal();
+        requestScanLight.setIcon(light(Boolean.TRUE.equals(requestScan)));
+        allowScanLight.setIcon(light(Boolean.TRUE.equals(allowScan)));
+        requestScanLight.setToolTipText(handshake.getScanRequestAddress());
+        allowScanLight.setToolTipText(handshake.getScanAllowAddress() + "(点击修改)");
+
+        scannedSnField.setText(emptyToDash(handshake.getLastScannedSn()));
+        validatedSnField.setText(emptyToDash(handshake.getValidatedSn()));
+        plcSnField.setText(emptyToDash(handshake.getPlcWrittenSn()));
+
+        String pendingOwner = handshake.getPendingOwner();
+        String deliveredCnc = handshake.getLastDeliveredCnc();
+        String ownerText;
+        if (!pendingOwner.isEmpty()) {
+            ownerText = "等待交付 -> " + pendingOwner;
+        } else if (!deliveredCnc.isEmpty()) {
+            ownerText = "最近已交付 -> " + deliveredCnc;
+        } else {
+            ownerText = "-";
+        }
+        ownerField.setText(ownerText);
+
+        String requestText = requestScan == null ? "-" : (requestScan ? "1" : "0");
+        stageField.setText("请求:" + requestText + " | " + stateText);
+    }
+
+    private static String emptyToDash(String value) {
+        return value == null || value.trim().isEmpty() ? "-" : value;
+    }
+}

+ 177 - 26
src/com/mes/component/WorkJPanelCnc.java

@@ -26,9 +26,9 @@ import java.util.TimerTask;
  * 点位 DB700X:0.0 请求上料 / 0.1 请求下料 / 0.2 运行中 / 0.3 设备状态 / 0.4 MES允许上料
  *            0.5 MES允许下料 / 0.6 心跳 / 0.7 上料到设备;1.0、1.1、2、4 为预留,不读不写
  *
- * 上料:请求上料时从 sourceSlot 取码(正面=本 PLC 扫码码,反面=反面待上料码),校验通过写 0.4
+ * 上料:OP130 从本 PLC 扫码槽取码,校验通过写 0.4;OP135 请求上料后直接写 0.4,扫码码由独立扫码握手回填
  * 进设备:0.7 上升沿或 0.2 运行中,码从「上料」移到「加工」
- * 下料:请求下料时上传结果;OP130A-F 要等反面待上料码为空,上传成功后存码给反面,再写 0.5
+ * 下料:请求下料时上传结果,接口成功后才写 0.5;无码时直接写 0.5
  */
 public class WorkJPanelCnc extends JPanel {
 
@@ -37,6 +37,9 @@ public class WorkJPanelCnc extends JPanel {
     public static final String PLC_92 = "192.168.90.92";
     public static final String PLC_93 = "192.168.90.93";
 
+    // 旧的 130 -> 135 共享码流转入口保留但关闭,避免现场误用。
+    private static final boolean LEGACY_SHARED_FLOW_ENABLED = false;
+
     private static final String[] CN_NO = {"一", "二", "三", "四", "五", "六", "七", "八", "九", "十"};
 
     public String oprno;      // OP130 / OP135
@@ -47,7 +50,7 @@ public class WorkJPanelCnc extends JPanel {
     public String deviceName;
 
     public SnSlot sourceSlot; // 上料取码来源
-    public SnSlot targetSlot; // 下料存码目标:OP130A-F=反面待上料码,反面为 null
+    public SnSlot targetSlot; // 旧共享流转目标,当前仅保留以隐藏旧实现
 
     public S7PLC s7PLC;
 
@@ -61,7 +64,12 @@ public class WorkJPanelCnc extends JPanel {
 
     private boolean feedingReleased = true; // 请求上料复位过,才处理下一次上料
     private boolean lastToDevice = false;   // 上一轮 0.7,用于取上升沿
+    private volatile boolean atDevice = false;
+    private volatile boolean running = false;
     private boolean plcHeart = false;
+    private boolean op135ScanOwnerRegistered = false;
+    private String completionSubmittedSn = "";
+    private DirectScanHandshake scanHandshake;
 
     public JButton status_menu;
     public JTextField productSnFeeding; // 上料码
@@ -116,7 +124,8 @@ public class WorkJPanelCnc extends JPanel {
         s7PLC.setReceiveTimeout(1000);
         s7PLC.setConnectTimeout(1000);
 
-        cacheName = "cache_" + oprno + pos;
+        // OP135 改用新缓存,旧 cache_OP135X 中的共享码不再恢复显示。
+        cacheName = front ? "cache_" + oprno + pos : "cache_" + oprno + pos + "_independent";
         cacheData = JdbcUtils.getCache(cacheName);
         if (cacheData == null) {
             cacheData = new CacheData();
@@ -165,7 +174,7 @@ public class WorkJPanelCnc extends JPanel {
         productSnFeeding = createSnField(50);
         resetFeedingBtn = createResetBtn(50, () -> {
             String sn = productSnFeeding.getText().trim();
-            if (confirm("确定刷新上料工件" + sn + "吗?\n刷新后该码不会退回待上料码")) {
+            if (confirm("确定刷新上料工件" + sn + "吗?")) {
                 resetFeeding();
             }
         });
@@ -174,8 +183,7 @@ public class WorkJPanelCnc extends JPanel {
         productSn = createSnField(100);
         resetBtn = createResetBtn(100, () -> {
             String sn = productSn.getText().trim();
-            String tip = front ? "\n刷新后不上传该件结果,也不会存入反面待上料码" : "\n刷新后不上传该件结果";
-            if (confirm("确定刷新加工工件" + sn + "吗?" + tip)) {
+            if (confirm("确定刷新加工工件" + sn + "吗?\n刷新后不上传该件结果")) {
                 resetBlanking("已手动清除加工工件");
             }
         });
@@ -335,6 +343,8 @@ public class WorkJPanelCnc extends JPanel {
             oprnoTimer.cancel();
         }
         oprnoTimer = new Timer();
+        // OP135 的上料请求可能在写入 0.4 后很快撤销,缩短采样周期以捕获短脉冲。
+        long pollInterval = front ? 3000L : 1000L;
         oprnoTimer.schedule(new TimerTask() {
             public void run() {
                 try {
@@ -345,7 +355,7 @@ public class WorkJPanelCnc extends JPanel {
                     log.error("<{}{}>轮询异常", oprno, pos, e);
                 }
             }
-        }, 100, 3000);
+        }, 100, pollInterval);
     }
 
     private void cycle() {
@@ -357,6 +367,8 @@ public class WorkJPanelCnc extends JPanel {
         boolean retToDevice = readBoolean(plcDb + ".0.7");
         boolean toDeviceRise = retToDevice && !lastToDevice;
         lastToDevice = retToDevice;
+        running = retRunning;
+        atDevice = retToDevice;
 
         feedinglabel.setIcon(light(retFeeding));
         feedingmeslabel.setIcon(light(retAllowFeeding));
@@ -365,6 +377,19 @@ public class WorkJPanelCnc extends JPanel {
         blankingmeslabel.setIcon(light(retAllowBlanking));
         feedingtodevicelabel.setIcon(light(retToDevice));
 
+        if (!front) {
+            cycleOp135(retFeeding, retBlanking, retRunning, retAllowFeeding,
+                    retAllowBlanking, toDeviceRise);
+            return;
+        }
+
+        cycleOp130(retFeeding, retBlanking, retRunning, retAllowFeeding,
+                retAllowBlanking, toDeviceRise);
+    }
+
+    private void cycleOp130(boolean retFeeding, boolean retBlanking, boolean retRunning,
+                            boolean retAllowFeeding, boolean retAllowBlanking,
+                            boolean toDeviceRise) {
         // 请求上料撤销后复位 MES允许上料
         if (!retFeeding && retAllowFeeding) {
             writeAllowFeeding(false);
@@ -391,23 +416,70 @@ public class WorkJPanelCnc extends JPanel {
             setMenuStatus("工件已上料到设备", 0);
         }
 
-        // ---------- 下料 ----------
-        // 加工码为空时直接放行下料(无码件或已上传完成)
-        if (retBlanking && productSn.getText().isEmpty() && !retAllowBlanking) {
-            writeAllowBlanking(true);
-        }
-        if (tjFlag == 0 && !retBlanking && retAllowBlanking) {
+        if (tjFlag == 1 && retRunning) {
+            tjFlag = 2;
+            writeAllowFeeding(false);
             writeAllowBlanking(false);
+            setMenuStatus("工件加工中", 0);
         }
 
+        if (LEGACY_SHARED_FLOW_ENABLED && tjFlag == 2 && retBlanking) {
+            finishWorkLegacy();
+            return;
+        }
+
+        handleBlankingRequest(retBlanking, retAllowBlanking);
+    }
+
+    private synchronized void cycleOp135(boolean retFeeding, boolean retBlanking,
+                                         boolean retRunning, boolean retAllowFeeding,
+                                         boolean retAllowBlanking, boolean toDeviceRise) {
+        // OP135 上料请求不等待扫码,直接允许。
+        if (retFeeding) {
+            if (!retAllowFeeding) {
+                writeAllowFeeding(true);
+            }
+            if (!op135ScanOwnerRegistered) {
+                if (scanHandshake == null) {
+                    log.error("<{}{}>独立扫码未初始化,无法登记扫码归属", oprno, pos);
+                    setMenuStatus("独立扫码未初始化", -1);
+                } else {
+                    op135ScanOwnerRegistered = scanHandshake.registerScanOwner(this);
+                    if (op135ScanOwnerRegistered) {
+                        setMenuStatus("收到上料请求,等待独立扫码", 0);
+                    } else {
+                        setMenuStatus("已有其他OP135工位等待扫码,本工位暂不绑定", -1);
+                    }
+                }
+            }
+        } else {
+            if (retAllowFeeding) {
+                writeAllowFeeding(false);
+            }
+            // 0.0 可能先于 64 的扫码请求撤销,归属必须锁存到扫码流程结束。
+            op135ScanOwnerRegistered = false;
+        }
+
+        // 扫码可能晚于设备进料,收到码后立即移动到加工码,避免丢失归属。
+        if (tjFeedingFlag == 1 && (toDeviceRise || retRunning || atDevice)) {
+            tjFlag = Math.max(tjFlag, 1);
+            tjFeedingFlag = 0;
+            productSn.setText(productSnFeeding.getText());
+            productSnFeeding.setText("");
+            setMenuStatus("工件已上料到设备", 0);
+        }
+
+        if (tjFlag == 0 && retRunning) {
+            tjFlag = 1;
+        }
         if (tjFlag == 1 && retRunning) {
             tjFlag = 2;
             writeAllowFeeding(false);
             writeAllowBlanking(false);
             setMenuStatus("工件加工中", 0);
-        } else if (tjFlag == 2 && retBlanking) {
-            finishWork();
         }
+
+        handleBlankingRequest(retBlanking, retAllowBlanking);
     }
 
     // 取码并校验:通过后清掉码槽里的码,写 MES允许上料
@@ -423,7 +495,7 @@ public class WorkJPanelCnc extends JPanel {
         try {
             String sn = sourceSlot.getSn();
             if (sn.isEmpty()) {
-                setMenuStatus(front ? "暂无扫码结果,等待扫码" : "反面待上料码为空,等待正面下料", -1);
+                setMenuStatus("暂无扫码结果,等待扫码", -1);
                 return;
             }
             productSnFeeding.setText(sn);
@@ -443,8 +515,49 @@ public class WorkJPanelCnc extends JPanel {
         }
     }
 
-    // 请求下料:上传结果,有存码目标时成功后存码
-    private void finishWork() {
+    /**
+     * 下料必须等待 pcresult 成功后再允许。失败时保留加工码,下一轮自动重试。
+     */
+    private void handleBlankingRequest(boolean retBlanking, boolean retAllowBlanking) {
+        String sn = productSn.getText().trim();
+        if (!retBlanking) {
+            if (retAllowBlanking) {
+                writeAllowBlanking(false);
+            }
+            completionSubmittedSn = "";
+            return;
+        }
+
+        if (sn.isEmpty()) {
+            completionSubmittedSn = "";
+            if (!retAllowBlanking) {
+                writeAllowBlanking(true);
+            }
+            return;
+        }
+
+        // 防止上一次遗留的允许信号绕过本次工件完成接口。
+        if (retAllowBlanking && !sn.equals(completionSubmittedSn)) {
+            if (!writeAllowBlanking(false)) {
+                setMenuStatus("清除旧下料允许失败,暂不上传", -1);
+                return;
+            }
+        }
+
+        if (!sn.equals(completionSubmittedSn)) {
+            if (!upload(sn)) {
+                return;
+            }
+            completionSubmittedSn = sn;
+        }
+
+        if (writeAllowBlanking(true)) {
+            resetBlanking("工件结果已提交,允许下料");
+        }
+    }
+
+    // 旧 130 -> 135 共享码流转实现,默认关闭但保留以便回退。
+    private void finishWorkLegacy() {
         String sn = productSn.getText().trim();
         if (targetSlot == null) {
             if (upload(sn)) {
@@ -454,7 +567,7 @@ public class WorkJPanelCnc extends JPanel {
             return;
         }
         if (!targetSlot.tryLock()) {
-            return; // 反面正在取码或其他正面机正在存码,下一轮再试
+            return;
         }
         try {
             if (!targetSlot.isEmpty()) {
@@ -471,14 +584,15 @@ public class WorkJPanelCnc extends JPanel {
         }
     }
 
-    // 上传加工结果,失败停在 tjFlag=3 等人工刷新(与原逻辑一致)
+    // 上传加工结果,失败保留加工码并在下一轮重试。
     private boolean upload(String sn) {
         tjFlag = 3;
-        tjStatus = 1;
+        tjStatus = 0;
         setMenuStatus("工件加工结束,结果上传中", 0);
         log.info("<{}{}>上传加工结果 sn={}", oprno, pos, sn);
         JSONObject retObj = DataUtil.sendQuality(sn, oprno + pos, "OK", MesClient.user_menu.getText());
         if (isOk(retObj)) {
+            tjStatus = 1;
             return true;
         }
         setMenuStatus(failMsg(retObj), -1);
@@ -488,17 +602,54 @@ public class WorkJPanelCnc extends JPanel {
     public void resetBlanking(String msg) {
         tjFlag = 0;
         tjStatus = 0;
+        completionSubmittedSn = "";
         productSn.setText("");
         setMenuStatus(msg, 0);
     }
 
     public void resetFeeding() {
         tjFeedingFlag = 0;
+        op135ScanOwnerRegistered = false;
         productSnFeeding.setText("");
         writeAllowFeeding(false);
         setMenuStatus("等待请求上料", 0);
     }
 
+    /** 绑定 OP135 独立扫码握手,用于登记扫码归属。 */
+    public void setScanHandshake(DirectScanHandshake scanHandshake) {
+        this.scanHandshake = scanHandshake;
+    }
+
+    /**
+     * 接收独立扫码结果。扫码、MES 校验和 PLC 写码均已在握手线程完成。
+     */
+    public synchronized boolean acceptScannedSn(String sn) {
+        String value = nvl(sn).trim();
+        if (value.isEmpty()) {
+            setMenuStatus("独立扫码结果为空,未接收", -1);
+            return false;
+        }
+        if (!productSn.getText().trim().isEmpty() && !productSn.getText().trim().equals(value)) {
+            setMenuStatus("当前加工码" + productSn.getText().trim() + "尚未下料,不能接收新码", -1);
+            return false;
+        }
+
+        lastSn = value;
+        if (running || atDevice || tjFlag >= 1) {
+            productSn.setText(value);
+            productSnFeeding.setText("");
+            tjFeedingFlag = 0;
+            tjFlag = Math.max(tjFlag, 1);
+            setMenuStatus("独立扫码码已写入加工:" + value, 0);
+        } else {
+            productSnFeeding.setText(value);
+            tjFeedingFlag = 1;
+            setMenuStatus("独立扫码码已写入上料:" + value, 0);
+        }
+        log.info("<{}{}>接收独立扫码码 {}", oprno, pos, value);
+        return true;
+    }
+
     private static boolean isOk(JSONObject retObj) {
         return retObj != null && "true".equalsIgnoreCase(String.valueOf(retObj.get("result")));
     }
@@ -521,12 +672,12 @@ public class WorkJPanelCnc extends JPanel {
 
     // 与设备交互 -----------------------------------------------------------------------------------------
 
-    public void writeAllowFeeding(boolean b) {
-        writeBoolean(plcDb + ".0.4", b);
+    public boolean writeAllowFeeding(boolean b) {
+        return writeBoolean(plcDb + ".0.4", b);
     }
 
-    public void writeAllowBlanking(boolean b) {
-        writeBoolean(plcDb + ".0.5", b);
+    public boolean writeAllowBlanking(boolean b) {
+        return writeBoolean(plcDb + ".0.5", b);
     }
 
     public boolean readBoolean(String addr) {

+ 24 - 13
src/com/mes/ui/MesClient.java

@@ -26,6 +26,9 @@ public class MesClient extends JFrame {
 
     public static final Logger log =  LoggerFactory.getLogger(MesClient.class);
 
+    // 旧 130 -> 135 共享码流转页面与入口保留但默认隐藏、停用。
+    private static final boolean LEGACY_SHARED_FLOW_ENABLED = false;
+
     public static int mes_auth = 0; // 权限级别 0=无权限 1=操作工人 2=管理员
     public static String mes_gw = ""; // 工位号
     public static String mes_gw_des = ""; // 工位名称
@@ -60,10 +63,10 @@ public class MesClient extends JFrame {
     // OP135 入口独立扫码枪
     public static TCPClient directScanClient;
 
-    // 码槽:正面扫码码按 PLC 分开(本 PLC 扫码存、本 PLC 正面机取),反面待上料码(正面下料存、反面取)
+    // 码槽:OP130 的扫码码按 PLC 分开;OP135 不再读取共享反面待上料码。
     public static SnSlot frontSlot92;
     public static SnSlot frontSlot93;
-    public static SnSlot backSlot;
+    public static SnSlot backSlot; // 旧共享码槽,仅隐藏实现保留
 
     // 工位表:工位号, 子工位, PLC, DB
     public static final String[][] STATIONS = {
@@ -83,6 +86,7 @@ public class MesClient extends JFrame {
     public static WorkJPanelScan workJPanelScan92; // 92 DB7010(PLC 发 1、2 号枪)
     public static WorkJPanelScan workJPanelScan93; // 93 DB7010(PLC 发 3 号枪)
     public static DirectScanHandshake directScanHandshake; // 93 DB7020 OP135 独立扫码
+    public static DirectScanMonitorPanel directScanMonitor64; // 64 扫码结果只读监控
     public static WorkJPanelBackSlot workJPanelBackSlot;
 
     // 扫码手动输入开关(参考 auto3,模拟扫码枪输入),每次启动默认关闭
@@ -310,26 +314,32 @@ public class MesClient extends JFrame {
         // 码槽要在工位面板之前创建,面板构造时会引用(92 沿用原缓存 key)
         frontSlot92 = new SnSlot("正面扫码92", "slot_front_scan");
         frontSlot93 = new SnSlot("正面扫码93", "slot_front_scan93");
-        backSlot = new SnSlot("反面待上料码", "slot_back_feeding");
+        if (LEGACY_SHARED_FLOW_ENABLED) {
+            backSlot = new SnSlot("反面待上料码", "slot_back_feeding");
+        }
+
+        if (directScanClient != null) {
+            directScanHandshake = new DirectScanHandshake(
+                    WorkJPanelCnc.PLC_93, directScanClient);
+        }
+        directScanMonitor64 = new DirectScanMonitorPanel(directScanHandshake);
 
         for (String[] s : STATIONS) {
             boolean front = "OP130".equals(s[0]);
             boolean on93 = WorkJPanelCnc.PLC_93.equals(s[2]);
-            // 正面取本 PLC 扫码码,反面取反面待上料码
-            SnSlot source = !front ? backSlot : (on93 ? frontSlot93 : frontSlot92);
-            // 下料存码:OP130A-F 统一存反面待上料码;反面不存
-            SnSlot target = front ? backSlot : null;
+            // 正面取本 PLC 扫码码;反面必须等独立扫码握手回填。
+            SnSlot source = front ? (on93 ? frontSlot93 : frontSlot92) : null;
+            // 旧共享存码入口默认关闭。
+            SnSlot target = LEGACY_SHARED_FLOW_ENABLED && front ? backSlot : null;
             WorkJPanelCnc panel = new WorkJPanelCnc(s[0], s[1], s[2], s[3], source, target);
+            if (!front && directScanHandshake != null) {
+                panel.setScanHandshake(directScanHandshake);
+            }
             (front ? op130Panels : op135Panels).add(panel);
         }
         // 92 推码:1 号枪 -> OP190 上料口1 DB7020.1034,2 号枪 -> OP190 上料口2 DB7020.1290
         workJPanelScan92 = new WorkJPanelScan(WorkJPanelCnc.PLC_92, frontSlot92, "DB7020.1034", "DB7020.1290");
         workJPanelScan93 = new WorkJPanelScan(WorkJPanelCnc.PLC_93, frontSlot93);
-        if (directScanClient != null) {
-            directScanHandshake = new DirectScanHandshake(
-                    WorkJPanelCnc.PLC_93, directScanClient);
-        }
-        workJPanelBackSlot = new WorkJPanelBackSlot();
 
         // 每页 4 格,布局与原来一致
         tabbedPane.addTab("OP130正面:A-D", null,
@@ -338,7 +348,8 @@ public class MesClient extends JFrame {
                 gridTab(op130Panels.get(4), op130Panels.get(5), workJPanelScan92, workJPanelScan93), null);
         tabbedPane.addTab("OP135反面:A-D", null,
                 gridTab(op135Panels.get(0), op135Panels.get(1), op135Panels.get(2), op135Panels.get(3)), null);
-        tabbedPane.addTab("反面待上料码", null, gridTab(workJPanelBackSlot), null);
+        tabbedPane.addTab("OP135独立扫码:64", null, gridTab(directScanMonitor64), null);
+        // “反面待上料码”页为旧共享流转入口,默认隐藏;实现类和旧缓存保留。
         tabbedPane.setEnabledAt(0, true);
 
         // ========== 工作记录 Tab:每个子工位一个Tab + 所有工位 ==========