hfy 1 неделя назад
Родитель
Сommit
e580a80d9b

+ 1 - 0
.classpath

@@ -21,4 +21,5 @@
 	<classpathentry kind="lib" path="lib/sqlite-jdbc-3.36.0.3.jar"/>
 	<classpathentry kind="lib" path="lib/commons-codec-1.15.jar"/>
 	<classpathentry kind="lib" path="lib/fastjson2-2.0.16.jar"/>
+	<classpathentry kind="lib" path="lib/jSerialComm-2.6.2.jar"/>
 </classpath>

+ 35 - 0
src/com/mes/ui/DataUtil.java

@@ -10,6 +10,7 @@ import java.io.*;
 import java.net.HttpURLConnection;
 import java.net.MalformedURLException;
 import java.net.URL;
+import java.net.URLEncoder;
 import java.util.ArrayList;
 import java.util.List;
 
@@ -85,6 +86,40 @@ public class DataUtil {
         }
     }
 
+    public static JSONObject sendQuality(String sn, String ret, String user, String deviceResult, String deviceData) {
+        try {
+            String mes_server_ip = MesClient.mes_server_ip;
+            String oprno = MesClient.mes_gw == null ? "" : MesClient.mes_gw.trim();
+            String lineSn = MesClient.mes_line_sn == null ? "" : MesClient.mes_line_sn.trim();
+            String url = "http://" + mes_server_ip + ":8980/js/a/mes/mesProductRecord/pcresult";
+            String params = "__ajax=json&oprno=" + encode(oprno)
+                    + "&lineSn=" + encode(lineSn)
+                    + "&sn=" + encode(sn)
+                    + "&result=" + encode(ret)
+                    + "&ucode=" + encode(user)
+                    + "&deviceType=UT5310"
+                    + "&deviceResult=" + encode(deviceResult)
+                    + "&deviceData=" + encode(deviceData);
+            log.info("params=" + params);
+            String result = doPost(url, params);
+            log.info("result=" + result);
+
+            if (result == null || result.trim().isEmpty() || result.equalsIgnoreCase("false")) {
+                return null;
+            } else {
+                JdbcUtils.insertData(oprno, "100000", params, "MQDW", sn);
+                return JSONObject.parseObject(result);
+            }
+        } catch (Exception e) {
+            log.info("e=" + e.getMessage());
+            return null;
+        }
+    }
+
+    private static String encode(String value) throws UnsupportedEncodingException {
+        return URLEncoder.encode(value == null ? "" : value, "UTF-8");
+    }
+
     public static String rightPad(final String str, final int size) {
         if (str == null) {
             return null;

+ 114 - 0
src/com/mes/ui/MesClient.java

@@ -8,6 +8,8 @@ import com.mes.util.HttpUtils;
 import com.mes.util.JdbcUtils;
 import com.mes.util.Op310PlcPoint;
 import com.mes.util.PlcService;
+import com.mes.util.Ut5310ScpiService;
+import com.mes.util.Ut5310TestResult;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import javax.swing.*;
@@ -37,6 +39,7 @@ public class MesClient extends JFrame {
     public static String mes_gw_des = ""; // 工位名称
     public static String mes_server_ip = ""; // 服务器IP地址
     public static int mes_heart_icon_cycle = 1;
+    public static boolean mes_ut5310_enable = false;
     public static String mes_line_sn = ""; // 产线编号
     public static String mes_plc_ip = "192.168.0.3"; // PLC IP地址
 
@@ -45,6 +48,7 @@ public class MesClient extends JFrame {
     public static final int PLC_PHASE_WAIT_REQUEST = 2;
     public static final int PLC_PHASE_WAIT_OPERATOR = 3;
     public static final int PLC_PHASE_WAIT_READY = 4;
+    public static final int PLC_PHASE_WAIT_UT5310 = 5;
 
     //session
     public static String sessionid = "";
@@ -109,6 +113,7 @@ public class MesClient extends JFrame {
     private static boolean lastReady = false;
     private static boolean lastError = false;
     private static int mesBitlifeCounter = 0;
+    private static final ExecutorService ut5310Executor = Executors.newSingleThreadExecutor();
 
     public static void main(String[] args) {
 
@@ -157,6 +162,16 @@ public class MesClient extends JFrame {
         mes_gw =  pro.getProperty("mes.gw");
         mes_line_sn = pro.getProperty("mes.line_sn");
         String plcIp = pro.getProperty("mes.plc_ip");
+        mes_ut5310_enable = Boolean.parseBoolean(pro.getProperty("mes.ut5310_enable", "false"));
+        Ut5310ScpiService.configure(
+                pro.getProperty("mes.ut5310_port", "COM1"),
+                getIntProperty(pro, "mes.ut5310_baud_rate", 9600),
+                getIntProperty(pro, "mes.ut5310_data_bits", 8),
+                getIntProperty(pro, "mes.ut5310_stop_bits", 1),
+                pro.getProperty("mes.ut5310_parity", "NONE"),
+                getIntProperty(pro, "mes.ut5310_read_timeout_ms", 1000),
+                getIntProperty(pro, "mes.ut5310_test_timeout_ms", 60000),
+                getIntProperty(pro, "mes.ut5310_fetch_interval_ms", 500));
 
         if (mes_gw == null) {
             mes_gw = "";
@@ -185,6 +200,18 @@ public class MesClient extends JFrame {
         log.info(mes_gw + ";" + mes_gw_des + ";" + mes_server_ip + ";");
     }
 
+    private static int getIntProperty(Properties pro, String name, int defaultValue) {
+        try {
+            String value = pro.getProperty(name);
+            if (value == null || value.trim().isEmpty()) {
+                return defaultValue;
+            }
+            return Integer.parseInt(value.trim());
+        } catch (Exception e) {
+            return defaultValue;
+        }
+    }
+
     public static void applyOpConfig(String op, String opName, String ip) {
         if (op != null) {
             mes_gw = op.trim();
@@ -609,12 +636,23 @@ public class MesClient extends JFrame {
             if (plcPhase == PLC_PHASE_WAIT_REQUEST) {
                 if (requestResult && !lastRequestResult) {
                     PlcService.setStart(false);
+                    if (mes_ut5310_enable) {
+                        plcPhase = PLC_PHASE_WAIT_UT5310;
+                        String sn = product_sn == null ? "" : product_sn.getText().trim();
+                        SwingUtilities.invokeLater(() -> {
+                            finish_ok_bt.setEnabled(false);
+                            finish_ng_bt.setEnabled(false);
+                            setMenuStatus("工装到位,开始绝缘耐压测试", 0);
+                        });
+                        startUt5310TestAsync(sn);
+                    } else {
                     plcPhase = PLC_PHASE_WAIT_OPERATOR;
                     SwingUtilities.invokeLater(() -> {
                         finish_ok_bt.setEnabled(true);
                         finish_ng_bt.setEnabled(true);
                         setMenuStatus("设备加工完成,请确认OK/NG", 0);
                     });
+                    }
                 }
             } else if (plcPhase == PLC_PHASE_WAIT_READY) {
                 if (ready && !lastReady) {
@@ -637,6 +675,82 @@ public class MesClient extends JFrame {
         }
     }
 
+    private static void startUt5310TestAsync(String sn) {
+        ut5310Executor.submit(() -> {
+            if (sn == null || sn.trim().isEmpty()) {
+                submitUt5310Result("", new Ut5310TestResult(false, "ERROR", "empty sn"));
+                return;
+            }
+            try {
+                SwingUtilities.invokeLater(() -> setMenuStatus("绝缘耐压测试中...", 0));
+                Ut5310TestResult result = Ut5310ScpiService.startAndFetchResult();
+                submitUt5310Result(sn, result);
+            } catch (Exception e) {
+                log.info("UT5310测试异常: {}", e.getMessage());
+                submitUt5310Result(sn, new Ut5310TestResult(false, "ERROR", e.getMessage()));
+            }
+        });
+    }
+
+    private static boolean submitUt5310Result(String sn, Ut5310TestResult testResult) {
+        if (plcPhase != PLC_PHASE_WAIT_UT5310) {
+            SwingUtilities.invokeLater(() -> setMenuStatus("当前状态不允许提交绝缘耐压结果", -1));
+            return false;
+        }
+        if (!PlcService.ensureConnected()) {
+            SwingUtilities.invokeLater(() -> {
+                setMenuStatus("PLC未连接,请检查网络", -1);
+                updatePlcStatus(false);
+            });
+            return false;
+        }
+        SwingUtilities.invokeLater(() -> updatePlcStatus(true));
+
+        boolean isOk = testResult != null && testResult.isOk();
+        String mesResult = isOk ? "OK" : "NG";
+        boolean plcWriteOk = isOk ? PlcService.setTestOk(true) : PlcService.setTestNg(true);
+        if (!plcWriteOk) {
+            SwingUtilities.invokeLater(() -> setMenuStatus("写入PLC绝缘耐压结果失败", -1));
+            return false;
+        }
+
+        JSONObject retObj = DataUtil.sendQuality(sn, mesResult, user20,
+                testResult == null ? "" : testResult.getJudge(),
+                testResult == null ? "" : testResult.getRawResponse());
+        if (retObj == null) {
+            if (isOk) {
+                PlcService.setTestOk(false);
+            } else {
+                PlcService.setTestNg(false);
+            }
+            SwingUtilities.invokeLater(() -> setMenuStatus("绝缘耐压结果上传失败,请重试", -1));
+            return false;
+        }
+        if (retObj.get("result") != null && retObj.get("result").toString().equalsIgnoreCase("true")) {
+            plcPhase = PLC_PHASE_WAIT_READY;
+            SwingUtilities.invokeLater(() -> {
+                finish_ok_bt.setEnabled(false);
+                finish_ng_bt.setEnabled(false);
+                setMenuStatus("绝缘耐压结果已提交,等待设备复位...", 0);
+            });
+            return true;
+        }
+
+        if (isOk) {
+            PlcService.setTestOk(false);
+        } else {
+            PlcService.setTestNg(false);
+        }
+        SwingUtilities.invokeLater(() -> {
+            if (retObj.get("result") == null) {
+                setMenuStatus("绝缘耐压结果上传失败,请重试", -1);
+            } else if (retObj.get("result").toString().equalsIgnoreCase("false")) {
+                setMenuStatus(retObj.getString("message"), -1);
+            }
+        });
+        return false;
+    }
+
     private static boolean submitPlcResult(String sn, String result, boolean isOk) {
         if (plcPhase != PLC_PHASE_WAIT_OPERATOR) {
             setMenuStatus("当前状态不允许提交结果", -1);

+ 227 - 0
src/com/mes/util/Ut5310ScpiService.java

@@ -0,0 +1,227 @@
+package com.mes.util;
+
+import com.fazecast.jSerialComm.SerialPort;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+
+public class Ut5310ScpiService {
+
+    public static final Logger log = LoggerFactory.getLogger(Ut5310ScpiService.class);
+
+    private static final Charset COMMAND_CHARSET = StandardCharsets.US_ASCII;
+    private static final String START_COMMAND = "FUNC:START";
+    private static final String FETCH_COMMAND = "FETCh?";
+
+    private static String portName = "COM1";
+    private static int baudRate = 9600;
+    private static int dataBits = 8;
+    private static int stopBits = SerialPort.ONE_STOP_BIT;
+    private static int parity = SerialPort.NO_PARITY;
+    private static int readTimeoutMs = 1000;
+    private static int testTimeoutMs = 60000;
+    private static int fetchIntervalMs = 500;
+
+    private static SerialPort serialPort;
+    private static InputStream inputStream;
+    private static OutputStream outputStream;
+    private static volatile boolean connected = false;
+
+    public static synchronized void configure(String port, int baud, int data, int stop, String parityName,
+                                              int readTimeout, int testTimeout, int fetchInterval) {
+        if (port != null && !port.trim().isEmpty()) {
+            portName = port.trim();
+        }
+        if (baud > 0) {
+            baudRate = baud;
+        }
+        if (data > 0) {
+            dataBits = data;
+        }
+        stopBits = toStopBits(stop);
+        parity = toParity(parityName);
+        if (readTimeout > 0) {
+            readTimeoutMs = readTimeout;
+        }
+        if (testTimeout > 0) {
+            testTimeoutMs = testTimeout;
+        }
+        if (fetchInterval > 0) {
+            fetchIntervalMs = fetchInterval;
+        }
+    }
+
+    public static synchronized boolean isConnected() {
+        return connected;
+    }
+
+    public static synchronized boolean connect() {
+        disconnect();
+        try {
+            serialPort = SerialPort.getCommPort(portName);
+            serialPort.setComPortParameters(baudRate, dataBits, stopBits, parity);
+            serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, readTimeoutMs, readTimeoutMs);
+            if (!serialPort.openPort()) {
+                connected = false;
+                log.info("UT5310 open port failed: {}", portName);
+                return false;
+            }
+            inputStream = serialPort.getInputStream();
+            outputStream = serialPort.getOutputStream();
+            connected = true;
+            log.info("UT5310 connected: {} {}bps", portName, baudRate);
+            return true;
+        } catch (Exception e) {
+            connected = false;
+            log.info("UT5310 connect failed: {}", e.getMessage());
+            disconnect();
+            return false;
+        }
+    }
+
+    public static synchronized void disconnect() {
+        connected = false;
+        closeQuietly(inputStream);
+        closeQuietly(outputStream);
+        inputStream = null;
+        outputStream = null;
+        if (serialPort != null) {
+            try {
+                serialPort.closePort();
+            } catch (Exception ignored) {
+            }
+            serialPort = null;
+        }
+    }
+
+    public static synchronized boolean ensureConnected() {
+        if (connected && serialPort != null && serialPort.isOpen()) {
+            return true;
+        }
+        return connect();
+    }
+
+    public static synchronized Ut5310TestResult startAndFetchResult() throws IOException {
+        if (!ensureConnected()) {
+            throw new IOException("UT5310 not connected");
+        }
+
+        drainInput();
+        writeCommand(START_COMMAND);
+        log.info("UT5310 command sent: {}", START_COMMAND);
+
+        long deadline = System.currentTimeMillis() + testTimeoutMs;
+        String lastResponse = "";
+        while (System.currentTimeMillis() < deadline) {
+            sleep(fetchIntervalMs);
+            writeCommand(FETCH_COMMAND);
+            lastResponse = readResponse();
+            log.info("UT5310 fetch response: {}", lastResponse);
+
+            Ut5310TestResult result = parseFetchResult(lastResponse);
+            if (result != null) {
+                return result;
+            }
+        }
+        throw new IOException("UT5310 test timeout, last response: " + lastResponse);
+    }
+
+    public static Ut5310TestResult parseFetchResult(String response) {
+        if (response == null) {
+            return null;
+        }
+        String raw = response.trim();
+        if (raw.isEmpty()) {
+            return null;
+        }
+        String normalized = raw.toUpperCase();
+        if (normalized.contains("FAIL") || normalized.contains("NG")) {
+            return new Ut5310TestResult(false, "FAIL", raw);
+        }
+        if (normalized.contains("PASS") || normalized.equals("OK") || normalized.startsWith("OK,")) {
+            return new Ut5310TestResult(true, "PASS", raw);
+        }
+        return null;
+    }
+
+    private static void writeCommand(String command) throws IOException {
+        outputStream.write((command + "\n").getBytes(COMMAND_CHARSET));
+        outputStream.flush();
+    }
+
+    private static String readResponse() throws IOException {
+        StringBuilder response = new StringBuilder();
+        byte[] buffer = new byte[256];
+        long deadline = System.currentTimeMillis() + readTimeoutMs;
+        while (System.currentTimeMillis() < deadline) {
+            int len = inputStream.read(buffer);
+            if (len > 0) {
+                response.append(new String(buffer, 0, len, COMMAND_CHARSET));
+                if (response.indexOf("\n") >= 0) {
+                    break;
+                }
+            } else if (response.length() > 0) {
+                break;
+            }
+        }
+        return response.toString().trim();
+    }
+
+    private static void drainInput() {
+        try {
+            while (inputStream != null && inputStream.available() > 0) {
+                inputStream.read();
+            }
+        } catch (Exception ignored) {
+        }
+    }
+
+    private static int toStopBits(int stop) {
+        if (stop == 2) {
+            return SerialPort.TWO_STOP_BITS;
+        }
+        return SerialPort.ONE_STOP_BIT;
+    }
+
+    private static int toParity(String parityName) {
+        if (parityName == null) {
+            return SerialPort.NO_PARITY;
+        }
+        String value = parityName.trim().toUpperCase();
+        if ("ODD".equals(value)) {
+            return SerialPort.ODD_PARITY;
+        }
+        if ("EVEN".equals(value)) {
+            return SerialPort.EVEN_PARITY;
+        }
+        return SerialPort.NO_PARITY;
+    }
+
+    private static void sleep(int millis) throws IOException {
+        try {
+            Thread.sleep(millis);
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            throw new IOException("UT5310 test interrupted", e);
+        }
+    }
+
+    private static void closeQuietly(Object closeable) {
+        if (closeable == null) {
+            return;
+        }
+        try {
+            if (closeable instanceof InputStream) {
+                ((InputStream) closeable).close();
+            } else if (closeable instanceof OutputStream) {
+                ((OutputStream) closeable).close();
+            }
+        } catch (Exception ignored) {
+        }
+    }
+}

+ 26 - 0
src/com/mes/util/Ut5310TestResult.java

@@ -0,0 +1,26 @@
+package com.mes.util;
+
+public class Ut5310TestResult {
+
+    private final boolean ok;
+    private final String judge;
+    private final String rawResponse;
+
+    public Ut5310TestResult(boolean ok, String judge, String rawResponse) {
+        this.ok = ok;
+        this.judge = judge;
+        this.rawResponse = rawResponse;
+    }
+
+    public boolean isOk() {
+        return ok;
+    }
+
+    public String getJudge() {
+        return judge;
+    }
+
+    public String getRawResponse() {
+        return rawResponse;
+    }
+}

+ 10 - 1
src/resources/config/config.properties

@@ -3,4 +3,13 @@
 #mes.server_ip=localhost
 #mes.server_ip=192.168.20.99
 mes.line_sn=XT
-mes.plc_ip=192.168.0.3
+mes.plc_ip=192.168.0.3
+mes.ut5310_enable=true
+mes.ut5310_port=COM1
+mes.ut5310_baud_rate=9600
+mes.ut5310_data_bits=8
+mes.ut5310_stop_bits=1
+mes.ut5310_parity=NONE
+mes.ut5310_read_timeout_ms=1000
+mes.ut5310_test_timeout_ms=60000
+mes.ut5310_fetch_interval_ms=500