hou 1 Minggu lalu
melakukan
8e95947edc
100 mengubah file dengan 3566 tambahan dan 0 penghapusan
  1. 24 0
      .classpath
  2. 7 0
      .gitignore
  3. 0 0
      .lock
  4. 0 0
      .lock2
  5. 17 0
      .project
  6. 2 0
      image/.gitignore
  7. TEMPAT SAMPAH
      image/background.png
  8. TEMPAT SAMPAH
      image/bg/a_side.png
  9. TEMPAT SAMPAH
      image/bg/b_side.png
  10. TEMPAT SAMPAH
      image/bg/bar_add.png
  11. TEMPAT SAMPAH
      image/bg/bar_bookmark.png
  12. TEMPAT SAMPAH
      image/bg/bar_cmd_go.png
  13. TEMPAT SAMPAH
      image/bg/bar_edit.png
  14. TEMPAT SAMPAH
      image/bg/bar_pause.png
  15. TEMPAT SAMPAH
      image/bg/bar_sampling.png
  16. TEMPAT SAMPAH
      image/bg/bar_setting.png
  17. TEMPAT SAMPAH
      image/bg/bar_stop.png
  18. TEMPAT SAMPAH
      image/bg/close_bt.png
  19. TEMPAT SAMPAH
      image/bg/company_setting_logo.png
  20. TEMPAT SAMPAH
      image/bg/delete.png
  21. TEMPAT SAMPAH
      image/bg/department_setting_logo.png
  22. TEMPAT SAMPAH
      image/bg/download.png
  23. TEMPAT SAMPAH
      image/bg/equipment_setting_logo.png
  24. TEMPAT SAMPAH
      image/bg/gj_001_1_20.png
  25. TEMPAT SAMPAH
      image/bg/gj_001_21_40.png
  26. TEMPAT SAMPAH
      image/bg/gj_001_41_60.png
  27. TEMPAT SAMPAH
      image/bg/green_dot.png
  28. TEMPAT SAMPAH
      image/bg/grey_dot.png
  29. TEMPAT SAMPAH
      image/bg/icon.png
  30. TEMPAT SAMPAH
      image/bg/inductance_logo.png
  31. TEMPAT SAMPAH
      image/bg/insulation_logo.png
  32. TEMPAT SAMPAH
      image/bg/login.png
  33. TEMPAT SAMPAH
      image/bg/logo.png
  34. TEMPAT SAMPAH
      image/bg/logoff.png
  35. TEMPAT SAMPAH
      image/bg/menu_data_analysis.png
  36. TEMPAT SAMPAH
      image/bg/menu_data_preprocess.png
  37. TEMPAT SAMPAH
      image/bg/menu_file.png
  38. TEMPAT SAMPAH
      image/bg/menu_setting.png
  39. TEMPAT SAMPAH
      image/bg/min_bt.png
  40. TEMPAT SAMPAH
      image/bg/ng_bg.png
  41. TEMPAT SAMPAH
      image/bg/ok_bg.png
  42. TEMPAT SAMPAH
      image/bg/open_file.png
  43. TEMPAT SAMPAH
      image/bg/refresh.png
  44. TEMPAT SAMPAH
      image/bg/reset_logo.png
  45. TEMPAT SAMPAH
      image/bg/resistance_logo.png
  46. TEMPAT SAMPAH
      image/bg/save_bg.png
  47. TEMPAT SAMPAH
      image/bg/scan_barcode.png
  48. TEMPAT SAMPAH
      image/bg/tree_folder_icon.png
  49. TEMPAT SAMPAH
      image/bg/tree_leaf_icon.png
  50. TEMPAT SAMPAH
      image/bg/user.png
  51. TEMPAT SAMPAH
      image/bg/vertical_line.png
  52. TEMPAT SAMPAH
      image/bg/zoom_in.png
  53. TEMPAT SAMPAH
      image/bg/zoom_out.png
  54. TEMPAT SAMPAH
      image/close_bt.png
  55. 0 0
      image/cmd.txt
  56. TEMPAT SAMPAH
      image/icon.ico
  57. TEMPAT SAMPAH
      image/info_bt.png
  58. TEMPAT SAMPAH
      image/min_bt.png
  59. TEMPAT SAMPAH
      lib/commons-codec-1.15.jar
  60. TEMPAT SAMPAH
      lib/fastjson2-2.0.16.jar
  61. TEMPAT SAMPAH
      lib/gson-2.10.jar
  62. TEMPAT SAMPAH
      lib/iot-communication-1.4.4.jar
  63. TEMPAT SAMPAH
      lib/jSerialComm-2.6.2.jar
  64. TEMPAT SAMPAH
      lib/jfreechart-1.5.4.jar
  65. TEMPAT SAMPAH
      lib/jshortcut-0.4-oberzalek.jar
  66. TEMPAT SAMPAH
      lib/kotlin-stdlib-1.8.10.jar
  67. TEMPAT SAMPAH
      lib/logback-classic-1.2.13.jar
  68. TEMPAT SAMPAH
      lib/logback-core-1.2.13.jar
  69. TEMPAT SAMPAH
      lib/netty-all-4.1.48.Final.jar
  70. TEMPAT SAMPAH
      lib/okhttp-4.10.0.jar
  71. TEMPAT SAMPAH
      lib/okio-jvm-3.3.0.jar
  72. TEMPAT SAMPAH
      lib/s7connector-2.1.jar
  73. TEMPAT SAMPAH
      lib/slf4j-api-1.7.36.jar
  74. TEMPAT SAMPAH
      lib/sqlite-jdbc-3.36.0.3.jar
  75. 3 0
      src/META-INF/MANIFEST.MF
  76. 10 0
      src/com/mes/component/CallFromJs.java
  77. 57 0
      src/com/mes/component/MesRadio.java
  78. 44 0
      src/com/mes/component/MesWebView.java
  79. 30 0
      src/com/mes/component/MyDialog.java
  80. 90 0
      src/com/mes/netty/MesMsgUtils.java
  81. 63 0
      src/com/mes/netty/NettyClient.java
  82. 85 0
      src/com/mes/netty/NettyClientHandler.java
  83. 73 0
      src/com/mes/netty/ProtocolParam.java
  84. 168 0
      src/com/mes/netty/XDecoder.java
  85. 58 0
      src/com/mes/ui/BindMaterialResp.java
  86. 334 0
      src/com/mes/ui/DataUtil.java
  87. 85 0
      src/com/mes/ui/LockUtil.java
  88. 210 0
      src/com/mes/ui/LoginFarme.java
  89. 1035 0
      src/com/mes/ui/MesClient.java
  90. 129 0
      src/com/mes/ui/MesRevice.java
  91. 61 0
      src/com/mes/ui/OprnoUtil.java
  92. 558 0
      src/com/mes/ui/S7Util.java
  93. 43 0
      src/com/mes/ui/TableCellEditorButton.java
  94. 14 0
      src/com/mes/ui/TableCellRendererButton.java
  95. 11 0
      src/com/mes/util/Base64Utils.java
  96. 32 0
      src/com/mes/util/DateLocalUtils.java
  97. 168 0
      src/com/mes/util/Db9051Test.java
  98. 92 0
      src/com/mes/util/Db9052Test.java
  99. 63 0
      src/com/mes/util/ErrorMsg.java
  100. 0 0
      src/com/mes/util/FswParamReq.java

+ 24 - 0
.classpath

@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
+		<attributes>
+			<attribute name="module" value="true"/>
+		</attributes>
+	</classpathentry>
+    <classpathentry kind="src" path="image"/>
+	<classpathentry excluding="resources/" kind="src" path="src"/>
+	<classpathentry kind="src" path="src/resources"/>
+	<classpathentry kind="output" path="bin"/>
+	<classpathentry kind="lib" path="lib/s7connector-2.1.jar"/>
+	<classpathentry kind="lib" path="lib/slf4j-api-2.0.6.jar"/>
+	<classpathentry kind="lib" path="lib/okhttp-4.10.0.jar"/>
+	<classpathentry kind="lib" path="lib/kotlin-stdlib-1.8.10.jar"/>
+	<classpathentry kind="lib" path="lib/okio-jvm-3.3.0.jar"/>
+	<classpathentry kind="lib" path="lib/gson-2.10.jar"/>
+	<classpathentry kind="lib" path="lib/jfreechart-1.5.4.jar"/>
+	<classpathentry kind="lib" path="lib/jshortcut-0.4-oberzalek.jar"/>
+	<classpathentry kind="lib" path="lib/netty-all-4.1.48.Final.jar"/>
+	<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"/>
+</classpath>

+ 7 - 0
.gitignore

@@ -0,0 +1,7 @@
+.idea
+.settings
+classes
+bin
+out
+*.db
+*.iml

+ 0 - 0
.lock


+ 0 - 0
.lock2


+ 17 - 0
.project

@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>mesclient-XT-OP180</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+	</natures>
+</projectDescription>

+ 2 - 0
image/.gitignore

@@ -0,0 +1,2 @@
+META-INF
+_system~.ini

TEMPAT SAMPAH
image/background.png


TEMPAT SAMPAH
image/bg/a_side.png


TEMPAT SAMPAH
image/bg/b_side.png


TEMPAT SAMPAH
image/bg/bar_add.png


TEMPAT SAMPAH
image/bg/bar_bookmark.png


TEMPAT SAMPAH
image/bg/bar_cmd_go.png


TEMPAT SAMPAH
image/bg/bar_edit.png


TEMPAT SAMPAH
image/bg/bar_pause.png


TEMPAT SAMPAH
image/bg/bar_sampling.png


TEMPAT SAMPAH
image/bg/bar_setting.png


TEMPAT SAMPAH
image/bg/bar_stop.png


TEMPAT SAMPAH
image/bg/close_bt.png


TEMPAT SAMPAH
image/bg/company_setting_logo.png


TEMPAT SAMPAH
image/bg/delete.png


TEMPAT SAMPAH
image/bg/department_setting_logo.png


TEMPAT SAMPAH
image/bg/download.png


TEMPAT SAMPAH
image/bg/equipment_setting_logo.png


TEMPAT SAMPAH
image/bg/gj_001_1_20.png


TEMPAT SAMPAH
image/bg/gj_001_21_40.png


TEMPAT SAMPAH
image/bg/gj_001_41_60.png


TEMPAT SAMPAH
image/bg/green_dot.png


TEMPAT SAMPAH
image/bg/grey_dot.png


TEMPAT SAMPAH
image/bg/icon.png


TEMPAT SAMPAH
image/bg/inductance_logo.png


TEMPAT SAMPAH
image/bg/insulation_logo.png


TEMPAT SAMPAH
image/bg/login.png


TEMPAT SAMPAH
image/bg/logo.png


TEMPAT SAMPAH
image/bg/logoff.png


TEMPAT SAMPAH
image/bg/menu_data_analysis.png


TEMPAT SAMPAH
image/bg/menu_data_preprocess.png


TEMPAT SAMPAH
image/bg/menu_file.png


TEMPAT SAMPAH
image/bg/menu_setting.png


TEMPAT SAMPAH
image/bg/min_bt.png


TEMPAT SAMPAH
image/bg/ng_bg.png


TEMPAT SAMPAH
image/bg/ok_bg.png


TEMPAT SAMPAH
image/bg/open_file.png


TEMPAT SAMPAH
image/bg/refresh.png


TEMPAT SAMPAH
image/bg/reset_logo.png


TEMPAT SAMPAH
image/bg/resistance_logo.png


TEMPAT SAMPAH
image/bg/save_bg.png


TEMPAT SAMPAH
image/bg/scan_barcode.png


TEMPAT SAMPAH
image/bg/tree_folder_icon.png


TEMPAT SAMPAH
image/bg/tree_leaf_icon.png


TEMPAT SAMPAH
image/bg/user.png


TEMPAT SAMPAH
image/bg/vertical_line.png


TEMPAT SAMPAH
image/bg/zoom_in.png


TEMPAT SAMPAH
image/bg/zoom_out.png


TEMPAT SAMPAH
image/close_bt.png


+ 0 - 0
image/cmd.txt


TEMPAT SAMPAH
image/icon.ico


TEMPAT SAMPAH
image/info_bt.png


TEMPAT SAMPAH
image/min_bt.png


TEMPAT SAMPAH
lib/commons-codec-1.15.jar


TEMPAT SAMPAH
lib/fastjson2-2.0.16.jar


TEMPAT SAMPAH
lib/gson-2.10.jar


TEMPAT SAMPAH
lib/iot-communication-1.4.4.jar


TEMPAT SAMPAH
lib/jSerialComm-2.6.2.jar


TEMPAT SAMPAH
lib/jfreechart-1.5.4.jar


TEMPAT SAMPAH
lib/jshortcut-0.4-oberzalek.jar


TEMPAT SAMPAH
lib/kotlin-stdlib-1.8.10.jar


TEMPAT SAMPAH
lib/logback-classic-1.2.13.jar


TEMPAT SAMPAH
lib/logback-core-1.2.13.jar


TEMPAT SAMPAH
lib/netty-all-4.1.48.Final.jar


TEMPAT SAMPAH
lib/okhttp-4.10.0.jar


TEMPAT SAMPAH
lib/okio-jvm-3.3.0.jar


TEMPAT SAMPAH
lib/s7connector-2.1.jar


TEMPAT SAMPAH
lib/slf4j-api-1.7.36.jar


TEMPAT SAMPAH
lib/sqlite-jdbc-3.36.0.3.jar


+ 3 - 0
src/META-INF/MANIFEST.MF

@@ -0,0 +1,3 @@
+Manifest-Version: 1.0
+Main-Class: com.mes.ui.MesClient
+

+ 10 - 0
src/com/mes/component/CallFromJs.java

@@ -0,0 +1,10 @@
+package com.mes.component;
+
+import com.mes.ui.MesClient;
+
+public class CallFromJs {
+    public String callFromJs(String info){
+        System.out.print("ss:"+info);
+        return MesClient.sessionid+":java:" + info;
+    }
+}

+ 57 - 0
src/com/mes/component/MesRadio.java

@@ -0,0 +1,57 @@
+package com.mes.component;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+public class MesRadio extends JPanel {
+
+    private String result = "";
+    private Integer i = 0;
+
+    public MesRadio(String[] radioTitles,String[] radioVals){
+        this.setLayout(new FlowLayout());
+        ButtonGroup group = new ButtonGroup();
+        i = 0;
+        for (String title:radioTitles){
+            JRadioButton radioButton = new JRadioButton(title);
+            radioButton.setFont(new Font("微软雅黑", Font.PLAIN, 28));
+
+            String val = radioVals[i];
+            radioButton.setName(val);
+
+            this.add(radioButton);
+            group.add(radioButton);
+
+            radioButton.addActionListener(new ActionListener() {
+                @Override
+                public void actionPerformed(ActionEvent e) {
+                    result = val;
+                    System.out.println("选择:"+result);
+                }
+            });
+            i++;
+        }
+    }
+
+    public void setResult(String ret){
+        this.result = "";
+        Component[] components = this.getComponents();
+        for (Component jRadioButton:components){
+            if(jRadioButton instanceof JRadioButton){
+                JRadioButton jRadioButtonParam = (JRadioButton)jRadioButton;
+                if(ret.equals(jRadioButtonParam.getName())){
+                    jRadioButtonParam.setSelected(true);
+                    this.result = jRadioButtonParam.getName();
+                }else{
+                    jRadioButtonParam.setSelected(false);
+                }
+            }
+        }
+    }
+
+    public String getResult(){
+        return this.result;
+    }
+}

+ 44 - 0
src/com/mes/component/MesWebView.java

@@ -0,0 +1,44 @@
+package com.mes.component;
+
+import javafx.application.Platform;
+import javafx.beans.value.ObservableValue;
+import javafx.concurrent.Worker;
+import javafx.embed.swing.JFXPanel;
+import javafx.scene.Scene;
+import javafx.scene.web.WebEngine;
+import javafx.scene.web.WebView;
+import netscape.javascript.JSObject;
+
+import java.util.Date;
+
+public class MesWebView extends JFXPanel {
+
+    public static WebEngine engine = null;
+
+    public MesWebView(String url){
+
+        Platform.runLater(() -> {
+            WebView webView = new WebView();
+            setScene(new Scene(webView));
+            Date date = new Date();
+//            String url = "http://"+mes_server_ip+":8980/js/a/mes/mesQuality/check?__sid="+sessionid+"&oprno="+mes_gw+"&t="+date.getTime();
+            System.out.print(url);
+            engine = webView.getEngine();
+            CallFromJs bridge = new CallFromJs();
+            engine.getLoadWorker().stateProperty().addListener(
+                    (ObservableValue<? extends Worker.State> ov, Worker.State oldState, Worker.State newState) -> {
+                        if (newState == Worker.State.SUCCEEDED) {
+                            JSObject window = (JSObject) engine.executeScript("window");
+                            window.setMember("apps", bridge);
+                            window.setMember("sout", System.out);
+                        }
+                    }
+            );
+            engine.load(url);
+        });
+    }
+
+    public void reloadWeb(){
+        engine.reload();
+    }
+}

+ 30 - 0
src/com/mes/component/MyDialog.java

@@ -0,0 +1,30 @@
+package com.mes.component;
+
+import javax.swing.*;
+import java.awt.*;
+
+public class MyDialog extends JDialog {
+
+    public MyDialog(Frame owner, String title, String msg){
+        super(owner, title);
+        init(msg);
+    }
+
+    private void init(String msg){
+        Container container = this.getContentPane();
+        container.setLayout(null);
+        container.setBackground(Color.BLACK);
+        this.setSize(800,220);
+        this.setLocationRelativeTo(null);
+
+        JLabel tslabel = new JLabel(msg);
+        tslabel.setHorizontalAlignment(SwingConstants.CENTER);
+        tslabel.setForeground(Color.RED);
+        tslabel.setFont(new Font("微软雅黑", Font.PLAIN,48));
+        tslabel.setBounds(0,30,800,100);
+
+        container.add(tslabel);
+        this.setModal(true);
+        this.setVisible(true);
+    }
+}

+ 90 - 0
src/com/mes/netty/MesMsgUtils.java

@@ -0,0 +1,90 @@
+package com.mes.netty;
+
+public class MesMsgUtils {
+
+    public static int SYNR_LEN = 46;
+    public static int AXTW_LEN = 46;
+    public static int ACLW_LEN = 46;
+    public static int MCJW_LEN = 96;
+    public static int AQDW_LEN = 96;
+    public static int MBDW_LEN = 96;
+    public static int MJBW_LEN = 96;
+    public static int MQDW_LEN = 96;
+    public static int MKSW_LEN = 96;
+    public static int MSBW_LEN = 96;
+    public static int MCSW_LEN = 96;
+    public static int AQRW_LEN = 96;
+
+    public static String MSG_TYPE[] = {
+        "SYNR",
+        "AXTW",
+        "ACLW",
+        "MCJW",
+        "AQDW",
+        "MBDW",
+        "MJBW",
+        "MQDW",
+        "MKSW",
+        "MSBW",
+        "MCSW",
+        "AQRW",
+    };
+
+    public static int isMsgContentOK(String msg, String msg_type) {
+        //ret=0OK,1 空内容,2 长度不符
+        int ret = 0;
+        if(msg==null||msg.equalsIgnoreCase("")) {
+            ret = 1;
+            return ret;
+        }
+
+        int len = msg.length();
+        //System.out.println("len="+len);
+        switch(msg_type) {
+            case "SYNR":
+            case "AXTW":
+            case "ACLW":
+                if(len==SYNR_LEN) {
+                    ret = 0;
+                }else {
+                    ret = 2;
+                }
+                break;
+            default:
+                if(len==AQDW_LEN) {
+                    ret = 0;
+                }else {
+                    ret = 2;
+                }
+                break;
+        }
+        return ret;
+    }
+
+    // 判断报文类型是否在清单里
+    public static boolean isMsgTypeOk(String msg_type) {
+        for (String str : MSG_TYPE) {
+            if (str.equals(msg_type)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    // 处理报文数据
+    public static String processMsg(String msg, String msg_type) {
+        String processMsgRet = "";
+        if(msg_type.equalsIgnoreCase("SYNR")) {
+
+        }else if(msg_type.equalsIgnoreCase("AXTW")) {
+
+        }else if(msg_type.equalsIgnoreCase("ACLW")) {
+
+        }else{
+            processMsgRet = ProtocolParam.getResult(msg);
+        }
+        return processMsgRet;
+    }
+
+
+}

+ 63 - 0
src/com/mes/netty/NettyClient.java

@@ -0,0 +1,63 @@
+package com.mes.netty;
+
+import io.netty.bootstrap.Bootstrap;
+import io.netty.channel.*;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioSocketChannel;
+import io.netty.handler.codec.string.StringEncoder;
+import java.util.concurrent.TimeUnit;
+
+import com.mes.ui.MesClient;
+
+public class NettyClient {
+    public SocketChannel socketChannel;
+    public static ChannelFuture future;
+
+    public  void run(Object msg){
+        //配置线程组
+        EventLoopGroup group = new NioEventLoopGroup();
+        //创建服务启动器
+        Bootstrap bootstrap = new Bootstrap();
+
+        //配置参数
+        bootstrap.group(group)
+                .channel(NioSocketChannel.class)
+                .option(ChannelOption.TCP_NODELAY,true)
+                .handler(new ChannelInitializer<SocketChannel>() {
+                    protected void initChannel(SocketChannel socketChannel) throws Exception {
+                        socketChannel.pipeline()
+                                .addLast(new XDecoder())
+                                .addLast(new StringEncoder())
+//                                    .addLast(new StringDecoder())
+                                .addLast(new NettyClientHandler());
+                    }
+                })
+                .remoteAddress(MesClient.mes_server_ip,MesClient.mes_tcp_port);
+
+        //连接
+        future = bootstrap.connect();
+        System.out.println("客户端正在连接服务端...");
+        //客户端断线重连逻辑
+        future.addListener((ChannelFutureListener) future1 -> {
+            if (future1.isSuccess()) {
+                //tcp连接成功
+                MesClient.tcp_connect_flag = true;
+                //设置TCP请求状态
+                MesClient.connect_request_flag = false;
+                System.out.println("连接Netty服务端成功");
+                future.channel().writeAndFlush(msg);
+            } else {
+                //tcp连接失败
+                MesClient.tcp_connect_flag = false;
+                MesClient.connect_request_flag = true;
+                System.out.println("连接失败,进行断线重连");
+                future1.channel().eventLoop().schedule(() -> run(msg), 10, TimeUnit.SECONDS);
+            }
+            //设置tcp连接状态
+            MesClient.setTcpStatus();
+        });
+        socketChannel = (SocketChannel) future.channel();
+
+    }
+}

+ 85 - 0
src/com/mes/netty/NettyClientHandler.java

@@ -0,0 +1,85 @@
+package com.mes.netty;
+
+import com.mes.ui.MesClient;
+import com.mes.ui.MesRevice;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+public class NettyClientHandler extends ChannelInboundHandlerAdapter {
+
+    private static final Logger log = LoggerFactory.getLogger(NettyClientHandler.class);
+    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+    public static byte[] responseByte;
+
+    @Override
+    public void channelActive(ChannelHandlerContext ctx) throws Exception {
+        log.info("[MES连接] TCP已连接 {}", sdf.format(new Date()));
+    }
+
+    @Override
+    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
+        Channel channel = ctx.channel();
+        log.warn("[MES连接] TCP已断开 ip={}", channel.remoteAddress());
+        MesClient.tcp_connect_flag = false;
+        MesClient.setTcpStatus();
+        channel.close();
+    }
+
+    @Override
+    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+        String raw = msg.toString();
+        log.info("[MES读] 原始报文={}", raw);
+
+        String mes_msg = formatResult(raw);
+        if(mes_msg == null || mes_msg.isEmpty()) {
+            log.warn("[MES读] 报文解析失败或为空,原始={}", raw);
+            return;
+        }
+
+        String msg_type = ProtocolParam.getMsgType(mes_msg);
+        String processMsgRet = MesMsgUtils.processMsg(mes_msg, msg_type);
+        log.info("[MES读] 类型={} 处理结果={} 内容={}", msg_type, processMsgRet, mes_msg);
+
+        switch(msg_type) {
+            case "AQDW":
+                MesRevice.checkQualityRevice(processMsgRet, mes_msg);
+                break;
+            case "MKSW":
+                MesRevice.startRevice(processMsgRet, mes_msg);
+                break;
+            case "MBDW":
+                MesRevice.bindRevice(processMsgRet, mes_msg);
+                break;
+            case "MJBW":
+                MesRevice.unbindRevice(processMsgRet, mes_msg);
+                break;
+            case "MQDW":
+                MesRevice.updateResultRevice(processMsgRet, mes_msg);
+                break;
+            default:
+                log.warn("[MES读] 未处理的报文类型={}", msg_type);
+                break;
+        }
+    }
+
+    @Override
+    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+        log.error("[MES连接异常]", cause);
+        ctx.close();
+    }
+
+    private String formatResult(String msg){
+        String msgType = msg.substring(0, 2).trim();
+        if(msgType.equals("OK")){
+            return msg.substring(3);
+        }
+        return "";
+    }
+
+}

+ 73 - 0
src/com/mes/netty/ProtocolParam.java

@@ -0,0 +1,73 @@
+package com.mes.netty;
+
+
+// 固定格式报文各参数获取方法
+public class ProtocolParam {
+    // bbbbfffffARWAQDWGWOP100 GY100000ID151245P00000106200123062900001      RSOKDA2023-09-07ZT10:16:58
+    public static Integer fixedLength = 96; // 固定长度
+
+    // 获取消息类型  所有报文都可使用
+    public static String getMsgType(String msg){
+        System.out.print(msg);
+        if(msg.length() < 16){
+            return "";
+        }
+        return msg.substring(12,16);
+    }
+
+    // 获取工位号
+    public static String getOprno(String msg){
+        if(msg.length() < 24){
+            return "";
+        }
+        return msg.substring(18,24);
+    }
+
+    // 获取工艺号
+    public static String getCraft(String msg){
+        if(msg.length() < 32){
+            return "";
+        }
+        return msg.substring(26,32);
+    }
+
+    // 获取镭雕码或设备报警故障代码
+    public static String getSn(String msg){
+        if(msg.length() < 70){
+            return "";
+        }
+        return msg.substring(34,70);
+    }
+
+    public static String getLx(String msg){
+        if(msg.length() < 72){
+            return "";
+        }
+        return msg.substring(70,72);
+    }
+
+    // 获取结果
+    public static String getResult(String msg){
+        if(msg.length() < 74){
+            return "";
+        }
+        return msg.substring(72,74);
+    }
+
+    // 获取日期
+    public static String getDay(String msg){
+        if(msg.length() < 86){
+            return "";
+        }
+        return msg.substring(76,86);
+    }
+
+    // 获取时间
+    public static String getTime(String msg){
+        if(msg.length() < 96){
+            return "";
+        }
+        return msg.substring(88,96);
+    }
+
+}

+ 168 - 0
src/com/mes/netty/XDecoder.java

@@ -0,0 +1,168 @@
+package com.mes.netty;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.ByteBufUtil;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.ByteToMessageDecoder;
+
+import java.util.List;
+
+public class XDecoder extends ByteToMessageDecoder {
+    static final int PACKET_SIZE = 46; // 最短包长度
+    static final int PACKET_MAX_SIZE = 1000; // 最长包长度
+
+    // 用来临时保留没有处理过的请求报文
+    ByteBuf tempMsg = Unpooled.buffer();
+
+    /**
+     * @param ctx
+     * @param in 请求的数据
+     * @param out 将粘在一起的报文拆分后的结果保留起来
+     * @throws Exception
+     */
+    @Override
+    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
+        System.out.println(Thread.currentThread() + "收到了一次数据包,长度是:" + in.readableBytes());
+        String content = hexStringToAscii(ByteBufUtil.hexDump(in));
+        System.out.println("接收包内容:" + hexStringToAscii(ByteBufUtil.hexDump(in)));
+
+        // 合并报文
+        ByteBuf message = null;
+        int tmpMsgSize = tempMsg.readableBytes();
+        // 如果暂存有上一次余下的请求报文,则合并
+        if (tmpMsgSize > 0) {
+            message = Unpooled.buffer();
+            message.writeBytes(tempMsg);
+            message.writeBytes(in);
+            System.out.println("合并:上一数据包余下的长度为:" + tmpMsgSize + ",合并后长度为:" + message.readableBytes());
+            System.out.println("合并后包内容:" + hexStringToAscii(ByteBufUtil.hexDump(message)));
+        } else {
+            message = in;
+        }
+
+//        System.out.println(Thread.currentThread() + "收到了一次数据包,长度是:" + message.readableBytes());
+        int size = 0;
+        String split = "bbbbfffffARW";
+
+        while (true){
+            size = message.readableBytes();
+            if(size >= PACKET_SIZE){
+                String retType = "NG:";
+                int qcsize = 0;
+                String str = hexStringToAscii(ByteBufUtil.hexDump(message));
+                String[] lists = str.split(split);
+
+                if(lists.length == 1 && size > PACKET_MAX_SIZE){ // 大于最大包长度
+                    byte[] request = new byte[size - PACKET_MAX_SIZE];
+                    // 每次从总的消息中读取n个字节的数据
+                    message.readBytes(request);
+                    // 将拆分后的结果放入out列表中,交由后面的业务逻辑去处理
+                    out.add(retType+hexStringToAscii(ByteBufUtil.hexDump(Unpooled.copiedBuffer(request))));
+                    break;
+                }
+
+                if(lists[0].length() > 0){
+                    byte[] request = new byte[lists[0].length()];
+                    // 每次从总的消息中读取n个字节的数据
+                    message.readBytes(request);
+                    // 将拆分后的结果放入out列表中,交由后面的业务逻辑去处理
+                    out.add(retType+hexStringToAscii(ByteBufUtil.hexDump(Unpooled.copiedBuffer(request))));
+                }else{
+                    if(lists.length > 1){
+                        String ss = lists[1];
+                        if(ss.length() <= 4){
+                            qcsize += ss.length();
+                        }else{
+                            String msgType = ProtocolParam.getMsgType(split+ss);
+                            if(!MesMsgUtils.isMsgTypeOk(msgType)){
+                                qcsize += split.length() + ss.length();
+                            }else{
+                                Integer ppsize = checkResultSize(ss,msgType,split);
+                                if(ppsize > 0){
+                                    qcsize = ppsize;
+                                    retType = "OK:";
+                                }else{
+                                    qcsize += split.length() + ss.length();
+                                }
+                            }
+                        }
+                    }
+                }
+
+
+                if(qcsize > 0){
+                    byte[] request = new byte[qcsize];
+                    // 每次从总的消息中读取n个字节的数据
+                    message.readBytes(request);
+                    // 将拆分后的结果放入out列表中,交由后面的业务逻辑去处理
+                    out.add(retType+hexStringToAscii(ByteBufUtil.hexDump(Unpooled.copiedBuffer(request))));
+                }
+            }else{
+                break;
+            }
+        }
+
+        // 多余的报文存起来
+        // 第一个报文: i+  暂存
+        // 第二个报文: 1 与第一次
+        size = message.readableBytes();
+        if (size != 0) {
+            System.out.println("多余的数据长度:" + size);
+            // 剩下来的数据放到tempMsg暂存
+            tempMsg.clear();
+            tempMsg.writeBytes(message.readBytes(size));
+        }
+    }
+
+    private Integer checkResultSize(String str, String msg_type, String split){
+        String oldstr = str;
+        str = split+str;
+        int tpsize = 0;
+        switch(msg_type) {
+            case "SYNR": // 同步
+                if(str.length() >= MesMsgUtils.SYNR_LEN){
+                    tpsize = MesMsgUtils.SYNR_LEN;
+                }
+                break;
+            case "AXTW": // 心跳
+                if(str.length() >= MesMsgUtils.AXTW_LEN){
+                    tpsize = MesMsgUtils.AXTW_LEN;
+                }
+                break;
+            case "ACLW": // 重连
+                if(str.length() >= MesMsgUtils.ACLW_LEN){
+                    tpsize = MesMsgUtils.ACLW_LEN;
+                }
+                break;
+            case "MCJW":
+            case "AQDW":
+            case "MBDW":
+            case "MJBW":
+            case "MQDW":
+            case "MKSW":
+            case "MSBW":
+            case "MCSW":
+            case "AQRW":
+            default: // 默认新报文
+                if(str.length() >= ProtocolParam.fixedLength){ // 大于固定长度
+                    tpsize = ProtocolParam.fixedLength;
+                }
+                break;
+        }
+
+        return tpsize;
+    }
+
+    // 16字符串转Ascii
+    private String hexStringToAscii(String hexString) {
+        StringBuilder sbuilder = new StringBuilder();
+        for (int i = 0; i < hexString.length(); i += 2) {
+            String hexByte = hexString.substring(i, i + 2);
+            int byteValue = Integer.parseInt(hexByte, 16);
+            char c = (char) byteValue;
+            sbuilder.append(c);
+        }
+        return sbuilder.toString();
+    }
+}

+ 58 - 0
src/com/mes/ui/BindMaterialResp.java

@@ -0,0 +1,58 @@
+package com.mes.ui;
+
+public class BindMaterialResp {
+    private String materialId;
+    private String materialTitle;
+    private String craft;
+    private String batchSn;
+    private String lastTimes;
+    private String type;
+
+    public String getMaterialId() {
+        return materialId;
+    }
+
+    public void setMaterialId(String materialId) {
+        this.materialId = materialId;
+    }
+
+    public String getMaterialTitle() {
+        return materialTitle;
+    }
+
+    public void setMaterialTitle(String materialTitle) {
+        this.materialTitle = materialTitle;
+    }
+
+    public String getCraft() {
+        return craft;
+    }
+
+    public void setCraft(String craft) {
+        this.craft = craft;
+    }
+
+    public String getBatchSn() {
+        return batchSn;
+    }
+
+    public void setBatchSn(String batchSn) {
+        this.batchSn = batchSn;
+    }
+
+    public String getLastTimes() {
+        return lastTimes;
+    }
+
+    public void setLastTimes(String lastTimes) {
+        this.lastTimes = lastTimes;
+    }
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
+}

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

@@ -0,0 +1,334 @@
+package com.mes.ui;
+
+import com.alibaba.fastjson2.JSONObject;
+import com.mes.netty.NettyClient;
+import com.mes.util.DateLocalUtils;
+import com.mes.util.JdbcUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.*;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.util.Properties;
+
+public class DataUtil {
+
+    private static final Logger log = LoggerFactory.getLogger(DataUtil.class);
+
+    public static Boolean synrTcp(NettyClient nettyClient,String mes_gw){
+        try{
+            //TCP连接后,直接先发同步报文
+            String start = "aaaabbbbbABW";
+            String msgType = "SYNR";
+            String gw = "GW"+DataUtil.rightPad(mes_gw, 6);
+            String da = "DA" + DateLocalUtils.getCurrentDate();
+            String zt = "ZT" + DateLocalUtils.getCurrentTimeHMS();
+            String synr_str = start + msgType + gw + da + zt;
+            //插入报文本地数据
+            String gy = "";
+            String sn = "";
+            JdbcUtils.insertData(gw, gy, synr_str, msgType, sn);
+
+            nettyClient.run(synr_str);
+
+            return true;
+        }catch (Exception e){
+            return false;
+        }
+    }
+
+    public static Boolean heartBeat(NettyClient nettyClient,String mes_gw){
+        try{
+            //TCP连接后,直接先发同步报文
+            String start = "aaaabbbbbABW";
+            String msgType = "AXTW";
+            String gw = "GW"+DataUtil.rightPad(mes_gw, 6);
+            String da = "DA" + DateLocalUtils.getCurrentDate();
+            String zt = "ZT" + DateLocalUtils.getCurrentTimeHMS();
+            String axtw_str = start + msgType + gw + da + zt;
+            //插入报文本地数据
+            String gy = "";
+            String sn = "";
+            JdbcUtils.insertData(gw, gy, axtw_str, msgType, sn);
+            nettyClient.future.channel().writeAndFlush(axtw_str);
+
+            return true;
+        }catch (Exception e){
+            return false;
+        }
+    }
+
+    public static Boolean checkQuality(NettyClient nettyClient, String sn, String user){
+        try{
+            String msgType = "AQDW";
+            String gy = "100000";
+            Boolean aqdw_str = sendMessage(nettyClient,msgType,gy,"",sn,"",user,"00","");
+            return aqdw_str;
+        }catch (Exception e){
+            return false;
+        }
+    }
+
+    public static Boolean startWork(NettyClient nettyClient,String sn,String user){
+        try{
+            String msgType = "MKSW";
+            String gy = "";
+            Boolean aqdw_str = sendMessage(nettyClient,msgType,gy,"",sn,"",user,"00","");
+            return aqdw_str;
+        }catch (Exception e){
+            return false;
+        }
+    }
+
+    public static Boolean bindUser(NettyClient nettyClient,String sn,String user){
+        try{
+            String msgType = "MBDW";
+            String gy = "400001";
+            String param = rightPad(user, 36);
+            Boolean aqdw_str = sendMessage(nettyClient,msgType,gy,"",sn,"",user,"01",param);
+            return aqdw_str;
+        }catch (Exception e){
+            return false;
+        }
+    }
+
+    public static Boolean bindWarehouse(NettyClient nettyClient,String sn,String wsn,String user,String craft){
+        try{
+            String msgType = "MBDW";
+            String param = rightPad(wsn, 36);
+            Boolean aqdw_str = sendMessage(nettyClient,msgType,craft,"",sn,"",user,"01",param);
+            return aqdw_str;
+        }catch (Exception e){
+            return false;
+        }
+    }
+
+    public static Boolean unBindWarehouse(NettyClient nettyClient,String sn,String wsn,String user,String craft){
+        try{
+            String msgType = "MJBW";
+            String param = rightPad(wsn, 36);
+            Boolean aqdw_str = sendMessage(nettyClient,msgType,craft,"",sn,"",user,"01",param);
+            return aqdw_str;
+        }catch (Exception e){
+            return false;
+        }
+    }
+
+    public static Boolean sendQualityOld(NettyClient nettyClient,String sn,String ret,String user){
+        try{
+            String msgType = "MQDW";
+            String gy = "100000";
+            String param = "";
+            Boolean aqdw_str = sendMessage(nettyClient,msgType,gy,"",sn,ret,user,"00",param);
+            return aqdw_str;
+        }catch (Exception e){
+            return false;
+        }
+    }
+
+    public static Boolean sendQuality(NettyClient nettyClient,String sn,String ret,String user){
+        try{
+            String msgType = "MQDW";
+            String craft = "100000";
+            String params = rightPad("Y"+MesClient.programNo, 12);
+            String enconding = "UTF-8";
+            InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties");
+            Properties pro = new Properties();
+            BufferedReader br = new BufferedReader(new InputStreamReader(is, enconding));
+            pro.load(br);
+            String gw = "GW"+rightPad(pro.getProperty("mes.gw"), 6);
+            String start = "aaaabbbbbABW";
+            String gy = "GY" + rightPad(craft, 6);
+            String reslx = "LX" + rightPad("", 2);
+            String id = pro.getProperty("mes.line_sn") + rightPad(sn, 36);
+            String rs = "RS"+ rightPad(ret, 2);
+            String da = "DA" + DateLocalUtils.getCurrentDate();
+            String zt = "ZT" + DateLocalUtils.getCurrentTimeHMS();
+            String yh = "YH" + rightPad(user, 20);
+            String aqdw_str = start + msgType + gw + gy + reslx + id + rs + da + zt + yh + "01" + params;
+            log.info("[MES写] {} 报文={}", msgType, aqdw_str);
+            if(!sn.isEmpty()){
+                JdbcUtils.insertSubmitRecord(gw, sn, aqdw_str);
+            }
+            return true;
+        }catch (Exception e){
+            return false;
+        }
+    }
+
+    public static Boolean sendMessage(NettyClient nettyClient,String msgType,String craft,String lx,String sn,String result,String user,String paramNums,String params){
+        try{
+            String enconding = "UTF-8";
+            InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties");
+            Properties pro = new Properties();
+            BufferedReader br = new BufferedReader(new InputStreamReader(is, enconding));
+            pro.load(br);
+            String gw = "GW"+rightPad(pro.getProperty("mes.gw"), 6);
+            String start = "aaaabbbbbABW";
+            String gy = "GY" + rightPad(craft, 6);
+            String reslx = "LX" + rightPad(lx, 2);
+            String id = pro.getProperty("mes.line_sn") + rightPad(sn, 36);
+            String rs = "RS"+ rightPad(result, 2);
+            String da = "DA" + DateLocalUtils.getCurrentDate();
+            String zt = "ZT" + DateLocalUtils.getCurrentTimeHMS();
+            String yh = "YH" + rightPad(user, 20);
+            String aqdw_str = start + msgType + gw + gy + reslx + id + rs + da + zt + yh + paramNums + params;
+            log.info("[MES写] {} 报文={}", msgType, aqdw_str);
+            JdbcUtils.insertData(gw, gy, aqdw_str, msgType, sn);
+            nettyClient.future.channel().writeAndFlush(aqdw_str);
+            return true;
+        }catch (Exception e){
+            return false;
+        }
+    }
+
+    public static String rightPad(final String str, final int size) {
+        if (str == null) {
+            return null;
+        }
+
+        String strret = str;
+        if(str.length() > size){
+            strret = str.substring(0,size);
+        }
+        return String.format("%-"+size+"s", strret);
+    }
+
+    public static JSONObject uploadFswParams(String paramsJson) {
+        try {
+            String enconding = "UTF-8";
+            InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties");
+            Properties pro = new Properties();
+            BufferedReader br = new BufferedReader(new InputStreamReader(is, enconding));
+            pro.load(br);
+            String mes_server_ip = pro.getProperty("mes.server_ip");
+            String url = "http://" + mes_server_ip + ":8980/js/a/mes/mesProductFsw/batchsave";
+            String params = "__ajax=json&params=" + URLEncoder.encode(paramsJson, "UTF-8");
+            log.info("[MES写] FSW过程参数上传 url={} count={}", url, paramsJson.length());
+            String result = doPost(url, params);
+            log.info("[MES写] FSW过程参数上传结果={}", result);
+            if (result.equalsIgnoreCase("false")) {
+                return null;
+            }
+            return JSONObject.parseObject(result);
+        } catch (Exception e) {
+            log.error("[MES写] FSW过程参数上传失败", e);
+            return null;
+        }
+    }
+
+    public static JSONObject getBindMaterail() {
+        try{
+            String enconding = "UTF-8";
+            InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties");
+            Properties pro = new Properties();
+            BufferedReader br = new BufferedReader(new InputStreamReader(is, enconding));
+            pro.load(br);
+            String mes_server_ip = pro.getProperty("mes.server_ip");
+            String oprno = pro.getProperty("mes.gw").trim();
+            String lineSn = pro.getProperty("mes.line_sn").trim();
+            String url = "http://"+mes_server_ip+":8980/js/a/mes/mesLineProcessMaterial/materials";
+            String params = "__ajax=json&oprno="+oprno+"&lineSn="+lineSn;
+            System.out.println("params="+params);
+            String result = doPost(url,params);
+            System.out.println("result="+result);
+
+            if(result.equalsIgnoreCase("false")) {
+                return null;
+            }else {
+                return JSONObject.parseObject(result);
+            }
+        }catch (Exception e){
+            return null;
+        }
+    }
+
+    public static JSONObject saveBindMaterail(String batchSn,String craft,String materialId,String type) {
+        try{
+            String enconding = "UTF-8";
+            InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties");
+            Properties pro = new Properties();
+            BufferedReader br = new BufferedReader(new InputStreamReader(is, enconding));
+            pro.load(br);
+            String mes_server_ip = pro.getProperty("mes.server_ip");
+            String oprno = pro.getProperty("mes.gw").trim();
+            String lineSn = pro.getProperty("mes.line_sn").trim();
+            String url = "http://"+mes_server_ip+":8980/js/a/mes/mesMaterialPrebind/bind";
+            String params = "__ajax=json&oprno="+oprno+"&lineSn="+lineSn+"&batchSn="+batchSn+"&craft="+craft+"&materialId="+materialId+"&type="+type;
+            System.out.println("params="+params);
+            String result = doPost(url,params);
+            System.out.println("result="+result);
+
+            if(result.equalsIgnoreCase("false")) {
+                return null;
+            }else {
+                return JSONObject.parseObject(result);
+            }
+        }catch (Exception e){
+            return null;
+        }
+    }
+
+    public static String doPost(String httpUrl, String param) {
+        HttpURLConnection connection = null;
+        InputStream is = null;
+        OutputStream os = null;
+        BufferedReader br = null;
+        String result = null;
+        try {
+            URL url = new URL(httpUrl);
+            connection = (HttpURLConnection) url.openConnection();
+            connection.setRequestMethod("POST");
+            connection.setConnectTimeout(15000);
+            connection.setReadTimeout(60000);
+            connection.setDoOutput(true);
+            connection.setDoInput(true);
+            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
+            connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
+            os = connection.getOutputStream();
+            os.write(param.getBytes());
+            if (connection.getResponseCode() == 200) {
+                is = connection.getInputStream();
+                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
+                StringBuffer sbf = new StringBuffer();
+                String temp = null;
+                while ((temp = br.readLine()) != null) {
+                    sbf.append(temp);
+                    sbf.append("\r\n");
+                }
+                result = sbf.toString();
+            }
+        } catch (MalformedURLException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        } finally {
+            if (null != br) {
+                try {
+                    br.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+            if (null != os) {
+                try {
+                    os.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+            if (null != is) {
+                try {
+                    is.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+            connection.disconnect();
+        }
+        return result;
+    }
+}

+ 85 - 0
src/com/mes/ui/LockUtil.java

@@ -0,0 +1,85 @@
+package com.mes.ui;
+
+import java.io.File;
+import java.io.RandomAccessFile;
+import java.nio.channels.FileChannel;
+import java.nio.channels.FileLock;
+import java.nio.channels.OverlappingFileLockException;
+
+public class LockUtil {
+    private FileChannel channel;
+
+    private FileLock lock;
+
+    private File file;
+
+    private static LockUtil instance = null;
+
+    /**
+     * 获取唯一进程限制的实例
+     * @Title: getInstance
+     * @return  唯一进程实例
+     */
+    public static LockUtil getInstance(){
+        if(instance == null){
+            instance = new LockUtil();
+        }
+        return instance;
+    }
+
+    /**
+     * 进程是否正在运行
+     * @Title: isAppActive
+     * @return  运行与否
+     */
+    public boolean isAppActive() {
+        File file = new File(".lock2");
+        try {
+            channel = new RandomAccessFile(file, "rw").getChannel();
+            try {
+                lock = channel.tryLock();
+
+            } catch (OverlappingFileLockException e) {
+                closeLock();
+                return true;
+            }
+            if (lock == null) {
+                closeLock();
+                return true;
+            }
+            Runtime.getRuntime().addShutdownHook(new Thread() {
+                public void run() {
+                    closeLock();
+                    deleteFile();
+                }
+            });
+            return false;
+        } catch (Exception e) {
+            closeLock();
+            return true;
+        }
+    }
+
+    protected void deleteFile() {
+        try {
+            file.delete();
+        } catch (Exception e) {
+
+        }
+
+    }
+
+    private void closeLock() {
+        try {
+            lock.release();
+        } catch (Exception e) {
+
+        }
+
+        try {
+            channel.close();
+        } catch (Exception e) {
+
+        }
+    }
+}

+ 210 - 0
src/com/mes/ui/LoginFarme.java

@@ -0,0 +1,210 @@
+package com.mes.ui;
+
+import com.alibaba.fastjson2.JSONObject;
+import com.mes.component.MesRadio;
+import com.mes.component.MesWebView;
+import com.mes.util.Base64Utils;
+import com.mes.util.HttpUtils;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.time.LocalDateTime;
+
+public class LoginFarme extends JFrame {
+    //登录模块组件
+    static JLabel userNameLabel= new JLabel("<html><body>用户名:</body></html>",JLabel.LEFT);//用户名
+    static JLabel userPasswordLabel= new JLabel("<html><body>密码:</body></html>",JLabel.LEFT);//用户名
+    public static JTextField userNameTxt;
+    public static JPasswordField userPasswordTxt;
+    static JButton loginButton = new JButton("用户密码登录");
+    static JButton scanLoginButton = new JButton("扫  码  登  录");
+
+    public LoginFarme(){
+        setTitle("MES系统客户端:"+MesClient.mes_gw+" - "+MesClient.mes_gw_des);
+
+        ImageIcon bg = new ImageIcon(MesClient.class.getResource("/background.png"));
+        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+        JLabel imgLabel = new JLabel(bg);//将背景图放在标签里。
+        getLayeredPane().add(imgLabel, new Integer(Integer.MIN_VALUE));//注意这里是关键,将背景标签添加到jfram的LayeredPane面板里。
+        imgLabel.setBounds(0,0,bg.getIconWidth(), bg.getIconHeight());//设置背景标签的位置
+        Container contentPane=getContentPane();
+        contentPane.setLayout(null);//布局,很重要
+        JPanel welcomePanel = new JPanel();
+        //welcomePanel.setLayout(new GridLayout(3, 1));
+        welcomePanel.setLayout(null);
+        //welcomeLable.setBounds(10, 5, 700, 100);
+        welcomePanel.setBounds(30, 330, 890, 300);
+        welcomePanel.setOpaque(false);//背景透明
+        contentPane.add(welcomePanel);
+
+        //登录页面
+        userNameLabel.setBounds(300, 100, 120, 40);
+        userNameLabel.setFont(new java.awt.Font("Dialog",   1,   16));
+        userPasswordLabel.setBounds(300, 150, 120, 40);
+        userPasswordLabel.setFont(new java.awt.Font("Dialog",   1,   16));
+        userNameTxt = new JTextField(20);
+        userNameTxt.setText("system");
+        userNameTxt.setBounds(400, 105, 150, 30);
+        userPasswordTxt = new JPasswordField(20);
+        userPasswordTxt.setBounds(400, 155, 150, 30);
+        userPasswordTxt.setText("Aa111111");
+        loginButton.setFont(new java.awt.Font("Dialog",   1,   16));
+        loginButton.setBounds(300, 200, 255, 40);
+        loginButton.setIcon(new ImageIcon(MesClient.class.getResource("/bg/user.png")));
+
+//        scanLoginButton.setVisible(false);
+        scanLoginButton.setFont(new java.awt.Font("Dialog",   1,   16));
+        scanLoginButton.setBounds(300, 250, 255, 40);
+        scanLoginButton.setIcon(new ImageIcon(MesClient.class.getResource("/bg/scan_barcode.png")));
+
+        welcomePanel.add(userNameLabel);
+        welcomePanel.add(userPasswordLabel);
+        welcomePanel.add(userNameTxt);
+        welcomePanel.add(userPasswordTxt);
+        welcomePanel.add(loginButton);
+        welcomePanel.add(scanLoginButton);
+        loginButton.addActionListener(new ActionListener(){
+            public void actionPerformed(ActionEvent e) {
+                login();
+            }
+        });
+        scanLoginButton.addActionListener(new ActionListener(){
+            public void actionPerformed(ActionEvent e) {
+                scanLogin();
+            }
+        });
+
+        ((JPanel)contentPane).setOpaque(false); //注意这里,将内容面板设为透明。这样LayeredPane面板中的背景才能显示出来。
+        //welcomeWin.setSize(902,678);
+        setResizable(false);//禁止最大化
+        setIconImage(Toolkit.getDefaultToolkit().getImage(MesClient.class.getResource("/bg/logo.png")));
+
+        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
+        int width = 902;
+        int height = 678;
+        setBounds((d.width-width)/2, (d.height-height)/2-(d.height-height)/4, width, height);
+        /*****正常模式******/
+        setVisible(true);
+    }
+
+    //登录
+    public static void login() {
+        String user_str = userNameTxt.getText().toString();
+        String password_str = userPasswordTxt.getText().toString();
+        if(user_str.equalsIgnoreCase("")||password_str.equalsIgnoreCase("")) {
+            JOptionPane.showMessageDialog(MesClient.mesClientFrame,"用户名或密码不能为空","提示窗口", JOptionPane.INFORMATION_MESSAGE);
+            return;
+        }
+        String username = Base64Utils.getBase64(user_str);
+        String password = Base64Utils.getBase64(password_str);
+        System.out.println("&username=" + username + "&password=" + password);
+        String url = "http://"+MesClient.mes_server_ip+":8980/js/a/login?__ajax=json&username="+username+"&password="+password+"&validCode=&__sid=";
+        String loginResult = HttpUtils.sendRequest(url);
+        if(loginResult.equalsIgnoreCase("false")) {
+            JOptionPane.showMessageDialog(MesClient.mesClientFrame,"登录异常,请检查网络或联系网络管理员","提示窗口", JOptionPane.INFORMATION_MESSAGE);
+            return;
+        }else {
+            JSONObject retObj = JSONObject.parseObject(loginResult);
+            if(retObj.get("result")!=null&&retObj.get("result").toString().equalsIgnoreCase("true")) {
+                //检查用户权限是否可登录界面
+                checkUserAuthority(retObj);
+            }else {
+                //ret = "msg save error";
+                //ret = false;
+                JOptionPane.showMessageDialog(MesClient.mesClientFrame,"登录失败,用户名或密码错误","提示窗口", JOptionPane.INFORMATION_MESSAGE);
+                return;
+            }
+        }
+    }
+    //扫码登录
+    public static void scanLogin() {
+        //userNameTxt.setText("");
+        //userPasswordTxt.setText("");
+        String scanContent = JOptionPane.showInputDialog(null, "请扫码工牌二维码");
+        System.out.println("scanContent="+scanContent);
+        if(scanContent!=null&&!scanContent.equalsIgnoreCase("")) {
+            String url = "http://"+MesClient.mes_server_ip+":8980/js/a/mes/mesLogin/login?__login=true&__ajax=json&username="+scanContent;
+            String loginResult = HttpUtils.sendRequest(url);
+            System.out.println("loginResult="+loginResult);
+            if(loginResult.equalsIgnoreCase("false")) {
+                JOptionPane.showMessageDialog(MesClient.mesClientFrame,"登录异常,请检查网络或联系网络管理员","提示窗口", JOptionPane.INFORMATION_MESSAGE);
+                return;
+            }else {
+                JSONObject retObj = JSONObject.parseObject(loginResult);
+                if(retObj.get("result")!=null&&retObj.get("result").toString().equalsIgnoreCase("true")) {
+                    //检查用户权限是否可登录界面
+                    checkUserAuthority(retObj);
+                }else {
+                    JOptionPane.showMessageDialog(MesClient.mesClientFrame,"登录失败,用户名或密码错误","提示窗口", JOptionPane.INFORMATION_MESSAGE);
+                    return;
+                }
+            }
+        }else {
+            JOptionPane.showMessageDialog(MesClient.mesClientFrame,"扫码内容错误","提示窗口", JOptionPane.INFORMATION_MESSAGE);
+            return;
+        }
+    }
+
+    //检查用户权限是否可登录界面
+    public static void checkUserAuthority(JSONObject retObj) {
+        //设置登录用户名
+        JSONObject userObj = JSONObject.parseObject(retObj.get("user").toString());
+        String user_id = userObj.getString("id").toString();
+
+        //获取sessionid,判断权限
+        MesClient.sessionid = retObj.get("sessionid").toString();
+        if(MesClient.sessionid!=null&&!MesClient.sessionid.equalsIgnoreCase("")) {
+            //请求权限
+            String url_authority = "http://"+MesClient.mes_server_ip+":8980/js/a/mes/mesLineProcess/userAuth?__ajax=json&type=0&__sid="+MesClient.sessionid+"&oprno="+MesClient.mes_gw+"&lineSn="+MesClient.mes_line_sn;
+            String authorityResult = HttpUtils.sendRequest(url_authority);
+            System.out.println("authorityResult="+authorityResult);
+            JSONObject authorityObj = JSONObject.parseObject(authorityResult);
+            if(authorityObj.get("result")!=null&&authorityObj.get("result").toString().equalsIgnoreCase("true")) {
+                JSONObject authObjTmp = JSONObject.parseObject(authorityObj.get("data").toString());
+                MesClient.mes_auth = Integer.parseInt(authObjTmp.getString("auth").toString());
+                if(MesClient.mes_auth==0) {
+                    //无权限登录
+                    JOptionPane.showMessageDialog(MesClient.mesClientFrame,"您无权登录该工位","提示窗口", JOptionPane.INFORMATION_MESSAGE);
+                    return;
+                }else if(MesClient.mes_auth==1||MesClient.mes_auth==2) {
+                    // 获取等于所处时间-当前小时
+                    LocalDateTime now = LocalDateTime.now();
+                    MesClient.userLoginHours = now.getHour();
+                    //初始化tcp连接,发送同步报文
+                    MesClient.initTcpConnection();
+                    //启动timer心跳包
+                    MesClient.startHeartBeatTimer();
+
+                    //1操作工人,2管理员
+                    //登录成功
+                    MesClient.user_menu.setText(user_id);
+                    MesClient.welcomeWin.setVisible(false);
+                    MesClient.mesClientFrame.setVisible(true);
+
+                    if(MesClient.jfxPanel == null){
+                        String url = "http://"+ MesClient.mes_server_ip+":8980/js/a/mes/mesProductRecord/work?oprno="+MesClient.mes_gw+"&lineSn="+MesClient.mes_line_sn;
+                        MesClient.jfxPanel = new MesWebView(url);
+                        MesClient.jfxPanel.setSize(990, 550);
+                        MesClient.indexPanelB.add(MesClient.jfxPanel);
+                    }
+
+                    if(MesClient.jfxPanel2 == null){
+                        String url = "http://"+ MesClient.mes_server_ip+":8980/js/a/mes/mesProcessCheckRecord/ulist?__sid="+MesClient.sessionid+"&oprno="+MesClient.mes_gw+"&lineSn="+MesClient.mes_line_sn;
+                        MesClient.jfxPanel2 = new MesWebView(url);
+                        MesClient.jfxPanel2.setSize(990, 550);
+                        MesClient.indexPanelC.add(MesClient.jfxPanel2);
+                    }
+
+                    MesClient.initWarehouseData();
+                }
+
+            }
+
+        }else {
+            JOptionPane.showMessageDialog(MesClient.mesClientFrame,"登录失败,用户名或密码错误","提示窗口", JOptionPane.INFORMATION_MESSAGE);
+            return;
+        }
+    }
+}

File diff ditekan karena terlalu besar
+ 1035 - 0
src/com/mes/ui/MesClient.java


+ 129 - 0
src/com/mes/ui/MesRevice.java

@@ -0,0 +1,129 @@
+package com.mes.ui;
+
+import com.mes.util.ErrorMsg;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.awt.*;
+
+public class MesRevice {
+    public static final Logger log = LoggerFactory.getLogger(MesRevice.class);
+
+    // 质量查询
+    public static void checkQualityRevice(String processMsgRet, String mes_msg) {
+        try {
+            log.info("[MES读] AQDW 回复 processMsgRet={} msg={}", processMsgRet, mes_msg);
+            if (processMsgRet.equalsIgnoreCase("UD")) {
+                MesClient.check_quality_result = true;
+                boolean needStartWork = MesClient.work_status == 0;
+                MesClient.paramRecordingStarted = false;
+
+                // 设备断电重上电后需先恢复 PLC 连接,再发允许启动
+                if (!S7Util.ensureConnected()) {
+                    MesClient.check_quality_result = false;
+                    MesClient.work_status = 0;
+                    MesClient.tjFlag = 0;
+                    MesClient.f_scan_data_bt_1.setEnabled(true);
+                    MesClient.setMenuStatus("PLC未连接,请等待重连后再扫码", -1);
+                    MesClient.updatePlcStatus(false);
+                    log.warn("[流程] 质量合格但PLC未连接,取消允许启动");
+                    return;
+                }
+                MesClient.updatePlcStatus(true);
+
+                // 质量查询通过后立即允许启动并进入等待加工状态(不依赖 MKSW 回复)
+                MesClient.work_status = 1;
+                MesClient.f_scan_data_bt_1.setEnabled(false);
+                MesClient.tjFlag = 1;
+                log.info("[流程] 质量合格,tjFlag=1,发送允许启动 DB9052.DBX0.0=true,工件={}",
+                        MesClient.product_sn.getText());
+                if (!S7Util.sendAllowStart(true)) {
+                    MesClient.check_quality_result = false;
+                    MesClient.work_status = 0;
+                    MesClient.tjFlag = 0;
+                    MesClient.f_scan_data_bt_1.setEnabled(true);
+                    MesClient.setMenuStatus("发送MES允许启动信号失败,请重试", -1);
+                    MesClient.updatePlcStatus(S7Util.isConnected());
+                    return;
+                }
+                MesClient.setMenuStatus(MesClient.tjFlagText5, 0);
+
+                if (needStartWork) {
+                    String barcode36 = MesClient.getBarcode(MesClient.product_sn.getText());
+                    MesClient.getUser();
+                    log.info("[MES写] MKSW 开工,工件={} 用户={}",
+                            MesClient.product_sn.getText(), MesClient.user20.trim());
+                    DataUtil.startWork(MesClient.nettyClient, barcode36, MesClient.user20);
+                }
+            } else {
+                MesClient.check_quality_result = false;
+                String lmsg = ErrorMsg.getErrorMsg(processMsgRet, mes_msg);
+                MesClient.setMenuStatus(lmsg, -1);
+                log.warn("[MES读] AQDW 质量不合格 processMsgRet={},禁止启动", processMsgRet);
+                S7Util.sendAllowStart(false);
+            }
+        } catch (Exception e) {
+            log.error("[MES异常] checkQualityRevice", e);
+        }
+    }
+
+    // 开始回复处理
+    public static void startRevice(String processMsgRet, String mes_msg) {
+        try {
+            log.info("[MES读] MKSW 回复 processMsgRet={} msg={}", processMsgRet, mes_msg);
+            if (processMsgRet.equalsIgnoreCase("OK")) {
+                log.info("[流程] MKSW 开工报文确认 OK,当前 tjFlag={} work_status={}",
+                        MesClient.tjFlag, MesClient.work_status);
+                // 兜底:若质量通过时未进入加工状态,在此补发允许启动
+                if (MesClient.tjFlag != 1) {
+                    if (!S7Util.ensureConnected()) {
+                        MesClient.setMenuStatus("PLC未连接,无法发送允许启动信号", -1);
+                        MesClient.updatePlcStatus(false);
+                        return;
+                    }
+                    MesClient.work_status = 1;
+                    MesClient.f_scan_data_bt_1.setEnabled(false);
+                    MesClient.tjFlag = 1;
+                    MesClient.paramRecordingStarted = false;
+                    S7Util.sendAllowStart(true);
+                }
+            } else {
+                log.warn("[MES读] MKSW 开工失败 processMsgRet={}(允许启动已在质量合格后发出)", processMsgRet);
+            }
+        } catch (Exception e) {
+            log.error("[MES异常] startRevice", e);
+        }
+    }
+
+    public static void bindRevice(String processMsgRet, String mes_msg) {
+        try {
+            log.info("[MES读] MBDW 回复 processMsgRet={} msg={}", processMsgRet, mes_msg);
+        } catch (Exception e) {
+            log.error("[MES异常] bindRevice", e);
+        }
+    }
+
+    public static void unbindRevice(String processMsgRet, String mes_msg) {
+        try {
+            log.info("[MES读] MJBW 回复 processMsgRet={} msg={}", processMsgRet, mes_msg);
+        } catch (Exception e) {
+            log.error("[MES异常] unbindRevice", e);
+        }
+    }
+
+    public static void updateResultRevice(String processMsgRet, String mes_msg) {
+        try {
+            log.info("[MES读] MQDW 回复 processMsgRet={} msg={}", processMsgRet, mes_msg);
+            if (processMsgRet.equalsIgnoreCase("OK")) {
+                MesClient.resetScanA();
+                MesClient.setMenuStatus("结果提交成功,请扫下一件", 0);
+                MesClient.scan_type = 1;
+                MesClient.scanBarcode();
+            } else {
+                MesClient.setMenuStatus("结果提交失败,请重试", -1);
+            }
+        } catch (Exception e) {
+            log.error("[MES异常] updateResultRevice", e);
+        }
+    }
+}

+ 61 - 0
src/com/mes/ui/OprnoUtil.java

@@ -0,0 +1,61 @@
+package com.mes.ui;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+public class OprnoUtil {
+    public static String[] xtoprnos = new String[]{
+            "OP180"
+    };
+    public static String[] xtoprnodes = new String[]{
+            "框架总成8-FSW"
+    };
+    public static String[] lboprnos = new String[]{
+            "OP040","OP050","OP060","OP070","OP080","OP090","OP100","OP110",
+            "OP120","OP130","OP140","OP150","OP160","OP170","OP180","OP190",
+            "OP200","OP210","OP220"
+    };
+    public static String[] lboprnodes = new String[]{
+            "左右冷板FSW(反面)","左右冷板FSW(正面)","左右冷板正面CNC","左右冷板反面CNC","去毛刺吹铝屑","超声波清洗","冷板FSW堵头反面焊接","冷板FSW堵头正面焊接",
+            "打磨焊道","水嘴自动激光焊","底护板支撑柱+BDU柱+线束支架焊接","冷板气检","冷板总成正面CNC","冷板总成反面CNC","去毛刺吹铝屑,清洁","高压冲洗",
+            "M5+M6钢丝牙套安装","冷板汽检","冷板氦检"
+    };
+    public static String getGwDes(String lineSn,String oprno){
+        String des = "";
+        oprno = formatOprno(oprno);
+        if(lineSn.equals("XT")){
+            int i = 0;
+            for (String gw:xtoprnos){
+                if(gw.equals(oprno)){
+                    des = xtoprnodes[i];
+                    break;
+                }
+                i++;
+            }
+        }else if(lineSn.equals("LB")){
+            int i = 0;
+            for (String gw:lboprnos){
+                if(gw.equals(oprno)){
+                    des = lboprnodes[i];
+                    break;
+                }
+                i++;
+            }
+        }
+        return des;
+    }
+
+    public static String formatOprno(String oprno){
+        List<String> lists = new ArrayList<>();
+
+        if(oprno.length() == 6){
+            String ysoprno = oprno.substring(0,5).trim();
+            if(!lists.contains(ysoprno)){
+                oprno = ysoprno;
+            }
+        }
+
+        return  oprno;
+    }
+}

+ 558 - 0
src/com/mes/ui/S7Util.java

@@ -0,0 +1,558 @@
+package com.mes.ui;
+
+import com.github.s7connector.api.DaveArea;
+import com.github.s7connector.api.factory.S7ConnectorFactory;
+import com.github.xingshuangs.iot.protocol.s7.service.S7PLC;
+import com.mes.util.JdbcUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.swing.*;
+import java.math.BigInteger;
+import java.text.DecimalFormat;
+
+public class S7Util {
+
+    private static final Logger log = LoggerFactory.getLogger(S7Util.class);
+
+    private static final int DB9051 = 9051;
+    private static final int DB9051_LEN = 38;
+    private static final int DB9052 = 9052;
+
+    /** 连接失败后的重试间隔 */
+    private static final long RECONNECT_COOLDOWN_MS = 5000L;
+    private static volatile long nextReconnectAt = 0L;
+    private static volatile boolean connected = false;
+    /** 实测本设备 slot=2 可通;成功后优先复用 */
+    private static volatile int lastSuccessSlot = 2;
+
+    /**
+     * 监控线程入口:读 DB9051 一次,刷新界面并执行业务状态机
+     */
+    public static void pollDeviceCycle() {
+        try {
+            if (!ensureConnected()) {
+                SwingUtilities.invokeLater(() -> MesClient.updatePlcStatus(false));
+                return;
+            }
+            SwingUtilities.invokeLater(() -> MesClient.updatePlcStatus(true));
+            byte[] db9051;
+            try {
+                db9051 = MesClient.s7Connector.read(DaveArea.DB, DB9051, DB9051_LEN, 0);
+            } catch (Exception e) {
+                markBroken("读DB9051", e);
+                SwingUtilities.invokeLater(() -> MesClient.updatePlcStatus(false));
+                return;
+            }
+            if (db9051 == null) {
+                return;
+            }
+            updateRealtimeDisplay(db9051);
+            getDeviceState(db9051);
+        } catch (Exception e) {
+            log.error("[PLC异常] pollDeviceCycle", e);
+            markBroken("pollDeviceCycle", e);
+            SwingUtilities.invokeLater(() -> MesClient.updatePlcStatus(false));
+        }
+    }
+
+    public static synchronized boolean isConnected() {
+        return connected && MesClient.s7Connector != null;
+    }
+
+    public static synchronized void disconnect() {
+        connected = false;
+        if (MesClient.s7Connector != null) {
+            try {
+                MesClient.s7Connector.close();
+            } catch (Exception ignored) {
+            }
+            MesClient.s7Connector = null;
+        }
+    }
+
+    public static synchronized boolean connect() {
+        disconnect();
+        // Unexpected function code 常见于 rack/slot 不匹配:
+        // 旧版默认 slot=2;S7-1200 常用 slot=1。按历史成功值优先,再依次尝试。
+        int[] slots;
+        if (lastSuccessSlot == 1) {
+            slots = new int[]{1, 2};
+        } else if (lastSuccessSlot == 2) {
+            slots = new int[]{2, 1};
+        } else {
+            slots = new int[]{2, 1};
+        }
+
+        Exception lastError = null;
+        for (int slot : slots) {
+            try {
+                log.info("[PLC连接] 尝试 {} rack=0 slot={} port=102 timeout=5000", MesClient.plcUrl, slot);
+                MesClient.s7Connector = S7ConnectorFactory
+                        .buildTCPConnector()
+                        .withHost(MesClient.plcUrl)
+                        .withPort(102)
+                        .withRack(0)
+                        .withSlot(slot)
+                        .withTimeout(5000)
+                        .build();
+                byte[] probe = MesClient.s7Connector.read(DaveArea.DB, DB9051, DB9051_LEN, 0);
+                if (probe == null || probe.length < DB9051_LEN) {
+                    throw new IllegalStateException("探测读取DB9051返回空数据");
+                }
+                connected = true;
+                lastSuccessSlot = slot;
+                nextReconnectAt = 0L;
+                log.info("[PLC连接] 连接成功 {} rack=0 slot={}", MesClient.plcUrl, slot);
+                return true;
+            } catch (Exception e) {
+                lastError = e;
+                log.error("[PLC连接] rack=0 slot={} 失败: {}", slot, rootCause(e));
+                disconnect();
+                try {
+                    Thread.sleep(800);
+                } catch (InterruptedException ie) {
+                    Thread.currentThread().interrupt();
+                    break;
+                }
+            }
+        }
+        log.error("[PLC连接] 全部 slot 尝试失败 {}: {}", MesClient.plcUrl,
+                lastError == null ? "" : rootCause(lastError));
+        nextReconnectAt = System.currentTimeMillis() + RECONNECT_COOLDOWN_MS;
+        return false;
+    }
+
+    /**
+     * 确保可用连接:半开连接探测失败时强制断开再重连。
+     */
+    public static synchronized boolean ensureConnected() {
+        if (connected && MesClient.s7Connector != null) {
+            try {
+                // 心跳探测只读1字节,减轻通讯负担
+                byte[] probe = MesClient.s7Connector.read(DaveArea.DB, DB9051, 1, 0);
+                if (probe != null && probe.length >= 1) {
+                    return true;
+                }
+                log.info("[PLC连接] 探测读取异常,准备重连");
+            } catch (Exception e) {
+                log.info("[PLC连接] 连接已失效,准备重连: {}", rootCause(e));
+            }
+            disconnect();
+        }
+        if (System.currentTimeMillis() < nextReconnectAt) {
+            return false;
+        }
+        return connect();
+    }
+
+    private static synchronized void markBroken(String action, Exception e) {
+        log.info("[PLC] {} 失败,释放连接: {}", action, rootCause(e));
+        disconnect();
+        nextReconnectAt = System.currentTimeMillis() + RECONNECT_COOLDOWN_MS;
+    }
+
+    private static String rootCause(Throwable e) {
+        if (e == null) {
+            return "";
+        }
+        Throwable cur = e;
+        while (cur.getCause() != null && cur.getCause() != cur) {
+            cur = cur.getCause();
+        }
+        if (cur == e) {
+            return e.getClass().getSimpleName() + ": " + e.getMessage();
+        }
+        return e.getClass().getSimpleName() + "(" + e.getMessage() + ") <- "
+                + cur.getClass().getSimpleName() + ": " + cur.getMessage();
+    }
+
+    // 监听状态
+    public static void getDeviceState(byte[] db9051){
+        try {
+            if (MesClient.s7Connector == null || db9051 == null) {
+                return;
+            }
+
+            if (MesClient.tjFlag == 3) {
+                if (MesClient.tjStatus == 0) {
+                    MesClient.tjStatus = 1;
+                    log.info("[流程] 焊接完成,复位允许启动并提交MES总结果 OK,工件={}",
+                            MesClient.product_sn.getText());
+                    sendAllowStart(false);
+                    Boolean ret = DataUtil.sendQuality(
+                            MesClient.nettyClient, MesClient.product_sn.getText(), "OK", MesClient.user20);
+                    if (ret) {
+                        log.info("[MES写] MQDW 提交成功,工件={}", MesClient.product_sn.getText());
+                        MesClient.resetScanA();
+                        MesClient.scan_type = 1;
+                        MesClient.scanBarcode();
+                        MesClient.setMenuStatus("结果提交成功,请扫下一件", 0);
+                    } else {
+                        log.warn("[MES写] MQDW 提交失败,工件={},等待重试", MesClient.product_sn.getText());
+                        MesClient.tjStatus = 0;
+                        MesClient.setMenuStatus(MesClient.tjFlagTextErr, -1);
+                    }
+                }
+            } else if (isWaitingProcess()) {
+                if (isWeldingComplete(db9051)) {
+                    log.info("[流程] 检测到焊接完成 DB9051.DBX36.0=true,tjFlag: {} -> 3", MesClient.tjFlag);
+                    MesClient.tjFlag = 3;
+                    MesClient.tjStatus = 0;
+                    MesClient.status_menu.setText(MesClient.tjFlagText3);
+                }
+            } else if (MesClient.tjFlag == 0) {
+                if (getAllowStart()) {
+                    log.info("[流程] 未扫码状态检测到允许启动仍为true,执行复位");
+                    sendAllowStart(false);
+                }
+            }
+
+        }catch (Exception e){
+            log.error("[流程异常] getDeviceState", e);
+        }
+    }
+
+    /** @deprecated 请使用 pollDeviceCycle */
+    public static void getDeviceState(){
+        byte[] db9051 = readDb9051Raw(true);
+        if (db9051 != null) {
+            getDeviceState(db9051);
+        }
+    }
+
+    /**
+     * 实时刷新 DB9051 主轴转速、进给速度、压力值到界面
+     */
+    public static void updateRealtimeDisplay(byte[] data) {
+        try {
+            if (data == null || MesClient.spindleSpeedLabel == null) {
+                return;
+            }
+            final String spindle = formatS7Val(subBytes(data, 0, 4));
+            final String feed = formatS7Val(subBytes(data, 4, 4));
+            final String pressure = formatS7Val(subBytes(data, 12, 4));
+
+            saveFswParamIfProcessing(spindle, feed, pressure);
+
+            SwingUtilities.invokeLater(() ->
+                    MesClient.updatePlcDisplay(spindle, feed, pressure));
+        } catch (Exception e) {
+            log.error("[PLC异常] updateRealtimeDisplay", e);
+        }
+    }
+
+    /** @deprecated 请使用 pollDeviceCycle */
+    public static void updateRealtimeDisplay() {
+        byte[] data = readDb9051Raw(true);
+        updateRealtimeDisplay(data);
+    }
+
+    private static byte[] readDb9051Raw(boolean withLog) {
+        try {
+            if (!ensureConnected()) {
+                if (withLog) {
+                    log.warn("[PLC读] DB9051 失败:S7未连接");
+                }
+                return null;
+            }
+            byte[] data = MesClient.s7Connector.read(DaveArea.DB, DB9051, DB9051_LEN, 0);
+            if (withLog) {
+                log.info(formatDb9051Log(data));
+            }
+            return data;
+        } catch (Exception e) {
+            log.error("[PLC读] DB9051 异常", e);
+            markBroken("读DB9051", e);
+            return null;
+        }
+    }
+
+    static String formatDb9051Log(byte[] data) {
+        if (data == null) {
+            return "[PLC读] DB9051 数据为空";
+        }
+        return String.format(
+                "[PLC读] DB9051 | 主轴转速=%s(HEX:%s) 进给速度=%s(HEX:%s) 压力值=%s(HEX:%s) | " +
+                        "焊接长度1=%s 2=%s 3=%s 4=%s 5=%s | 焊接完成(DBX36.0)=%s 出站OK(DBB37)=%d | tjFlag=%d work_status=%d",
+                formatS7Val(subBytes(data, 0, 4)), bytesToHex(subBytes(data, 0, 4)),
+                formatS7Val(subBytes(data, 4, 4)), bytesToHex(subBytes(data, 4, 4)),
+                formatS7Val(subBytes(data, 12, 4)), bytesToHex(subBytes(data, 12, 4)),
+                formatS7Val(subBytes(data, 16, 4)),
+                formatS7Val(subBytes(data, 20, 4)),
+                formatS7Val(subBytes(data, 24, 4)),
+                formatS7Val(subBytes(data, 28, 4)),
+                formatS7Val(subBytes(data, 32, 4)),
+                isWeldingComplete(data),
+                data[37] & 0xFF,
+                MesClient.tjFlag,
+                MesClient.work_status
+        );
+    }
+
+    /** 等待加工中(质量合格、尚未收到焊接完成),不含 tjFlag=3 提交阶段 */
+    private static boolean isWaitingProcess() {
+        return MesClient.tjFlag == 1;
+    }
+
+    private static boolean isMeaningfulParam(String value) {
+        if (value == null || value.trim().isEmpty() || "--".equals(value.trim())) {
+            return false;
+        }
+        try {
+            float v = Float.parseFloat(value.trim());
+            return !Float.isNaN(v) && !Float.isInfinite(v) && Math.abs(v) > 1e-4f;
+        } catch (Exception e) {
+            return false;
+        }
+    }
+
+    private static void saveFswParamIfProcessing(String spindleSpeed, String feedRate, String pressure) {
+        if (!isWaitingProcess()) {
+            return;
+        }
+        String sn = MesClient.product_sn.getText();
+        if (sn == null || sn.trim().isEmpty()) {
+            return;
+        }
+        // 设备未启动前三个参数多为0,等任一非0再开始存,避免无用数据
+        if (!MesClient.paramRecordingStarted) {
+            if (isMeaningfulParam(spindleSpeed) || isMeaningfulParam(feedRate) || isMeaningfulParam(pressure)) {
+                MesClient.paramRecordingStarted = true;
+                log.info("[过程参数] 检测到有效数据,开始缓存 sn={}", sn.trim());
+            } else {
+                return;
+            }
+        }
+        MesClient.getUser();
+        boolean saved = JdbcUtils.insertFswParam(
+                MesClient.mes_gw,
+                MesClient.mes_line_sn,
+                sn.trim(),
+                spindleSpeed,
+                feedRate,
+                pressure,
+                MesClient.user20.trim()
+        );
+        if (saved) {
+            log.debug("[过程参数] 本地缓存 sn={} 主轴={} 进给={} 压力={}",
+                    sn.trim(), spindleSpeed, feedRate, pressure);
+        }
+    }
+
+    /** DB9051.DBX36.0 焊接完成(BOOL) */
+    private static boolean isWeldingComplete(byte[] data) {
+        if (data.length <= 36) {
+            return false;
+        }
+        return (data[36] & (1 << 0)) != 0;
+    }
+
+    private static byte[] subBytes(byte[] src, int offset, int length) {
+        byte[] dest = new byte[length];
+        System.arraycopy(src, offset, dest, 0, length);
+        return dest;
+    }
+
+    //屏蔽mes交互  如果设备禁止启动  则启动设备
+    public static void getDeviceShield(){
+        try {
+            if (!getAllowStart()) {
+                log.info("[MES屏蔽] 强制发送允许启动 DB9052.DBX0.0=true");
+                sendAllowStart(true);
+            }
+        }catch (Exception e){
+            log.error("[MES屏蔽异常] getDeviceShield", e);
+        }
+    }
+
+    // 监听急停
+    public static void checkStop(){
+        try {
+            if (!ensureConnected()) {
+                return;
+            }
+
+            byte[] bytes = MesClient.s7Connector.read(DaveArea.DB, DB9052, 1, 0);
+            log.info(formatDb9052Log(bytes[0], "读-急停检测"));
+
+            int jtstatus = getBit(bytes[0], 7);
+            log.info("[PLC读] DB9052.DBX0.7 急停状态={}", jtstatus);
+
+            if(jtstatus == 0){
+                switchEnable(0);
+            }
+
+            if(MesClient.tjFlag == 2 && jtstatus == 0){
+                MesClient.tjResult = "NG";
+                MesClient.finish_ok_bt.setEnabled(true);
+                MesClient.finish_ng_bt.setEnabled(true);
+            }
+        }catch (Exception e){
+            log.error("[PLC异常] checkStop", e);
+            markBroken("checkStop", e);
+        }
+    }
+
+    public static int getBit(byte b, int n) {
+        String binaryString = Integer.toBinaryString(b & 0xFF);
+        binaryString = String.format("%8s", binaryString).replace(' ', '0');
+        return binaryString.charAt(n) == '1' ? 1 : 0;
+    }
+
+    private static String formatDb9052Log(byte b, String action) {
+        boolean allowStart = (b & (1 << 0)) != 0;
+        return String.format("[PLC%s] DB9052.DBB0=0x%02X DBX0.0(允许启动)=%s DBX0.7(急停)=%d",
+                action, b & 0xFF, allowStart, getBit(b, 7));
+    }
+
+    // 转大端排序
+    private static byte[] xtob( byte[] bytes){
+        byte[] reversedBytes = new byte[bytes.length];
+        System.arraycopy(bytes, 0, reversedBytes, 0, bytes.length);
+        for (int i = 0; i < bytes.length / 2; i++) {
+            byte temp = reversedBytes[i];
+            reversedBytes[i] = reversedBytes[reversedBytes.length - 1 - i];
+            reversedBytes[reversedBytes.length - 1 - i] = temp;
+        }
+        return reversedBytes;
+    }
+
+    private static String bytesToHex(byte[] bytes) {
+        StringBuilder sb = new StringBuilder();
+        for (byte b : bytes) {
+            sb.append(String.format("%02X", b & 0xFF));
+        }
+        return sb.toString();
+    }
+
+    // 格式化 S7 REAL(大端 IEEE754,不做字节反转)
+    private static float parseS7Real(byte[] val) {
+        if (val == null || val.length < 4) {
+            return 0f;
+        }
+        int bits = ((val[0] & 0xFF) << 24)
+                | ((val[1] & 0xFF) << 16)
+                | ((val[2] & 0xFF) << 8)
+                | (val[3] & 0xFF);
+        return Float.intBitsToFloat(bits);
+    }
+
+    private static String formatS7Val(byte[] val){
+        float floatValue = parseS7Real(val);
+        if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) {
+            return "0.0";
+        }
+        DecimalFormat df = new DecimalFormat("#.#");
+        df.setMaximumFractionDigits(1);
+        return df.format(floatValue);
+    }
+
+    // 禁止/启用启动
+    public static Boolean switchEnable(int state){
+        try{
+            log.info("[PLC写] switchEnable state={} -> DB9052.DBX0.0={}", state, state == 1);
+            sendAllowStart(state == 1);
+            return true;
+        }catch (Exception e){
+            log.error("[PLC异常] switchEnable", e);
+            return false;
+        }
+    }
+
+    // 获取 DB9052.DBX0.0 允许启动状态
+    public static boolean getAllowStart() {
+        try {
+            if (!ensureConnected()) {
+                return false;
+            }
+            byte[] data = MesClient.s7Connector.read(DaveArea.DB, DB9052, 1, 0);
+            log.info(formatDb9052Log(data[0], "读-允许启动"));
+            return (data[0] & (1 << 0)) != 0;
+        } catch (Exception e) {
+            log.error("[PLC读] DB9052 允许启动 异常", e);
+            markBroken("读允许启动", e);
+            return false;
+        }
+    }
+
+    // 获取允许运行状态
+    public static Integer getSwitchEnable(){
+        try{
+            if (!ensureConnected()) {
+                return 0;
+            }
+            byte[] data = MesClient.s7Connector.read(DaveArea.DB, DB9052, 1, 0);
+            log.info(formatDb9052Log(data[0], "读-整字节"));
+            return new BigInteger(xtob(data)).intValue();
+        }catch (Exception e){
+            log.error("[PLC读] DB9052 整字节 异常", e);
+            markBroken("读DB9052", e);
+            return 0;
+        }
+    }
+
+    /** DB9052.DBX0.0 允许启动信号:true=允许,false=禁止/复位 */
+    public static boolean sendAllowStart(boolean allow) {
+        log.info("[PLC写] 请求设置 DB9052.DBX0.0 允许启动={}", allow);
+        return writeBit(DB9052, 0, 0, allow);
+    }
+
+    /**
+     * 兼容旧接口:true=禁止启动,false=允许启动
+     */
+    public static boolean sendStartSignal(boolean forbidStart) {
+        return sendAllowStart(!forbidStart);
+    }
+
+    public static boolean writeBit(int dbNumber, int byteIndex, int bitIndex, boolean value) {
+        try {
+            if (!ensureConnected()) {
+                log.warn("[PLC写] DB{}.DBX{}.{} 失败:S7未连接", dbNumber, byteIndex, bitIndex);
+                return false;
+            }
+            byte[] data = MesClient.s7Connector.read(DaveArea.DB, dbNumber, 1, byteIndex);
+            byte oldByte = data[0];
+            boolean oldBit = (oldByte & (1 << bitIndex)) != 0;
+            byte b = oldByte;
+
+            if (value) {
+                b = (byte)(b | (1 << bitIndex));
+            } else {
+                b = (byte)(b & ~(1 << bitIndex));
+            }
+
+            byte[] toWrite = new byte[]{b};
+            MesClient.s7Connector.write(DaveArea.DB, dbNumber, byteIndex, toWrite);
+
+            log.info("[PLC写] DB{}.DBX{}.{} {} -> {} | DBB{}: 0x{} -> 0x{}",
+                    dbNumber, byteIndex, bitIndex, oldBit, value,
+                    byteIndex,
+                    String.format("%02X", oldByte & 0xFF),
+                    String.format("%02X", b & 0xFF));
+
+            if (dbNumber == DB9052 && byteIndex == 0 && bitIndex == 0) {
+                log.info("[PLC写] DB9052.DBX0.0 允许启动信号已设为 {}", value);
+            }
+            return true;
+        } catch (Exception e) {
+            log.error("[PLC写] DB{}.DBX{}.{} 异常", dbNumber, byteIndex, bitIndex, e);
+            markBroken("写位", e);
+            return false;
+        }
+    }
+
+    // 获取运行的程序名
+    public static String getProgramName(S7PLC s7PLC){
+        String programName = "";
+        try{
+            programName = s7PLC.readProgramName();
+            log.info("[PLC读] 当前程序名={}", programName);
+        }catch (Exception e){
+            log.error("[PLC读] 程序名异常", e);
+            programName = "";
+        }
+        return programName;
+    }
+
+}

+ 43 - 0
src/com/mes/ui/TableCellEditorButton.java

@@ -0,0 +1,43 @@
+package com.mes.ui;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+public class TableCellEditorButton extends DefaultCellEditor {
+    private JButton btn;
+    public TableCellEditorButton() {
+        super(new JTextField());
+        //设置点击一次就激活,否则默认好像是点击2次激活。
+        this.setClickCountToStart(1);
+        btn = new JButton("扫码");
+        btn.addActionListener(new ActionListener() {
+
+            @Override
+            public void actionPerformed(ActionEvent e) {
+                System.out.println("按钮事件触发----");
+                int selectedRow = MesClient.table.getSelectedRow();//获得选中行的索引
+//                MesClient.rowData[selectedRow][1] = (new Date()).getTime();
+//                MesClient.table.repaint(); //重绘
+
+//                MesClient.scan_type = selectedRow + 4;
+                BindMaterialResp bindMaterialResp = new BindMaterialResp();
+                bindMaterialResp.setMaterialTitle(MesClient.rowData[selectedRow][0] + "");
+                bindMaterialResp.setBatchSn(MesClient.rowData[selectedRow][1] + "");
+                bindMaterialResp.setLastTimes(MesClient.rowData[selectedRow][2] + "");
+                bindMaterialResp.setCraft(MesClient.rowData[selectedRow][4] + "");
+                bindMaterialResp.setMaterialId(MesClient.rowData[selectedRow][5] + "");
+                bindMaterialResp.setType(MesClient.rowData[selectedRow][6] + "");
+
+                MesClient.scanBatchSn(bindMaterialResp);
+            }
+        });
+
+    }
+    @Override
+    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
+
+        return btn;
+    }
+}

+ 14 - 0
src/com/mes/ui/TableCellRendererButton.java

@@ -0,0 +1,14 @@
+package com.mes.ui;
+
+import javax.swing.*;
+import javax.swing.table.TableCellRenderer;
+import java.awt.*;
+
+public class TableCellRendererButton implements TableCellRenderer {
+    @Override
+    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
+                                                   int row, int column) {
+        JButton button = new JButton("扫码");
+        return button;
+    }
+}

+ 11 - 0
src/com/mes/util/Base64Utils.java

@@ -0,0 +1,11 @@
+package com.mes.util;
+
+import org.apache.commons.codec.binary.Base64;
+
+public class Base64Utils {
+	public static String getBase64(String str) {
+        byte[] binaryData = str.getBytes();
+        String encodedString = Base64.encodeBase64String(binaryData);
+        return encodedString;
+	}
+}

+ 32 - 0
src/com/mes/util/DateLocalUtils.java

@@ -0,0 +1,32 @@
+package com.mes.util;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+public class DateLocalUtils {
+	public static SimpleDateFormat DATA_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
+	public static SimpleDateFormat DATA_FORMAT1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
+	
+	
+	public static String getCurrentTime() {
+		String currentTime = DATA_FORMAT.format(new Date());
+		return currentTime;
+	}
+	
+	public static String getCurrentTime1() {
+		String currentTime = DATA_FORMAT1.format(new Date());
+		return currentTime;
+	}
+
+	public static SimpleDateFormat DATA_FORMAT2 = new SimpleDateFormat("yyyy-MM-dd");
+	public static String getCurrentDate() {
+		String currentTime = DATA_FORMAT2.format(new Date());
+		return currentTime;
+	}
+
+	public static SimpleDateFormat DATA_FORMAT3 = new SimpleDateFormat("HH:mm:ss");
+	public static String getCurrentTimeHMS() {
+		String currentTime = DATA_FORMAT3.format(new Date());
+		return currentTime;
+	}
+}

+ 168 - 0
src/com/mes/util/Db9051Test.java

@@ -0,0 +1,168 @@
+package com.mes.util;
+
+import com.github.s7connector.api.DaveArea;
+import com.mes.ui.MesClient;
+
+import java.text.DecimalFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * DB9051 循环监听测试
+ * <p>
+ * 地址布局:
+ * 0.0  主轴转速   REAL
+ * 4.0  进给速度   REAL
+ * 8.0  Z轴坐标    REAL
+ * 12.0 压力值     REAL
+ * 16.0 焊接长度1  REAL
+ * 20.0 焊接长度2  REAL
+ * 24.0 焊接长度3  REAL
+ * 28.0 焊接长度4  REAL
+ * 32.0 焊接长度5  REAL
+ * 36.0 焊接完成   BOOL (DBX36.0)
+ * 37.0 出站OK     BYTE
+ */
+public class Db9051Test {
+
+    private static final int DB_NUMBER = 9051;
+    private static final int DB_LENGTH = 38;
+
+    // ===== 测试参数,运行前修改此处 =====
+    private static final String PLC_IP = "192.168.88.99";
+    private static final int POLL_INTERVAL_MS = 500;  // 轮询间隔(毫秒)
+    // ===================================
+
+    private static final SimpleDateFormat TIME_FMT = new SimpleDateFormat("HH:mm:ss.SSS");
+    private static Boolean lastWeldingComplete = null;
+
+    public static void main(String[] args) {
+        MesClient.plcUrl = PLC_IP;
+        System.out.println("========== DB9051 循环监听测试 ==========");
+        System.out.println("PLC 地址: " + MesClient.plcUrl);
+        System.out.println("轮询间隔: " + POLL_INTERVAL_MS + "ms");
+        System.out.println("按 Ctrl+C 停止");
+        System.out.println("=========================================");
+
+        MesClient.initS7();
+        if (MesClient.s7Connector == null) {
+            printConnectionHelp();
+            return;
+        }
+        System.out.println("S7 连接成功,开始监听...\n");
+
+        while (true) {
+            try {
+                Map<String, Object> data = readDb9051();
+                if (data.isEmpty()) {
+                    System.err.println("[" + now() + "] 读取失败,1秒后重试...");
+                    Thread.sleep(1000);
+                    continue;
+                }
+
+                boolean weldingComplete = (Boolean) data.get("DB9051.DBX36.0 焊接完成");
+                printCycle(data, weldingComplete);
+
+                Thread.sleep(POLL_INTERVAL_MS);
+            } catch (InterruptedException e) {
+                System.out.println("\n监听已停止");
+                Thread.currentThread().interrupt();
+                break;
+            } catch (Exception e) {
+                System.err.println("[" + now() + "] 异常: " + e.getMessage());
+                e.printStackTrace();
+                try {
+                    Thread.sleep(1000);
+                } catch (InterruptedException ie) {
+                    Thread.currentThread().interrupt();
+                    break;
+                }
+            }
+        }
+    }
+
+    private static void printCycle(Map<String, Object> data, boolean weldingComplete) {
+        StringBuilder sb = new StringBuilder();
+        sb.append("[").append(now()).append("] ");
+        sb.append("主轴=").append(data.get("DB9051.DBD0  主轴转速"));
+        sb.append(" 进给=").append(data.get("DB9051.DBD4  进给速度"));
+        sb.append(" 压力=").append(data.get("DB9051.DBD12 压力值"));
+        sb.append(" | 焊接完成=").append(weldingComplete);
+        sb.append(" 出站OK=").append(data.get("DB9051.DBB37 出站OK"));
+        System.out.println(sb);
+
+        if (lastWeldingComplete != null && !lastWeldingComplete && weldingComplete) {
+            System.out.println(">>> [" + now() + "] 焊接完成信号上升沿 DB9051.DBX36.0: false -> true");
+            printFullDetail(data);
+        }
+        lastWeldingComplete = weldingComplete;
+    }
+
+    private static void printFullDetail(Map<String, Object> data) {
+        System.out.println("--- DB9051 全量数据 ---");
+        data.forEach((key, value) -> System.out.println("  " + key + " = " + value));
+        System.out.println("-----------------------");
+    }
+
+    /**
+     * 读取 DB9051 全部字段
+     */
+    public static Map<String, Object> readDb9051() {
+        Map<String, Object> result = new LinkedHashMap<>();
+        try {
+            MesClient.initS7();
+            if (MesClient.s7Connector == null) {
+                return result;
+            }
+            byte[] data = MesClient.s7Connector.read(DaveArea.DB, DB_NUMBER, DB_LENGTH, 0);
+
+            result.put("DB9051.DBD0  主轴转速", formatS7Float(subBytes(data, 0, 4)));
+            result.put("DB9051.DBD4  进给速度", formatS7Float(subBytes(data, 4, 4)));
+            result.put("DB9051.DBD8  Z轴坐标", formatS7Float(subBytes(data, 8, 4)));
+            result.put("DB9051.DBD12 压力值", formatS7Float(subBytes(data, 12, 4)));
+            result.put("DB9051.DBD16 焊接长度1", formatS7Float(subBytes(data, 16, 4)));
+            result.put("DB9051.DBD20 焊接长度2", formatS7Float(subBytes(data, 20, 4)));
+            result.put("DB9051.DBD24 焊接长度3", formatS7Float(subBytes(data, 24, 4)));
+            result.put("DB9051.DBD28 焊接长度4", formatS7Float(subBytes(data, 28, 4)));
+            result.put("DB9051.DBD32 焊接长度5", formatS7Float(subBytes(data, 32, 4)));
+            result.put("DB9051.DBX36.0 焊接完成", (data[36] & (1 << 0)) != 0);
+            result.put("DB9051.DBB37 出站OK", data[37] & 0xFF);
+        } catch (Exception e) {
+            System.err.println("读取 DB9051 失败: " + e.getMessage());
+        }
+        return result;
+    }
+
+    private static String now() {
+        return TIME_FMT.format(new Date());
+    }
+
+    private static void printConnectionHelp() {
+        System.err.println("PLC 连接失败,请检查:");
+        System.err.println("  1. PLC IP 是否正确,当前: " + MesClient.plcUrl);
+        System.err.println("  2. 本机是否与 PLC 在同一网段");
+        System.err.println("  3. 修改 Db9051Test.PLC_IP / POLL_INTERVAL_MS");
+    }
+
+    private static byte[] subBytes(byte[] src, int offset, int length) {
+        byte[] dest = new byte[length];
+        System.arraycopy(src, offset, dest, 0, length);
+        return dest;
+    }
+
+    private static float formatS7Float(byte[] val) {
+        if (val == null || val.length < 4) {
+            return 0f;
+        }
+        int bits = ((val[0] & 0xFF) << 24)
+                | ((val[1] & 0xFF) << 16)
+                | ((val[2] & 0xFF) << 8)
+                | (val[3] & 0xFF);
+        float floatValue = Float.intBitsToFloat(bits);
+        DecimalFormat df = new DecimalFormat("#.#");
+        df.setMaximumFractionDigits(1);
+        return Float.parseFloat(df.format(floatValue));
+    }
+}

+ 92 - 0
src/com/mes/util/Db9052Test.java

@@ -0,0 +1,92 @@
+package com.mes.util;
+
+import com.github.s7connector.api.DaveArea;
+import com.mes.ui.MesClient;
+
+/**
+ * DB9052 数据块写入测试
+ * <p>
+ * 地址布局:
+ * 0.0  A   BOOL
+ */
+public class Db9052Test {
+
+    private static final int DB_NUMBER = 9052;
+    private static final int BYTE_INDEX = 0;
+    private static final int BIT_INDEX = 0;
+
+    // ===== 测试参数,运行前修改此处 =====
+    private static final String PLC_IP = "192.168.88.99";
+    private static final boolean WRITE_VALUE = true;  // true=ON, false=OFF
+    // ===================================
+
+    public static void main(String[] args) {
+        MesClient.plcUrl = PLC_IP;
+        System.out.println("PLC 地址: " + MesClient.plcUrl);
+        System.out.println("写入 DB9052.DBX0.0 (A) = " + WRITE_VALUE);
+
+        if (writeA(WRITE_VALUE)) {
+            System.out.println("写入成功,回读: " + readA());
+        } else {
+            System.out.println("写入失败");
+        }
+    }
+
+    /**
+     * 写入 DB9052.DBX0.0 (A)
+     */
+    public static boolean writeA(boolean value) {
+        return writeBit(BYTE_INDEX, BIT_INDEX, value);
+    }
+
+    /**
+     * 读取 DB9052.DBX0.0 (A)
+     */
+    public static boolean readA() {
+        try {
+            MesClient.initS7();
+            if (MesClient.s7Connector == null) {
+                printConnectionHelp();
+                return false;
+            }
+            byte[] data = MesClient.s7Connector.read(DaveArea.DB, DB_NUMBER, 1, BYTE_INDEX);
+            return (data[0] & (1 << BIT_INDEX)) != 0;
+        } catch (Exception e) {
+            System.err.println("读取 DB9052 失败: " + e.getMessage());
+            e.printStackTrace();
+            return false;
+        }
+    }
+
+    /**
+     * 写入指定位(与 Test.writeBit / S7Util.writeBit 一致:先读后改再写)
+     */
+    public static boolean writeBit(int byteIndex, int bitIndex, boolean value) {
+        try {
+            MesClient.initS7();
+            if (MesClient.s7Connector == null) {
+                printConnectionHelp();
+                return false;
+            }
+            byte[] data = MesClient.s7Connector.read(DaveArea.DB, DB_NUMBER, 1, byteIndex);
+            byte b = data[0];
+
+            if (value) {
+                b = (byte) (b | (1 << bitIndex));
+            } else {
+                b = (byte) (b & ~(1 << bitIndex));
+            }
+
+            MesClient.s7Connector.write(DaveArea.DB, DB_NUMBER, byteIndex, new byte[]{b});
+            return true;
+        } catch (Exception e) {
+            System.err.println("写入 DB9052 失败: " + e.getMessage());
+            e.printStackTrace();
+            return false;
+        }
+    }
+
+    private static void printConnectionHelp() {
+        System.err.println("PLC 连接失败,请检查 IP 与网络,当前: " + MesClient.plcUrl);
+    }
+}

+ 63 - 0
src/com/mes/util/ErrorMsg.java

@@ -0,0 +1,63 @@
+package com.mes.util;
+
+import com.mes.netty.ProtocolParam;
+
+public class ErrorMsg {
+    public static String getErrorMsg(String processMsgRet,String mes_msg){
+        String lmsg = "该工件本工位不可加工";
+        try{
+
+            String lxpre = ProtocolParam.getLx(mes_msg);
+            String da = mes_msg.substring(74,76);
+            String lastChar = da.substring(0,1);
+            String lx = lxpre + lastChar;
+
+            if(processMsgRet.equalsIgnoreCase("OK")||processMsgRet.equalsIgnoreCase("NG")) {
+                lmsg = "该工件本工位已加工,结果:"+processMsgRet;
+            }else if(processMsgRet.equalsIgnoreCase("NE")) {
+                lmsg = "该工件未录入系统";
+            }else if(processMsgRet.equalsIgnoreCase("NN")) {
+                lmsg = "该工件跳过该工位";
+            }else if(processMsgRet.equalsIgnoreCase("QN")) {
+                lmsg = "该工件OP"+ lx+"加工NG";
+            }else if(processMsgRet.equalsIgnoreCase("QD")) {
+                lmsg = "该工件OP"+ lx+"未加工";
+            }else if(processMsgRet.equalsIgnoreCase("NF")) {
+                lmsg = "该工件已合格下线";
+            }else if(processMsgRet.equalsIgnoreCase("NR")) {
+                lmsg = "该工件离线返修中";
+            }else if(processMsgRet.equalsIgnoreCase("NB")) {
+                lmsg = "该工件已报废";
+            }else if(processMsgRet.equalsIgnoreCase("ND")) {
+                lmsg = "该工件NG待处理";
+            }else if(processMsgRet.equalsIgnoreCase("FN")) {
+                lmsg = "首件检查工件不合格停机";
+            }else if(processMsgRet.equalsIgnoreCase("GN")) {
+                lmsg = "更换配件首件检查不合格停机";
+            }else if(processMsgRet.equalsIgnoreCase("DJ")) {
+                lmsg = "未进行开班点检";
+            }else if(processMsgRet.equalsIgnoreCase("BM")) {
+                lmsg = "未绑定物料";
+            }else if(processMsgRet.equalsIgnoreCase("PL")) {
+                lmsg = "配件寿命不足";
+            }else if(processMsgRet.equalsIgnoreCase("QM")) {
+                lmsg = "两次气密必须间隔15分钟";
+            }else if(processMsgRet.equalsIgnoreCase("GS")) {
+                lmsg = "工件码格式不正确";
+            }else if(processMsgRet.equalsIgnoreCase("CF")) {
+                lmsg = "工件码重复";
+            }else if(processMsgRet.equalsIgnoreCase("GQ")) {
+                lmsg = "物料过期";
+            }else if(processMsgRet.equalsIgnoreCase("JL")) {
+                lmsg = "胶水失效或未绑定";
+            }else if(processMsgRet.equalsIgnoreCase("BD")) {//OP280底护板装配专用
+                lmsg = "未绑定底护板";
+            }else if(processMsgRet.equalsIgnoreCase("JZ")) {
+                lmsg = "涂胶静置时间超过规定时长";
+            }else if(processMsgRet.equalsIgnoreCase("TT")) {
+                lmsg = "套筒涂胶静置时间未达到规定时长";
+            }
+        }catch (Exception e){ }
+        return lmsg;
+    }
+}

+ 0 - 0
src/com/mes/util/FswParamReq.java


Beberapa file tidak ditampilkan karena terlalu banyak file yang berubah dalam diff ini