zxl 3 minggu lalu
melakukan
20d45d4c66
79 mengubah file dengan 3473 tambahan dan 0 penghapusan
  1. 22 0
      .gitignore
  2. TEMPAT SAMPAH
      lib/iot-communication-1.4.4.jar
  3. 5 0
      pack/build-exe.bat
  4. 6 0
      pack/build-exe.ps1
  5. TEMPAT SAMPAH
      pack/icon.ico
  6. 64 0
      pom.xml
  7. 59 0
      src/main/java/com/mes/MesClientApplication.java
  8. 111 0
      src/main/java/com/mes/config/DcPressProfiles.java
  9. 148 0
      src/main/java/com/mes/config/MesClientProperties.java
  10. 31 0
      src/main/java/com/mes/entity/DcRunSnapshot.java
  11. 29 0
      src/main/java/com/mes/entity/DcWorkRecord.java
  12. 113 0
      src/main/java/com/mes/service/DcBatchPrinter.java
  13. 24 0
      src/main/java/com/mes/service/DcPackCode.java
  14. 229 0
      src/main/java/com/mes/service/DcPlcClient.java
  15. 44 0
      src/main/java/com/mes/service/DcWorkRecordStore.java
  16. 87 0
      src/main/java/com/mes/service/MesApiClient.java
  17. 148 0
      src/main/java/com/mes/service/MesDcApiClient.java
  18. 259 0
      src/main/java/com/mes/service/MesFlexQueuePushClient.java
  19. 101 0
      src/main/java/com/mes/ui/BreathingLight.java
  20. 459 0
      src/main/java/com/mes/ui/MainFrame.java
  21. 903 0
      src/main/java/com/mes/ui/StationPanel.java
  22. 72 0
      src/main/java/com/mes/ui/StatusLight.java
  23. 225 0
      src/main/java/com/mes/ui/UiTheme.java
  24. 117 0
      src/main/java/com/mes/ui/WorkRecordPanel.java
  25. 89 0
      src/main/java/com/mes/util/SingleInstanceLock.java
  26. 47 0
      src/main/java/com/mes/util/UiImages.java
  27. 37 0
      src/main/resources/config/application.yml
  28. TEMPAT SAMPAH
      src/main/resources/images/background.png
  29. TEMPAT SAMPAH
      src/main/resources/images/close_bt.png
  30. TEMPAT SAMPAH
      src/main/resources/images/icon.ico
  31. TEMPAT SAMPAH
      src/main/resources/images/icons/a_side.png
  32. TEMPAT SAMPAH
      src/main/resources/images/icons/b_side.png
  33. TEMPAT SAMPAH
      src/main/resources/images/icons/bar_add.png
  34. TEMPAT SAMPAH
      src/main/resources/images/icons/bar_bookmark.png
  35. TEMPAT SAMPAH
      src/main/resources/images/icons/bar_cmd_go.png
  36. TEMPAT SAMPAH
      src/main/resources/images/icons/bar_edit.png
  37. TEMPAT SAMPAH
      src/main/resources/images/icons/bar_pause.png
  38. TEMPAT SAMPAH
      src/main/resources/images/icons/bar_sampling.png
  39. TEMPAT SAMPAH
      src/main/resources/images/icons/bar_setting.png
  40. TEMPAT SAMPAH
      src/main/resources/images/icons/bar_stop.png
  41. TEMPAT SAMPAH
      src/main/resources/images/icons/close_bt.png
  42. TEMPAT SAMPAH
      src/main/resources/images/icons/company_setting_logo.png
  43. TEMPAT SAMPAH
      src/main/resources/images/icons/delete.png
  44. TEMPAT SAMPAH
      src/main/resources/images/icons/department_setting_logo.png
  45. TEMPAT SAMPAH
      src/main/resources/images/icons/download.png
  46. TEMPAT SAMPAH
      src/main/resources/images/icons/equipment_setting_logo.png
  47. TEMPAT SAMPAH
      src/main/resources/images/icons/gj_001_1_20.png
  48. TEMPAT SAMPAH
      src/main/resources/images/icons/gj_001_21_40.png
  49. TEMPAT SAMPAH
      src/main/resources/images/icons/gj_001_41_60.png
  50. TEMPAT SAMPAH
      src/main/resources/images/icons/green_dot.png
  51. TEMPAT SAMPAH
      src/main/resources/images/icons/grey_dot.png
  52. TEMPAT SAMPAH
      src/main/resources/images/icons/icon.png
  53. TEMPAT SAMPAH
      src/main/resources/images/icons/inductance_logo.png
  54. TEMPAT SAMPAH
      src/main/resources/images/icons/insulation_logo.png
  55. TEMPAT SAMPAH
      src/main/resources/images/icons/login.png
  56. TEMPAT SAMPAH
      src/main/resources/images/icons/logo.png
  57. TEMPAT SAMPAH
      src/main/resources/images/icons/logoff.png
  58. TEMPAT SAMPAH
      src/main/resources/images/icons/menu_data_analysis.png
  59. TEMPAT SAMPAH
      src/main/resources/images/icons/menu_data_preprocess.png
  60. TEMPAT SAMPAH
      src/main/resources/images/icons/menu_file.png
  61. TEMPAT SAMPAH
      src/main/resources/images/icons/menu_setting.png
  62. TEMPAT SAMPAH
      src/main/resources/images/icons/min_bt.png
  63. TEMPAT SAMPAH
      src/main/resources/images/icons/ng_bg.png
  64. TEMPAT SAMPAH
      src/main/resources/images/icons/ok_bg.png
  65. TEMPAT SAMPAH
      src/main/resources/images/icons/open_file.png
  66. TEMPAT SAMPAH
      src/main/resources/images/icons/refresh.png
  67. TEMPAT SAMPAH
      src/main/resources/images/icons/reset_logo.png
  68. TEMPAT SAMPAH
      src/main/resources/images/icons/resistance_logo.png
  69. TEMPAT SAMPAH
      src/main/resources/images/icons/save_bg.png
  70. TEMPAT SAMPAH
      src/main/resources/images/icons/scan_barcode.png
  71. TEMPAT SAMPAH
      src/main/resources/images/icons/tree_folder_icon.png
  72. TEMPAT SAMPAH
      src/main/resources/images/icons/tree_leaf_icon.png
  73. TEMPAT SAMPAH
      src/main/resources/images/icons/user.png
  74. TEMPAT SAMPAH
      src/main/resources/images/icons/vertical_line.png
  75. TEMPAT SAMPAH
      src/main/resources/images/icons/zoom_in.png
  76. TEMPAT SAMPAH
      src/main/resources/images/icons/zoom_out.png
  77. TEMPAT SAMPAH
      src/main/resources/images/info_bt.png
  78. TEMPAT SAMPAH
      src/main/resources/images/min_bt.png
  79. 44 0
      src/main/resources/logback.xml

+ 22 - 0
.gitignore

@@ -0,0 +1,22 @@
+# IDE
+.idea
+*.iml
+.vscode
+
+# Eclipse(已弃用,禁止再提交)
+.classpath
+.project
+.settings
+bin
+classes
+
+# Maven / 构建
+target
+out
+
+# 运行时
+*.db
+.lock
+
+# 资源目录杂项(原 image/.gitignore)
+_system~.ini

TEMPAT SAMPAH
lib/iot-communication-1.4.4.jar


+ 5 - 0
pack/build-exe.bat

@@ -0,0 +1,5 @@
+@echo off
+chcp 65001 >nul
+cd /d "%~dp0\.."
+powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0..\..\tools\mesclient-pack\build-exe.ps1" -ProjectDir "%cd%" %*
+if errorlevel 1 pause

+ 6 - 0
pack/build-exe.ps1

@@ -0,0 +1,6 @@
+# 转发到仓库通用打包脚本(封面/Launch4j 共用)
+$here = $PSScriptRoot
+$proj = Split-Path -Parent $here
+$shared = Join-Path (Split-Path -Parent $proj) 'tools\mesclient-pack\build-exe.ps1'
+if (-not (Test-Path $shared)) { throw "找不到通用脚本: $shared" }
+& $shared -ProjectDir $proj @args

TEMPAT SAMPAH
pack/icon.ico


+ 64 - 0
pom.xml

@@ -0,0 +1,64 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <parent>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-parent</artifactId>
+        <version>2.7.18</version>
+        <relativePath/>
+    </parent>
+
+    <groupId>com.mes</groupId>
+    <artifactId>mesclient-dachong-yt</artifactId>
+    <version>1.0.0-SNAPSHOT</version>
+    <name>mesclient-dachong-yt</name>
+    <description>MES 一拖二大冲工控机(TE2-800 + TL4-1600)</description>
+    <packaging>jar</packaging>
+
+    <properties>
+        <java.version>1.8</java.version>
+        <maven.compiler.source>1.8</maven.compiler.source>
+        <maven.compiler.target>1.8</maven.compiler.target>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-api</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba.fastjson2</groupId>
+            <artifactId>fastjson2</artifactId>
+            <version>2.0.16</version>
+        </dependency>
+        <!-- S7 PLC:大冲 DcPlcClient -->
+        <dependency>
+            <groupId>com.github.xingshuangs</groupId>
+            <artifactId>iot-communication</artifactId>
+            <version>1.4.4</version>
+            <scope>system</scope>
+            <systemPath>${project.basedir}/lib/iot-communication-1.4.4.jar</systemPath>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+                <configuration>
+                    <mainClass>com.mes.MesClientApplication</mainClass>
+                    <includeSystemScope>true</includeSystemScope>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+</project>

+ 59 - 0
src/main/java/com/mes/MesClientApplication.java

@@ -0,0 +1,59 @@
+package com.mes;
+
+import java.util.concurrent.CountDownLatch;
+
+import org.springframework.boot.ApplicationArguments;
+import org.springframework.boot.ApplicationRunner;
+import org.springframework.boot.WebApplicationType;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.builder.SpringApplicationBuilder;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+import com.mes.config.MesClientProperties;
+import com.mes.ui.MainFrame;
+
+/**
+ * 一拖二大冲工控机启动入口(TE2-800 + TL4-1600,Swing 桌面)。
+ * 配置读 {@code config/application.yml} 的 {@code mes.*}。
+ */
+@SpringBootApplication
+@EnableConfigurationProperties(MesClientProperties.class)
+public class MesClientApplication {
+
+	public static void main(String[] args) {
+		// Swing 必须非 headless,否则无法弹窗
+		System.setProperty("java.awt.headless", "false");
+		new SpringApplicationBuilder(MesClientApplication.class)
+				.web(WebApplicationType.NONE)
+				.headless(false)
+				.run(args);
+	}
+
+	/**
+	 * 容器就绪后:先应用 yml 配置,再拉起 Swing;闩锁防止无 Web 进程提前退出。
+	 */
+	@Component
+	public static class SwingBootstrap implements ApplicationRunner {
+
+		private final MesClientProperties mesClientProperties;
+
+		public SwingBootstrap(MesClientProperties mesClientProperties) {
+			this.mesClientProperties = mesClientProperties;
+		}
+
+		@Override
+		public void run(ApplicationArguments args) throws Exception {
+			// 将 yml 中的 mes.* 写入 MainFrame 静态字段
+			MainFrame.applyConfig(mesClientProperties);
+			boolean started = MainFrame.launch();
+			if (!started) {
+				// 单实例冲突:不能再 await,否则进程无窗口挂死
+				System.exit(0);
+				return;
+			}
+			// 无 Web 时挡住主线程,避免 Spring 结束过早;窗口 System.exit 时进程结束
+			new CountDownLatch(1).await();
+		}
+	}
+}

+ 111 - 0
src/main/java/com/mes/config/DcPressProfiles.java

@@ -0,0 +1,111 @@
+package com.mes.config;
+
+/**
+ * 一拖二大冲点表:TE2-800 / TL4-1600。
+ * 「无」的点不读;MES 屏蔽不读。
+ * 两台都有 MES 允许,地址未定时 {@link #mesAllowAddr} 留空,开批/结案只本地盯冲次;有了填 yml {@code mes-allow-addr}。
+ */
+public enum DcPressProfiles {
+
+	/** TE2-800:IP 示例 192.168.0.1:102 */
+	TE2_800(
+			"TE2-800",
+			"DB395.6.0",
+			"DB3.100",
+			"DB3.168",
+			"DB91.2",
+			"DB900.360",
+			"DB63.6",
+			true),
+
+	/** TL4-1600:IP 示例 192.168.1.99:102 */
+	TL4_1600(
+			"TL4-1600",
+			"DB76.128.0",
+			"DB76.26",
+			"DB76.9",
+			"DB76.0",
+			"DB76.54",
+			"DB76.100",
+			false);
+
+	private final String title;
+	/** 设备运行 BOOL;空则不读 */
+	private final String deviceRunAddr;
+	/** 生产高度 REAL */
+	private final String dieHeightAddr;
+	/** 冲次数量 UDINT(本批进度按此累计差) */
+	private final String strokeCountAddr;
+	/** 顶缸压力 REAL */
+	private final String cylinderPressureAddr;
+	/** 生产吨位:TE2=DINT,TL4=REAL */
+	private final String tonnageAddr;
+	/** 压机行程次数 REAL(SPM) */
+	private final String pressSpmAddr;
+	/** 吨位是否按 DINT 读(否则 REAL) */
+	private final boolean tonnageDint;
+
+	DcPressProfiles(String title, String deviceRunAddr,
+			String dieHeightAddr, String strokeCountAddr, String cylinderPressureAddr,
+			String tonnageAddr, String pressSpmAddr, boolean tonnageDint) {
+		this.title = title;
+		this.deviceRunAddr = deviceRunAddr;
+		this.dieHeightAddr = dieHeightAddr;
+		this.strokeCountAddr = strokeCountAddr;
+		this.cylinderPressureAddr = cylinderPressureAddr;
+		this.tonnageAddr = tonnageAddr;
+		this.pressSpmAddr = pressSpmAddr;
+		this.tonnageDint = tonnageDint;
+	}
+
+	public String getTitle() {
+		return title;
+	}
+
+	public String getDeviceRunAddr() {
+		return deviceRunAddr;
+	}
+
+	public String getDieHeightAddr() {
+		return dieHeightAddr;
+	}
+
+	public String getStrokeCountAddr() {
+		return strokeCountAddr;
+	}
+
+	public String getCylinderPressureAddr() {
+		return cylinderPressureAddr;
+	}
+
+	public String getTonnageAddr() {
+		return tonnageAddr;
+	}
+
+	public String getPressSpmAddr() {
+		return pressSpmAddr;
+	}
+
+	public boolean isTonnageDint() {
+		return tonnageDint;
+	}
+
+	/** yml press-profile 解析;未知则 TE2_800 */
+	public static DcPressProfiles of(String raw) {
+		if (raw == null || raw.trim().isEmpty()) {
+			return TE2_800;
+		}
+		String s = raw.trim().toUpperCase().replace('-', '_').replace(' ', '_');
+		if (s.contains("TL4") || s.contains("1600")) {
+			return TL4_1600;
+		}
+		if (s.contains("TE2") || s.contains("800")) {
+			return TE2_800;
+		}
+		try {
+			return DcPressProfiles.valueOf(s);
+		} catch (Exception e) {
+			return TE2_800;
+		}
+	}
+}

+ 148 - 0
src/main/java/com/mes/config/MesClientProperties.java

@@ -0,0 +1,148 @@
+package com.mes.config;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * 一拖二大冲工控机配置,对应 application.yml 中 {@code mes.*}。
+ */
+@ConfigurationProperties(prefix = "mes")
+public class MesClientProperties {
+
+	/** 窗口标题 */
+	private String appTitle = "MES 一拖二大冲";
+	/** MES 服务器 IP */
+	private String serverIp = "";
+	/** 刷新周期毫秒 */
+	private int tickMs = 500;
+	/** 结案小票打印机名;空=系统默认 */
+	private String printerName = "";
+	/** 两台压机工位 */
+	private List<StationConfig> stations = new ArrayList<StationConfig>();
+
+	/**
+	 * 单台压机:取批次 →(可选)MES允许=true → 盯冲次差 → 结案允许=false → 打印。
+	 */
+	public static class StationConfig {
+		private int id = 1;
+		/** 工位编码(与 MES 工位主数据 / 队列一致) */
+		private String stationSn = "";
+		/** PLC IP */
+		private String plcIp = "";
+		/** S7 端口,默认 102 */
+		private int plcPort = 102;
+		/**
+		 * 机型点表:TE2_800 / TL4_1600。
+		 */
+		private String pressProfile = "TE2_800";
+		/**
+		 * MES 允许运行 BOOL(两台都有,地址未定时留空预留)。
+		 */
+		private String mesAllowAddr = "";
+		/** Tab / 顶栏显示名 */
+		private String title = "";
+
+		public int getId() {
+			return id;
+		}
+
+		public void setId(int id) {
+			this.id = id;
+		}
+
+		public String getStationSn() {
+			return stationSn;
+		}
+
+		public void setStationSn(String stationSn) {
+			this.stationSn = stationSn;
+		}
+
+		public String getPlcIp() {
+			return plcIp;
+		}
+
+		public void setPlcIp(String plcIp) {
+			this.plcIp = plcIp;
+		}
+
+		public int getPlcPort() {
+			return plcPort;
+		}
+
+		public void setPlcPort(int plcPort) {
+			this.plcPort = plcPort;
+		}
+
+		public String getPressProfile() {
+			return pressProfile;
+		}
+
+		public void setPressProfile(String pressProfile) {
+			this.pressProfile = pressProfile;
+		}
+
+		public String getMesAllowAddr() {
+			return mesAllowAddr;
+		}
+
+		public void setMesAllowAddr(String mesAllowAddr) {
+			this.mesAllowAddr = mesAllowAddr;
+		}
+
+		public String getTitle() {
+			return title;
+		}
+
+		public void setTitle(String title) {
+			this.title = title;
+		}
+
+		/** 解析机型枚举 */
+		public DcPressProfiles resolveProfile() {
+			return DcPressProfiles.of(pressProfile);
+		}
+	}
+
+	public String getAppTitle() {
+		return appTitle;
+	}
+
+	public void setAppTitle(String appTitle) {
+		this.appTitle = appTitle;
+	}
+
+	public String getServerIp() {
+		return serverIp;
+	}
+
+	public void setServerIp(String serverIp) {
+		this.serverIp = serverIp;
+	}
+
+	public int getTickMs() {
+		return tickMs;
+	}
+
+	public void setTickMs(int tickMs) {
+		this.tickMs = tickMs;
+	}
+
+	public String getPrinterName() {
+		return printerName;
+	}
+
+	public void setPrinterName(String printerName) {
+		this.printerName = printerName;
+	}
+
+	public List<StationConfig> getStations() {
+		return stations;
+	}
+
+	public void setStations(List<StationConfig> stations) {
+		this.stations = stations;
+	}
+}

+ 31 - 0
src/main/java/com/mes/entity/DcRunSnapshot.java

@@ -0,0 +1,31 @@
+package com.mes.entity;
+
+/**
+ * 一拖二大冲实时快照:生产高度/冲次/顶缸压力/吨位/行程次数 + 设备运行态。
+ * 示值保留设备原串,统计另议。
+ */
+public class DcRunSnapshot {
+
+	/** 生产高度(原串) */
+	public String dieHeight = "";
+	/** 冲次数量累计(本批进度用) */
+	public long strokeCount;
+	/** 冲次数量原串 */
+	public String strokeCountText = "";
+	/** 顶缸压力(原串) */
+	public String cylinderPressure = "";
+	/** 生产吨位(原串) */
+	public String tonnage = "";
+	/** 压机行程次数 / SPM(原串) */
+	public String pressSpm = "";
+	/** 设备是否运行 */
+	public boolean deviceRunning;
+	/** 设备状态文案 */
+	public String deviceStateText = "未知";
+
+	@Override
+	public String toString() {
+		return "stroke=" + strokeCount + ", die=" + dieHeight + ", press=" + cylinderPressure
+				+ ", ton=" + tonnage + ", spm=" + pressSpm + ", run=" + deviceRunning;
+	}
+}

+ 29 - 0
src/main/java/com/mes/entity/DcWorkRecord.java

@@ -0,0 +1,29 @@
+package com.mes.entity;
+
+/**
+ * 大冲本机工作记录一行:批次结案后写入,供工作记录页展示。
+ */
+public class DcWorkRecord {
+
+	/** 包装码(年月日+6位随机,批量追溯) */
+	public String packCode = "";
+	/** 批次码 */
+	public String batchCode = "";
+	/** 记录时间 yyyy-MM-dd HH:mm:ss */
+	public String recordTime = "";
+	/** 本批次生产数量 */
+	public int qty;
+	/** 过站结果:OK / NG */
+	public String result = "";
+
+	public DcWorkRecord() {
+	}
+
+	public DcWorkRecord(String packCode, String batchCode, String recordTime, int qty, String result) {
+		this.packCode = packCode == null ? "" : packCode.trim();
+		this.batchCode = batchCode == null ? "" : batchCode.trim();
+		this.recordTime = recordTime == null ? "" : recordTime.trim();
+		this.qty = qty;
+		this.result = result == null ? "" : result.trim();
+	}
+}

+ 113 - 0
src/main/java/com/mes/service/DcBatchPrinter.java

@@ -0,0 +1,113 @@
+package com.mes.service;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.print.PrintService;
+import javax.print.PrintServiceLookup;
+import java.awt.Font;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.print.PageFormat;
+import java.awt.print.Printable;
+import java.awt.print.PrinterException;
+import java.awt.print.PrinterJob;
+
+/**
+ * 批次结案小票:连接系统打印机,打印包装码、生产时间、本批数量。
+ * 打印机名由 yml {@code mes.printer-name} 指定;空则用系统默认打印机。
+ */
+public final class DcBatchPrinter {
+
+	private static final Logger log = LoggerFactory.getLogger(DcBatchPrinter.class);
+
+	/** 目标打印机名称(空=默认打印机) */
+	private static volatile String printerName = "";
+
+	private DcBatchPrinter() {
+	}
+
+	/** 启动时注入配置的打印机名 */
+	public static void setPrinterName(String name) {
+		printerName = name == null ? "" : name.trim();
+	}
+
+	/**
+	 * 连接打印机并送打包装码小票。
+	 *
+	 * @param packCode 包装码(年月日+6位随机)
+	 * @param produceTime 生产时间文案 yyyy-MM-dd HH:mm:ss
+	 * @param qty 本批实际增产数量
+	 * @return 是否送打印成功
+	 */
+	public static boolean printPack(final String packCode, final String produceTime, final int qty) {
+		final String code = packCode == null ? "" : packCode.trim();
+		final String time = produceTime == null ? "" : produceTime.trim();
+		try {
+			PrintService service = resolvePrinter();
+			if (service == null) {
+				log.warn("未找到可用打印机(printer-name={}),跳过打印 pack={}", printerName, code);
+				return false;
+			}
+			PrinterJob job = PrinterJob.getPrinterJob();
+			job.setPrintService(service);
+			job.setJobName("DC-PACK-" + code);
+			job.setPrintable(new Printable() {
+				@Override
+				public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) {
+					if (pageIndex > 0) {
+						return NO_SUCH_PAGE;
+					}
+					Graphics2D g = (Graphics2D) graphics;
+					g.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
+					g.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
+					int y = 24;
+					g.drawString("自动化大冲 · 包装小票", 10, y);
+					y += 28;
+					g.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
+					g.drawString("包装码:" + code, 10, y);
+					y += 22;
+					g.drawString("生产时间:" + time, 10, y);
+					y += 22;
+					g.drawString("生产数量:" + qty, 10, y);
+					return PAGE_EXISTS;
+				}
+			});
+			job.print();
+			log.info("已连接打印机[{}] 送打 pack={} qty={} time={}",
+					service.getName(), code, Integer.valueOf(qty), time);
+			return true;
+		} catch (PrinterException e) {
+			log.warn("连接/打印失败 pack={}: {}", code, e.getMessage());
+			return false;
+		} catch (Exception e) {
+			log.warn("打印异常 pack={}: {}", code, e.getMessage());
+			return false;
+		}
+	}
+
+	/**
+	 * 按配置名查找打印机;未配名则用系统默认;都没有则返回 null。
+	 */
+	private static PrintService resolvePrinter() {
+		if (!printerName.isEmpty()) {
+			PrintService[] all = PrintServiceLookup.lookupPrintServices(null, null);
+			if (all != null) {
+				for (int i = 0; i < all.length; i++) {
+					PrintService ps = all[i];
+					if (ps != null && printerName.equalsIgnoreCase(ps.getName())) {
+						return ps;
+					}
+				}
+			}
+			log.warn("配置的打印机名未找到: {},已枚举系统打印机数={}",
+					printerName, Integer.valueOf(all == null ? 0 : all.length));
+			return null;
+		}
+		PrintService def = PrintServiceLookup.lookupDefaultPrintService();
+		if (def == null) {
+			log.warn("系统无默认打印机");
+		}
+		return def;
+	}
+}

+ 24 - 0
src/main/java/com/mes/service/DcPackCode.java

@@ -0,0 +1,24 @@
+package com.mes.service;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.concurrent.ThreadLocalRandom;
+
+/**
+ * 包装码:一批次结案时生成,用于打印与服务端批量追溯。
+ * 规则:年月日(yyyyMMdd) + 随机 6 位数字。
+ */
+public final class DcPackCode {
+
+	private DcPackCode() {
+	}
+
+	/**
+	 * 生成包装码,如 20261106123456。
+	 */
+	public static String next() {
+		String day = new SimpleDateFormat("yyyyMMdd").format(new Date());
+		int rnd = ThreadLocalRandom.current().nextInt(0, 1000000);
+		return day + String.format("%06d", Integer.valueOf(rnd));
+	}
+}

+ 229 - 0
src/main/java/com/mes/service/DcPlcClient.java

@@ -0,0 +1,229 @@
+package com.mes.service;
+
+import com.github.xingshuangs.iot.protocol.s7.enums.EPlcType;
+import com.github.xingshuangs.iot.protocol.s7.service.S7PLC;
+import com.mes.config.DcPressProfiles;
+import com.mes.entity.DcRunSnapshot;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * 一拖二大冲 S7:按机型点表读过程参数;可选写 MES 允许。
+ * 断线指数退避:2s→4s→8s→16s→30s。
+ */
+public class DcPlcClient {
+
+	private static final Logger log = LoggerFactory.getLogger(DcPlcClient.class);
+
+	private static final long RETRY_INITIAL_MS = 2L * 1000L;
+	private static final long RETRY_MAX_MS = 30L * 1000L;
+
+	private final String stationSn;
+	private final String plcIp;
+	private final int plcPort;
+	private final DcPressProfiles profile;
+	/** MES 允许 BOOL;空则跳过写 PLC */
+	private final String mesAllowAddr;
+
+	private S7PLC plc;
+	private volatile boolean connected;
+	private volatile long nextRetryAtMs;
+	private volatile long currentRetryDelayMs = RETRY_INITIAL_MS;
+
+	public DcPlcClient(String stationSn, String plcIp, int plcPort,
+			DcPressProfiles profile, String mesAllowAddr) {
+		this.stationSn = stationSn == null ? "" : stationSn.trim();
+		this.plcIp = plcIp == null ? "" : plcIp.trim();
+		this.plcPort = plcPort <= 0 ? 102 : plcPort;
+		this.profile = profile == null ? DcPressProfiles.TE2_800 : profile;
+		// 两台都有 MES 允许;地址未提供前 yml 留空,开批/结案仍本地盯冲次
+		this.mesAllowAddr = mesAllowAddr == null ? "" : mesAllowAddr.trim();
+	}
+
+	public String getStationSn() {
+		return stationSn;
+	}
+
+	public String getPlcIp() {
+		return plcIp;
+	}
+
+	public int getPlcPort() {
+		return plcPort;
+	}
+
+	public DcPressProfiles getProfile() {
+		return profile;
+	}
+
+	public String getMesAllowAddr() {
+		return mesAllowAddr;
+	}
+
+	public boolean isConnected() {
+		return connected && plc != null;
+	}
+
+	/** tick:未连接按退避重连 */
+	public void maintainConnection() {
+		if (isConnected()) {
+			return;
+		}
+		connect();
+	}
+
+	/** 连接并用冲次数量探活 */
+	public synchronized void connect() {
+		if (isConnected()) {
+			return;
+		}
+		long now = System.currentTimeMillis();
+		if (now < nextRetryAtMs) {
+			return;
+		}
+		if (plcIp.isEmpty()) {
+			connected = false;
+			long waitSec = scheduleRetryAfterFailure() / 1000L;
+			log.warn("工位[{}] PLC IP 未配置,跳过连接({}s 后再试)", stationSn, Long.valueOf(waitSec));
+			return;
+		}
+		try {
+			plc = new S7PLC(EPlcType.S1200, plcIp, plcPort);
+			plc.readUInt32(profile.getStrokeCountAddr());
+			connected = true;
+			resetRetryBackoff();
+			log.info("工位[{}] {} PLC 已连接 {}:{} allow={}",
+					stationSn, profile.getTitle(), plcIp, Integer.valueOf(plcPort),
+					mesAllowAddr.isEmpty() ? "(预留未配)" : mesAllowAddr);
+		} catch (Exception e) {
+			connected = false;
+			plc = null;
+			long waitSec = scheduleRetryAfterFailure() / 1000L;
+			log.warn("工位[{}] PLC 连接失败 {}:{} — {}({}s 后再试)",
+					stationSn, plcIp, Integer.valueOf(plcPort), e.getMessage(), Long.valueOf(waitSec));
+		}
+	}
+
+	/**
+	 * 写 MES 允许运行。点未配置时返回 false(业务仍可本地走完)。
+	 */
+	public boolean setMesAllow(boolean allow) {
+		if (mesAllowAddr.isEmpty()) {
+			log.warn("工位[{}] mes-allow-addr 未配置(预留),跳过写 PLC allow={}",
+					stationSn, Boolean.valueOf(allow));
+			return false;
+		}
+		return writeBoolean(mesAllowAddr, allow);
+	}
+
+	/** 轮询读本机需采集的过程参数(不含「无」与 MES 屏蔽) */
+	public DcRunSnapshot readSnapshot() {
+		DcRunSnapshot s = new DcRunSnapshot();
+		if (!ensurePlc()) {
+			return s;
+		}
+		try {
+			s.dieHeight = fmtFloat(plc.readFloat32(profile.getDieHeightAddr()));
+			long stroke = plc.readUInt32(profile.getStrokeCountAddr());
+			s.strokeCount = stroke;
+			s.strokeCountText = String.valueOf(stroke);
+			s.cylinderPressure = fmtFloat(plc.readFloat32(profile.getCylinderPressureAddr()));
+			if (profile.isTonnageDint()) {
+				s.tonnage = String.valueOf(plc.readInt32(profile.getTonnageAddr()));
+			} else {
+				s.tonnage = fmtFloat(plc.readFloat32(profile.getTonnageAddr()));
+			}
+			s.pressSpm = fmtFloat(plc.readFloat32(profile.getPressSpmAddr()));
+			if (!isBlank(profile.getDeviceRunAddr())) {
+				s.deviceRunning = plc.readBoolean(profile.getDeviceRunAddr());
+				s.deviceStateText = s.deviceRunning ? "运行" : "停止";
+			}
+		} catch (Exception e) {
+			log.warn("工位[{}] 读过程参数失败: {}", stationSn, e.getMessage());
+			markDisconnectedAndResetBackoff();
+		}
+		return s;
+	}
+
+	/** 仅读冲次累计;失败返回 null */
+	public Long readStrokeCount() {
+		if (!ensurePlc()) {
+			return null;
+		}
+		try {
+			return Long.valueOf(plc.readUInt32(profile.getStrokeCountAddr()));
+		} catch (Exception e) {
+			markDisconnectedAndResetBackoff();
+			return null;
+		}
+	}
+
+	private boolean ensurePlc() {
+		if (isConnected()) {
+			return true;
+		}
+		connect();
+		return isConnected();
+	}
+
+	private boolean writeBoolean(String addr, boolean value) {
+		if (isBlank(addr) || !ensurePlc() || plc == null) {
+			return false;
+		}
+		try {
+			plc.writeBoolean(addr, value);
+			return true;
+		} catch (Exception e) {
+			log.warn("工位[{}] 写 {}={} 失败: {}", stationSn, addr, Boolean.valueOf(value), e.getMessage());
+			markDisconnectedAndResetBackoff();
+			return false;
+		}
+	}
+
+	private void markDisconnectedAndResetBackoff() {
+		connected = false;
+		currentRetryDelayMs = RETRY_INITIAL_MS;
+		nextRetryAtMs = System.currentTimeMillis() + currentRetryDelayMs;
+	}
+
+	private long scheduleRetryAfterFailure() {
+		connected = false;
+		long used = currentRetryDelayMs;
+		if (used < RETRY_INITIAL_MS) {
+			used = RETRY_INITIAL_MS;
+		}
+		if (used > RETRY_MAX_MS) {
+			used = RETRY_MAX_MS;
+		}
+		nextRetryAtMs = System.currentTimeMillis() + used;
+		long next = used * 2L;
+		currentRetryDelayMs = next > RETRY_MAX_MS ? RETRY_MAX_MS : next;
+		return used;
+	}
+
+	private void resetRetryBackoff() {
+		currentRetryDelayMs = RETRY_INITIAL_MS;
+		nextRetryAtMs = 0L;
+	}
+
+	private static boolean isBlank(String s) {
+		return s == null || s.trim().isEmpty();
+	}
+
+	/** REAL 示值原样转串,去掉无意义尾零 */
+	private static String fmtFloat(float v) {
+		if (Float.isNaN(v) || Float.isInfinite(v)) {
+			return "";
+		}
+		String s = String.valueOf(v);
+		if (s.indexOf('.') > 0) {
+			while (s.endsWith("0")) {
+				s = s.substring(0, s.length() - 1);
+			}
+			if (s.endsWith(".")) {
+				s = s.substring(0, s.length() - 1);
+			}
+		}
+		return s;
+	}
+}

+ 44 - 0
src/main/java/com/mes/service/DcWorkRecordStore.java

@@ -0,0 +1,44 @@
+package com.mes.service;
+
+import com.mes.entity.DcWorkRecord;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * 大冲本机工作记录内存库:结案写入,工作记录页读取。
+ * 服务端查询接口后续再接。
+ */
+public final class DcWorkRecordStore {
+
+	private static final List<DcWorkRecord> RECORDS =
+			Collections.synchronizedList(new ArrayList<DcWorkRecord>());
+
+	private DcWorkRecordStore() {
+	}
+
+	/**
+	 * 追加一条结案记录(插到最前,新记录在上)。
+	 *
+	 * @param packCode 包装码
+	 * @param batchCode 批次码
+	 * @param recordTime 记录时间
+	 * @param qty 本批产量
+	 * @param result 过站结果 OK/NG
+	 */
+	public static void add(String packCode, String batchCode, String recordTime, int qty, String result) {
+		RECORDS.add(0, new DcWorkRecord(packCode, batchCode, recordTime, qty, result));
+	}
+
+	/** 当前全部记录快照(新→旧) */
+	public static List<DcWorkRecord> list() {
+		synchronized (RECORDS) {
+			return new ArrayList<DcWorkRecord>(RECORDS);
+		}
+	}
+
+	public static int size() {
+		return RECORDS.size();
+	}
+}

+ 87 - 0
src/main/java/com/mes/service/MesApiClient.java

@@ -0,0 +1,87 @@
+package com.mes.service;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+/**
+ * 通用 form-urlencoded POST;大冲业务请求走 {@link MesDcApiClient}。
+ */
+public final class MesApiClient {
+
+	private static final Logger log = LoggerFactory.getLogger(MesApiClient.class);
+
+	private MesApiClient() {
+	}
+
+	/**
+	 * form-urlencoded POST;显式 UTF-8,避免打包 exe 后默认 GBK 导致中文乱码。
+	 */
+	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;charset=UTF-8");
+			os = connection.getOutputStream();
+			os.write(param.getBytes("UTF-8"));
+			if (connection.getResponseCode() == 200) {
+				is = connection.getInputStream();
+				br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
+				StringBuffer sbf = new StringBuffer();
+				String temp;
+				while ((temp = br.readLine()) != null) {
+					sbf.append(temp);
+					sbf.append("\r\n");
+				}
+				result = sbf.toString();
+			} else {
+				log.warn("HTTP {} => {}", httpUrl, connection.getResponseCode());
+			}
+		} catch (MalformedURLException e) {
+			log.error("URL 非法: {}", httpUrl, e);
+		} catch (IOException e) {
+			log.error("POST 失败: {}", httpUrl, e);
+		} finally {
+			if (br != null) {
+				try {
+					br.close();
+				} catch (IOException ignored) {
+				}
+			}
+			if (os != null) {
+				try {
+					os.close();
+				} catch (IOException ignored) {
+				}
+			}
+			if (is != null) {
+				try {
+					is.close();
+				} catch (IOException ignored) {
+				}
+			}
+			if (connection != null) {
+				connection.disconnect();
+			}
+		}
+		return result;
+	}
+}

+ 148 - 0
src/main/java/com/mes/service/MesDcApiClient.java

@@ -0,0 +1,148 @@
+package com.mes.service;
+
+import com.alibaba.fastjson2.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * 一拖二大冲工控机 HTTP:取批次 / 结案一次上传(包装码+过程参数)。
+ */
+public final class MesDcApiClient {
+
+	private static final Logger log = LoggerFactory.getLogger(MesDcApiClient.class);
+
+	private MesDcApiClient() {
+	}
+
+	/**
+	 * 取本工位待开批次(PDA 已扫码入通用队列)。
+	 * 路径:{@code /js/a/mes/mesFlexDcYt/nextBatch};期望 data:batchCode、targetQty。
+	 */
+	public static JSONObject nextBatch(String serverIp, String stationSn) {
+		Map<String, String> p = new LinkedHashMap<String, String>();
+		p.put("stationSn", nvl(stationSn));
+		return post(serverIp, "/js/a/mes/mesFlexDcYt/nextBatch", p);
+	}
+
+	/**
+	 * 批次结案一次上报:包装码 + 过程参数(落 mes_flex_dc_yt)。
+	 * 路径:{@code /js/a/mes/mesFlexDcYt/completeBatch}。
+	 */
+	public static JSONObject completeBatch(String serverIp, Map<String, String> fields) {
+		return post(serverIp, "/js/a/mes/mesFlexDcYt/completeBatch", fields);
+	}
+
+	/**
+	 * 探活服务端(不取码、不结案):短超时连 8980。
+	 * 须在独立线程调用,勿放进工位 tick,否则不通时会卡住指示灯刷新。
+	 */
+	public static boolean ping(String serverIp) {
+		String ip = nvl(serverIp);
+		if (ip.isEmpty()) {
+			return false;
+		}
+		java.net.HttpURLConnection conn = null;
+		try {
+			java.net.URL url = new java.net.URL("http://" + ip + ":8980/js/a/");
+			conn = (java.net.HttpURLConnection) url.openConnection();
+			conn.setRequestMethod("GET");
+			// 短超时:不通时尽快返回,避免顶栏灯半天才变
+			conn.setConnectTimeout(800);
+			conn.setReadTimeout(800);
+			conn.setInstanceFollowRedirects(false);
+			int code = conn.getResponseCode();
+			// 任意 HTTP 响应(含 302 登录墙)都说明服务在
+			return code > 0;
+		} catch (Exception e) {
+			log.debug("mes ping 失败: {}", e.getMessage());
+			return false;
+		} finally {
+			if (conn != null) {
+				conn.disconnect();
+			}
+		}
+	}
+
+	public static boolean isSuccess(JSONObject result) {
+		if (result == null) {
+			return false;
+		}
+		Object r = result.get("result");
+		return r != null && "true".equalsIgnoreCase(String.valueOf(r).trim());
+	}
+
+	public static String messageOf(JSONObject result) {
+		if (result == null) {
+			return "请求失败或无响应(服务端接口可能未上线)";
+		}
+		String m = result.getString("message");
+		return m == null || m.isEmpty() ? "失败" : m;
+	}
+
+	public static String dataStr(JSONObject result, String key) {
+		if (result == null || key == null) {
+			return "";
+		}
+		JSONObject data = result.getJSONObject("data");
+		if (data == null) {
+			return nvl(result.getString(key));
+		}
+		return nvl(data.getString(key));
+	}
+
+	public static int dataInt(JSONObject result, String key, int def) {
+		if (result == null || key == null) {
+			return def;
+		}
+		JSONObject data = result.getJSONObject("data");
+		Object raw = data != null ? data.get(key) : result.get(key);
+		if (raw == null) {
+			return def;
+		}
+		try {
+			return Integer.parseInt(String.valueOf(raw).trim());
+		} catch (Exception e) {
+			return def;
+		}
+	}
+
+	private static JSONObject post(String serverIp, String path, Map<String, String> fields) {
+		try {
+			String url = "http://" + nvl(serverIp) + ":8980" + path;
+			String body = toForm(fields);
+			log.debug("dc POST {} body={}", path, body);
+			String raw = MesApiClient.doPost(url, body);
+			if (raw == null || raw.isEmpty() || "false".equalsIgnoreCase(raw.trim())) {
+				return null;
+			}
+			return JSONObject.parseObject(raw);
+		} catch (Exception e) {
+			log.debug("dc 请求异常 path={} err={}", path, e.getMessage());
+			return null;
+		}
+	}
+
+	private static String toForm(Map<String, String> fields) throws UnsupportedEncodingException {
+		StringBuilder sb = new StringBuilder();
+		sb.append("__ajax=json");
+		if (fields != null) {
+			for (Map.Entry<String, String> e : fields.entrySet()) {
+				if (e.getKey() == null) {
+					continue;
+				}
+				sb.append('&').append(URLEncoder.encode(e.getKey(), "UTF-8"));
+				sb.append('=').append(URLEncoder.encode(nvl(e.getValue()), "UTF-8"));
+			}
+		}
+		return sb.toString();
+	}
+
+	private static String nvl(String s) {
+		return s == null ? "" : s.trim();
+	}
+}

+ 259 - 0
src/main/java/com/mes/service/MesFlexQueuePushClient.java

@@ -0,0 +1,259 @@
+package com.mes.service;
+
+import com.alibaba.fastjson2.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.io.UnsupportedEncodingException;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * 取码队列 SSE 订阅:入队 ENQUEUED / 清码 CLEARED。
+ * <p>
+ * 用 {@link HttpURLConnection} 读 text/event-stream(与 MesApiClient 一致,避免 OkHttp/Kotlin 在 IDE 爆红)。
+ * 断线指数退避重连(1s→30s);未连接时由 MainFrame 每 15s 慢轮询兜底。
+ * </p>
+ */
+public class MesFlexQueuePushClient {
+
+	private static final Logger log = LoggerFactory.getLogger(MesFlexQueuePushClient.class);
+
+	/** 队列门铃:入队 / 清码 */
+	public interface EnqueuedListener {
+		/** PDA 入队成功 */
+		void onEnqueued(String stationSn, String sn);
+
+		/** PDA/他端清码成功:本机若正占用该 sn 应复位 */
+		void onCleared(String stationSn, String sn);
+	}
+
+	private final String serverIp;
+	private final List<String> stationSns;
+	private final EnqueuedListener listener;
+	private final AtomicBoolean running = new AtomicBoolean(false);
+	private final AtomicBoolean connected = new AtomicBoolean(false);
+	private final AtomicLong backoffMs = new AtomicLong(1000L);
+
+	private volatile Thread worker;
+	/** 当前长连接,stop 时 disconnect 打断 readLine */
+	private volatile HttpURLConnection currentConn;
+
+	/**
+	 * @param serverIp   MES IP
+	 * @param stationSns 本机全部工位编码
+	 * @param listener   入队回调
+	 */
+	public MesFlexQueuePushClient(String serverIp, List<String> stationSns, EnqueuedListener listener) {
+		this.serverIp = serverIp == null ? "" : serverIp.trim();
+		this.stationSns = stationSns == null ? new ArrayList<String>() : new ArrayList<String>(stationSns);
+		this.listener = listener;
+	}
+
+	/** 是否已连上 SSE(连上后应关掉慢轮询兜底) */
+	public boolean isConnected() {
+		return connected.get();
+	}
+
+	/** 启动后台订阅线程(可重复调用,仅首次生效) */
+	public void start() {
+		if (!running.compareAndSet(false, true)) {
+			return;
+		}
+		worker = new Thread(new Runnable() {
+			@Override
+			public void run() {
+				loopUntilStopped();
+			}
+		}, "mes-flex-queue-sse");
+		worker.setDaemon(true);
+		worker.start();
+		log.info("SSE 推送客户端已启动,工位={}", stationSns);
+	}
+
+	/** 停止订阅并断开当前连接 */
+	public void stop() {
+		running.set(false);
+		connected.set(false);
+		HttpURLConnection c = currentConn;
+		if (c != null) {
+			try {
+				c.disconnect();
+			} catch (Exception ignore) {
+				// ignore
+			}
+		}
+		Thread t = worker;
+		if (t != null) {
+			try {
+				t.interrupt();
+			} catch (Exception ignore) {
+				// ignore
+			}
+		}
+		log.info("SSE 推送客户端已停止");
+	}
+
+	private void loopUntilStopped() {
+		while (running.get()) {
+			try {
+				openAndRead();
+			} catch (Exception e) {
+				log.warn("SSE 连接异常: {}", e.getMessage());
+			} finally {
+				connected.set(false);
+				currentConn = null;
+			}
+			if (!running.get()) {
+				break;
+			}
+			long wait = backoffMs.get();
+			log.info("SSE 将在 {}ms 后重连", wait);
+			sleepQuiet(wait);
+			// 指数退避 1s → 2s → … → 30s
+			long next = Math.min(30000L, wait * 2L);
+			backoffMs.set(next);
+		}
+	}
+
+	private void openAndRead() throws Exception {
+		if (serverIp.isEmpty() || stationSns.isEmpty()) {
+			log.warn("SSE 未配置 serverIp 或 stations,跳过");
+			sleepQuiet(5000L);
+			return;
+		}
+		String joined = joinCsv(stationSns);
+		String urlStr = "http://" + serverIp + ":8980/js/a/mes/mesFlexQueue/events?stationSn="
+				+ urlEncode(joined);
+		log.info("SSE 连接中 {}", urlStr);
+		HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
+		currentConn = conn;
+		conn.setRequestMethod("GET");
+		conn.setRequestProperty("Accept", "text/event-stream");
+		conn.setConnectTimeout(15000);
+		// 0 = 无限读超时,SSE 长连接
+		conn.setReadTimeout(0);
+		conn.setDoInput(true);
+		conn.connect();
+		int code = conn.getResponseCode();
+		if (code != HttpURLConnection.HTTP_OK) {
+			throw new IllegalStateException("HTTP " + code);
+		}
+		connected.set(true);
+		backoffMs.set(1000L);
+		log.info("SSE 已连接,订阅工位={}", joined);
+		BufferedReader reader = new BufferedReader(
+				new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8")));
+		try {
+			String eventName = "message";
+			StringBuilder dataBuf = new StringBuilder();
+			String line;
+			while (running.get() && (line = reader.readLine()) != null) {
+				if (line.isEmpty()) {
+					dispatchEvent(eventName, dataBuf.toString());
+					eventName = "message";
+					dataBuf.setLength(0);
+					continue;
+				}
+				if (line.startsWith(":")) {
+					continue;
+				}
+				if (line.startsWith("event:")) {
+					eventName = line.substring(6).trim();
+					continue;
+				}
+				if (line.startsWith("data:")) {
+					if (dataBuf.length() > 0) {
+						dataBuf.append('\n');
+					}
+					dataBuf.append(line.substring(5).trim());
+				}
+			}
+		} finally {
+			try {
+				reader.close();
+			} catch (Exception ignore) {
+				// ignore
+			}
+			try {
+				conn.disconnect();
+			} catch (Exception ignore) {
+				// ignore
+			}
+			connected.set(false);
+		}
+	}
+
+	private void dispatchEvent(String eventName, String data) {
+		if (data == null || data.isEmpty()) {
+			return;
+		}
+		if ("ping".equalsIgnoreCase(eventName)) {
+			log.debug("SSE ping");
+			return;
+		}
+		if ("ready".equalsIgnoreCase(eventName)) {
+			log.info("SSE ready {}", data);
+			return;
+		}
+		try {
+			JSONObject json = JSONObject.parseObject(data);
+			if (json == null) {
+				return;
+			}
+			String type = json.getString("type");
+			String stationSn = json.getString("stationSn");
+			String sn = json.getString("sn");
+			if ("ENQUEUED".equalsIgnoreCase(type)) {
+				log.info("SSE 收到入队 stationSn={} sn={}", stationSn, sn);
+				if (listener != null) {
+					listener.onEnqueued(stationSn, sn);
+				}
+				return;
+			}
+			if ("CLEARED".equalsIgnoreCase(type)) {
+				log.info("SSE 收到清码 stationSn={} sn={}", stationSn, sn);
+				if (listener != null) {
+					listener.onCleared(stationSn, sn);
+				}
+			}
+		} catch (Exception e) {
+			log.warn("SSE 事件解析失败 data={} err={}", data, e.getMessage());
+		}
+	}
+
+	private static String joinCsv(List<String> list) {
+		StringBuilder sb = new StringBuilder();
+		for (int i = 0; i < list.size(); i++) {
+			String s = list.get(i);
+			if (s == null || s.trim().isEmpty()) {
+				continue;
+			}
+			if (sb.length() > 0) {
+				sb.append(',');
+			}
+			sb.append(s.trim());
+		}
+		return sb.toString();
+	}
+
+	private static String urlEncode(String s) throws UnsupportedEncodingException {
+		return URLEncoder.encode(s == null ? "" : s, "UTF-8");
+	}
+
+	private static void sleepQuiet(long ms) {
+		try {
+			Thread.sleep(ms);
+		} catch (InterruptedException e) {
+			Thread.currentThread().interrupt();
+		}
+	}
+}

+ 101 - 0
src/main/java/com/mes/ui/BreathingLight.java

@@ -0,0 +1,101 @@
+package com.mes.ui;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+/**
+ * 服务端心跳指示灯:在线时灰/绿约 1.5s 交替闪烁;断开时红色常亮、停止闪烁。
+ * 与弧焊客户端同款。
+ */
+public class BreathingLight extends JComponent {
+
+	private static final long serialVersionUID = 1L;
+
+	/** 灰 ↔ 绿 切换间隔(毫秒) */
+	private static final int BLINK_MS = 1500;
+
+	private static final Color GREEN = new Color(40, 220, 100);
+	private static final Color GRAY = new Color(120, 130, 140);
+	private static final Color RED = new Color(230, 60, 50);
+	private static final Color RED_RING = new Color(140, 40, 35);
+
+	private final javax.swing.Timer blinkTimer;
+	private volatile boolean online;
+	/** true=当前亮绿,false=当前亮灰 */
+	private boolean showGreen = true;
+
+	public BreathingLight() {
+		setPreferredSize(new Dimension(28, 28));
+		setMinimumSize(new Dimension(24, 24));
+		setOpaque(false);
+		setToolTipText("服务端心跳:绿/灰闪=已连接,红=断开");
+		blinkTimer = new javax.swing.Timer(BLINK_MS, new ActionListener() {
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				if (!online) {
+					return;
+				}
+				showGreen = !showGreen;
+				repaint();
+			}
+		});
+		blinkTimer.setRepeats(true);
+	}
+
+	/**
+	 * 更新在线状态:true 灰绿交替闪;false 红停。
+	 */
+	public void setOnline(boolean online) {
+		boolean was = this.online;
+		this.online = online;
+		if (online) {
+			if (!was) {
+				showGreen = true;
+			}
+			if (!blinkTimer.isRunning()) {
+				blinkTimer.start();
+			}
+		} else {
+			blinkTimer.stop();
+			showGreen = false;
+		}
+		repaint();
+	}
+
+	public boolean isOnline() {
+		return online;
+	}
+
+	/** 面板销毁时停表,避免泄漏 */
+	public void dispose() {
+		blinkTimer.stop();
+	}
+
+	@Override
+	protected void paintComponent(Graphics g) {
+		super.paintComponent(g);
+		Graphics2D g2 = (Graphics2D) g.create();
+		try {
+			g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+			int w = getWidth();
+			int h = getHeight();
+			int r = Math.min(w, h) / 2 - 2;
+			int cx = w / 2;
+			int cy = h / 2;
+
+			if (online) {
+				g2.setColor(showGreen ? GREEN : GRAY);
+				g2.fillOval(cx - r, cy - r, r * 2, r * 2);
+			} else {
+				g2.setColor(RED_RING);
+				g2.fillOval(cx - r - 1, cy - r - 1, (r + 1) * 2, (r + 1) * 2);
+				g2.setColor(RED);
+				g2.fillOval(cx - r, cy - r, r * 2, r * 2);
+			}
+		} finally {
+			g2.dispose();
+		}
+	}
+}

+ 459 - 0
src/main/java/com/mes/ui/MainFrame.java

@@ -0,0 +1,459 @@
+package com.mes.ui;
+
+import com.mes.config.MesClientProperties;
+import com.mes.service.DcBatchPrinter;
+import com.mes.service.MesFlexQueuePushClient;
+import com.mes.util.SingleInstanceLock;
+import com.mes.util.UiImages;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.swing.*;
+import javax.swing.border.EmptyBorder;
+import java.awt.*;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * 一拖二大冲主窗:两台压机各自独立周期 / 结案;取批次订 SSE 门铃 + 断线慢轮询兜底。
+ */
+public class MainFrame extends JFrame {
+
+	public static final Logger log = LoggerFactory.getLogger(MainFrame.class);
+
+	public static MainFrame mesClientFrame;
+
+	public static String mes_server_ip = "";
+	public static String mes_app_title = "MES 一拖二大冲";
+
+	private static MesClientProperties props;
+	private static final List<StationPanel> stationPanels = new ArrayList<StationPanel>();
+	private static WorkRecordPanel workRecordPanel;
+	/** 取码队列 SSE(入队门铃 / 清码) */
+	private static MesFlexQueuePushClient pushClient;
+	/** SSE 断线时 IDLE 慢轮询 nextBatch */
+	private static Timer fallbackNextTimer;
+	private static final AtomicBoolean exiting = new AtomicBoolean(false);
+	private static JLabel menuStatus;
+	/** 当前选中的压机页下标(手动提交用) */
+	private static final AtomicInteger activeStationIdx = new AtomicInteger(0);
+
+	public static boolean launch() {
+		if (SingleInstanceLock.getInstance().isAppActive()) {
+			log.warn("已有客户端实例在运行,本次启动取消");
+			return false;
+		}
+		EventQueue.invokeLater(new Runnable() {
+			@Override
+			public void run() {
+				try {
+					UiTheme.applyLookAndFeel();
+					mesClientFrame = new MainFrame();
+					mesClientFrame.setVisible(true);
+					new Thread(new Runnable() {
+						@Override
+						public void run() {
+							// 不等待两台都连上:一台 PLC 挂死不能拖住另一台开跑
+							startStationLoops();
+							startPush();
+							for (final StationPanel p : stationPanels) {
+								new Thread(new Runnable() {
+									@Override
+									public void run() {
+										try {
+											p.initPlc();
+										} catch (Exception ex) {
+											log.warn("PLC 初始化异常 sn={}: {}",
+													p.getStationSn(), ex.getMessage());
+										}
+									}
+								}, "dc-yt-plc-init-" + p.getStationSn()).start();
+							}
+						}
+					}, "dc-yt-boot").start();
+				} catch (Exception e) {
+					log.error("启动主界面失败", e);
+				}
+			}
+		});
+		return true;
+	}
+
+	public static void applyConfig(MesClientProperties p) {
+		if (p == null) {
+			throw new IllegalStateException("MesClientProperties 为空,请检查 application.yml 中 mes 配置");
+		}
+		props = p;
+		mes_server_ip = trim(p.getServerIp());
+		mes_app_title = trim(p.getAppTitle());
+		if (mes_app_title.isEmpty()) {
+			mes_app_title = "MES 一拖二大冲";
+		}
+		DcBatchPrinter.setPrinterName(p.getPrinterName());
+		log.info("打印机配置 name={}", trim(p.getPrinterName()).isEmpty() ? "(系统默认)" : trim(p.getPrinterName()));
+		List<MesClientProperties.StationConfig> list = p.getStations();
+		if (list == null || list.isEmpty()) {
+			log.warn("mes.stations 为空");
+		} else {
+			log.info("加载压机数={}", list.size());
+			for (MesClientProperties.StationConfig s : list) {
+				log.info("压机 sn={} title={} profile={} plc={}:{} allow={}",
+						s.getStationSn(), s.getTitle(), s.getPressProfile(),
+						s.getPlcIp(), Integer.valueOf(s.getPlcPort()), s.getMesAllowAddr());
+			}
+		}
+	}
+
+	/**
+	 * 兼容旧调用:SSE 已连时忽略;未连时不在此强行改灯(以 SSE 为准)。
+	 */
+	public static void setMesServerOnline(boolean online) {
+		// 在线态以 pushClient SSE 为准,保留空方法避免各处编译改动过大
+	}
+
+	/** 服务端是否在线:以取码队列 SSE 长连接为准 */
+	public static boolean isMesServerOnline() {
+		return pushClient != null && pushClient.isConnected();
+	}
+
+	public static void setMenuStatus(final String text, final int level) {
+		SwingUtilities.invokeLater(new Runnable() {
+			@Override
+			public void run() {
+				if (menuStatus == null) {
+					return;
+				}
+				menuStatus.setText(text == null ? "" : text);
+				if (level < 0) {
+					menuStatus.setForeground(new Color(220, 80, 80));
+				} else {
+					menuStatus.setForeground(new Color(180, 220, 230));
+				}
+			}
+		});
+	}
+
+	public MainFrame() {
+		setIconImage(Toolkit.getDefaultToolkit().getImage(UiImages.icon("logo.png")));
+		setTitle(mes_app_title);
+		setBounds(40, 40, 1280, 720);
+		setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
+		addWindowListener(new WindowAdapter() {
+			@Override
+			public void windowClosing(WindowEvent e) {
+				if (exiting.get()) {
+					return;
+				}
+				int choice = JOptionPane.showConfirmDialog(MainFrame.this, "确定退出?", "关闭确认",
+						JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
+				if (choice != JOptionPane.YES_OPTION) {
+					return;
+				}
+				if (!exiting.compareAndSet(false, true)) {
+					return;
+				}
+				setVisible(false);
+				dispose();
+				new Thread(new Runnable() {
+					@Override
+					public void run() {
+						try {
+							stopPush();
+							stopStationLoops();
+						} catch (Throwable t) {
+							log.warn("退出清理异常: {}", t.getMessage());
+						} finally {
+							System.exit(0);
+						}
+					}
+				}, "mes-client-exit").start();
+			}
+		});
+
+		menuStatus = new JLabel("就绪");
+		menuStatus.setVisible(false);
+
+		JPanel content = new JPanel(new BorderLayout(0, 0));
+		content.setBorder(new EmptyBorder(0, 0, 0, 0));
+		content.setBackground(UiTheme.BG);
+		setContentPane(content);
+
+		stationPanels.clear();
+		List<MesClientProperties.StationConfig> stations =
+				props == null ? null : props.getStations();
+		if (stations == null || stations.isEmpty()) {
+			JLabel empty = new JLabel("请在 application.yml 配置 mes.stations(TE2-800 + TL4-1600)",
+					SwingConstants.CENTER);
+			empty.setFont(new Font("微软雅黑", Font.PLAIN, 18));
+			content.add(empty, BorderLayout.CENTER);
+			return;
+		}
+
+		final JPanel cards = new JPanel(new CardLayout());
+		cards.setOpaque(false);
+		final List<JButton> stationNavBtns = new ArrayList<JButton>();
+		final JButton btnRecord = navBtn("工作记录", false);
+
+		for (int i = 0; i < stations.size(); i++) {
+			MesClientProperties.StationConfig sc = stations.get(i);
+			StationPanel panel = new StationPanel(sc, mes_server_ip);
+			stationPanels.add(panel);
+			String cardKey = "station-" + i;
+			cards.add(panel, cardKey);
+			final int idx = i;
+			final JButton btn = navBtn(panel.tabTitle(), i == 0);
+			stationNavBtns.add(btn);
+			btn.addActionListener(new ActionListener() {
+				@Override
+				public void actionPerformed(ActionEvent e) {
+					activeStationIdx.set(idx);
+					((CardLayout) cards.getLayout()).show(cards, "station-" + idx);
+					for (int j = 0; j < stationNavBtns.size(); j++) {
+						styleNavSelected(stationNavBtns.get(j), j == idx);
+					}
+					styleNavSelected(btnRecord, false);
+				}
+			});
+		}
+		workRecordPanel = new WorkRecordPanel();
+		cards.add(workRecordPanel, "record");
+
+		final JButton btnSettings = navBtn("设置", false);
+		final JPopupMenu settingsMenu = new JPopupMenu();
+		JMenuItem miNext = new JMenuItem("手动取批次(当前压机)");
+		miNext.setFont(new Font("微软雅黑", Font.PLAIN, 14));
+		miNext.addActionListener(new ActionListener() {
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				int idx = activeStationIdx.get();
+				if (idx >= 0 && idx < stationPanels.size()) {
+					stationPanels.get(idx).onManualNextClick();
+				}
+			}
+		});
+		JMenuItem miManual = new JMenuItem("手动提交(当前压机)");
+		miManual.setFont(new Font("微软雅黑", Font.PLAIN, 14));
+		miManual.addActionListener(new ActionListener() {
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				int idx = activeStationIdx.get();
+				if (idx >= 0 && idx < stationPanels.size()) {
+					stationPanels.get(idx).onManualSubmitClick();
+				}
+			}
+		});
+		settingsMenu.add(miNext);
+		settingsMenu.add(miManual);
+		btnSettings.addActionListener(new ActionListener() {
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				settingsMenu.show(btnSettings, 0, btnSettings.getHeight());
+			}
+		});
+		btnRecord.addActionListener(new ActionListener() {
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				((CardLayout) cards.getLayout()).show(cards, "record");
+				for (int j = 0; j < stationNavBtns.size(); j++) {
+					styleNavSelected(stationNavBtns.get(j), false);
+				}
+				styleNavSelected(btnRecord, true);
+			}
+		});
+
+		JPanel nav = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
+		nav.setOpaque(true);
+		nav.setBackground(UiTheme.BG);
+		nav.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, UiTheme.LINE));
+		nav.add(btnSettings);
+		for (JButton b : stationNavBtns) {
+			nav.add(b);
+		}
+		nav.add(btnRecord);
+
+		JPanel page = new JPanel(new BorderLayout(0, 0));
+		page.setOpaque(false);
+		page.setBorder(new EmptyBorder(10, 12, 12, 12));
+		page.add(nav, BorderLayout.NORTH);
+		page.add(cards, BorderLayout.CENTER);
+		content.add(page, BorderLayout.CENTER);
+	}
+
+	private static JButton navBtn(String text, boolean selected) {
+		JButton b = new JButton(text);
+		b.setFont(new Font("微软雅黑", Font.PLAIN, 14));
+		b.setFocusPainted(false);
+		b.setMargin(new Insets(8, 18, 8, 18));
+		b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
+		b.setOpaque(true);
+		styleNavSelected(b, selected);
+		return b;
+	}
+
+	private static void styleNavSelected(JButton b, boolean selected) {
+		if (selected) {
+			b.setBackground(Color.WHITE);
+			b.setForeground(UiTheme.ACCENT);
+			b.setBorder(BorderFactory.createCompoundBorder(
+					BorderFactory.createMatteBorder(0, 0, 2, 0, UiTheme.ACCENT),
+					new EmptyBorder(8, 18, 6, 18)));
+		} else {
+			b.setBackground(UiTheme.BG);
+			b.setForeground(UiTheme.TEXT);
+			b.setBorder(BorderFactory.createCompoundBorder(
+					BorderFactory.createMatteBorder(0, 0, 2, 0, UiTheme.BG),
+					new EmptyBorder(8, 18, 6, 18)));
+		}
+	}
+
+	public static void refreshWorkRecords() {
+		SwingUtilities.invokeLater(new Runnable() {
+			@Override
+			public void run() {
+				if (workRecordPanel != null) {
+					workRecordPanel.reload();
+				}
+			}
+		});
+	}
+
+	/** 每台压机各自 startStationLoop,共享 Timer/线程池一律不用 */
+	private static void startStationLoops() {
+		int period = 500;
+		if (props != null && props.getTickMs() > 0) {
+			period = props.getTickMs();
+		}
+		for (StationPanel p : stationPanels) {
+			try {
+				p.startStationLoop(period);
+			} catch (Exception ex) {
+				log.warn("启动工位周期失败 sn={}: {}", p.getStationSn(), ex.getMessage());
+			}
+		}
+	}
+
+	private static void stopStationLoops() {
+		for (StationPanel p : stationPanels) {
+			try {
+				p.stopStationLoop();
+			} catch (Exception ex) {
+				log.warn("停止工位周期失败 sn={}: {}", p.getStationSn(), ex.getMessage());
+			}
+		}
+	}
+
+	/**
+	 * 启动 SSE 入队订阅 + 断线 15s 慢轮询兜底。
+	 * 推送只当门铃:真正取批仍走 StationPanel.requestNextAsync → nextBatch。
+	 */
+	private static void startPush() {
+		stopPush();
+		if (stationPanels.isEmpty()) {
+			return;
+		}
+		List<String> sns = new ArrayList<String>();
+		for (StationPanel p : stationPanels) {
+			String sn = p.getStationSn();
+			if (sn != null && !sn.isEmpty() && !sns.contains(sn)) {
+				sns.add(sn);
+			}
+		}
+		pushClient = new MesFlexQueuePushClient(mes_server_ip, sns, new MesFlexQueuePushClient.EnqueuedListener() {
+			@Override
+			public void onEnqueued(String stationSn, String sn) {
+				final StationPanel panel = findPanel(stationSn);
+				if (panel == null) {
+					log.warn("SSE 入队工位[{}] 本机无对应页", stationSn);
+					return;
+				}
+				final String st = stationSn;
+				new Thread(new Runnable() {
+					@Override
+					public void run() {
+						panel.tryAutoNextFromPush(st);
+					}
+				}, "dc-yt-push-enq-" + st).start();
+			}
+
+			@Override
+			public void onCleared(String stationSn, String sn) {
+				final StationPanel panel = findPanel(stationSn);
+				if (panel == null) {
+					return;
+				}
+				final String cleared = sn;
+				new Thread(new Runnable() {
+					@Override
+					public void run() {
+						panel.applyClearedFromPush(cleared);
+					}
+				}, "dc-yt-push-clr-" + stationSn).start();
+			}
+		});
+		pushClient.start();
+		// 首拉:启动前 PDA 已入队时没有 ENQUEUED 事件,连上后补一次
+		new Timer("dc-yt-first-next", true).schedule(new TimerTask() {
+			@Override
+			public void run() {
+				for (StationPanel p : stationPanels) {
+					try {
+						p.tryAutoNextFromPush();
+					} catch (Exception ex) {
+						log.debug("first next skip: {}", ex.getMessage());
+					}
+				}
+			}
+		}, 1500L);
+		// 安全网:不论 SSE 是否在线,15s 慢轮询一次(兜住漏推送 / 开批失败后队列已取)
+		fallbackNextTimer = new Timer("dc-yt-fallback-next", true);
+		fallbackNextTimer.scheduleAtFixedRate(new TimerTask() {
+			@Override
+			public void run() {
+				for (StationPanel p : stationPanels) {
+					try {
+						p.tryAutoNextFromPush();
+					} catch (Exception ex) {
+						log.debug("fallback next skip: {}", ex.getMessage());
+					}
+				}
+			}
+		}, 15000L, 15000L);
+		log.info("已启动取码推送订阅 + 首拉 + 15s 安全轮询");
+	}
+
+	private static void stopPush() {
+		if (fallbackNextTimer != null) {
+			fallbackNextTimer.cancel();
+			fallbackNextTimer = null;
+		}
+		if (pushClient != null) {
+			pushClient.stop();
+			pushClient = null;
+		}
+	}
+
+	private static StationPanel findPanel(String stationSn) {
+		if (stationSn == null || stationSn.trim().isEmpty()) {
+			return null;
+		}
+		String key = stationSn.trim();
+		for (StationPanel p : stationPanels) {
+			if (key.equalsIgnoreCase(p.getStationSn())) {
+				return p;
+			}
+		}
+		return null;
+	}
+
+	private static String trim(String s) {
+		return s == null ? "" : s.trim();
+	}
+}

+ 903 - 0
src/main/java/com/mes/ui/StationPanel.java

@@ -0,0 +1,903 @@
+package com.mes.ui;
+
+import com.alibaba.fastjson2.JSONObject;
+import com.mes.config.DcPressProfiles;
+import com.mes.config.MesClientProperties;
+import com.mes.entity.DcRunSnapshot;
+import com.mes.service.DcBatchPrinter;
+import com.mes.service.DcPackCode;
+import com.mes.service.DcPlcClient;
+import com.mes.service.DcWorkRecordStore;
+import com.mes.service.MesDcApiClient;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.swing.*;
+import javax.swing.border.EmptyBorder;
+import java.awt.*;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * 一拖二单机面板:轮询取批次 → MES允许(可预留) → 盯冲次差 → 结案关允许 → 打印。
+ * 每台压机独立调度线程,一台 PLC/HTTP 卡死不影响另一台。
+ */
+public class StationPanel extends JPanel {
+
+	private static final Logger log = LoggerFactory.getLogger(StationPanel.class);
+
+	/** 兜底轮询最小间隔(SSE 正常时不走 tick 取批) */
+	private static final long POLL_BATCH_INTERVAL_MS = 2000L;
+
+	public enum Phase {
+		IDLE, RUN, DONE
+	}
+
+	private final MesClientProperties.StationConfig cfg;
+	private final DcPressProfiles profile;
+	private final String serverIp;
+	private final DcPlcClient plc;
+	private final AtomicBoolean busy = new AtomicBoolean(false);
+	/** 后台取码进行中,与开批/结案 busy 分开,避免互踩 */
+	private final AtomicBoolean nextBusy = new AtomicBoolean(false);
+	/** 本工位 tick 进行中:PLC 连不上时丢弃重叠调度 */
+	private final AtomicBoolean tickInFlight = new AtomicBoolean(false);
+	/** 本工位专属周期线程(与另一台完全隔离) */
+	private ScheduledExecutorService stationScheduler;
+
+	private volatile Phase phase = Phase.IDLE;
+	private volatile String batchCode = "";
+	private volatile int targetQty;
+	/** 开批时冲次起点;中途复位后按已产重定 */
+	private volatile long baseStrokeCount;
+	private volatile int producedQty;
+	private volatile long lastStrokeCount;
+	private volatile String batchStartTime = "";
+	private volatile long lastPollBatchAtMs;
+	private volatile DcRunSnapshot lastSnap = new DcRunSnapshot();
+	/** 本批是否已成功写下 MES 允许(灯只跟这个,不跟 phase 瞎亮) */
+	private volatile boolean mesAllowOn;
+	/** 结案上传未成功时的待重试报文(DONE 态由 tick 续传,避免卡死) */
+	private volatile Map<String, String> pendingCompleteFields;
+	private volatile String pendingHow = "";
+	private volatile String pendingPackCode = "";
+	private volatile int pendingQty;
+	private volatile boolean pendingPrinted;
+	private final AtomicBoolean completeRetryBusy = new AtomicBoolean(false);
+
+	private final JLabel lblStation;
+	private final JLabel lblStatus;
+	private final JTextField txtBatch;
+	private final JTextField txtTarget;
+	private final JTextField txtDieHeight;
+	private final JTextField txtStrokeCount;
+	private final JTextField txtProduced;
+	private final JTextField txtCylinderPressure;
+	private final JTextField txtTonnage;
+	private final JTextField txtPressSpm;
+	/** 服务端心跳:绿/灰闪=已连,红=断开(与弧焊同款) */
+	private final BreathingLight serverHeartbeat;
+	private final StatusLight lampPlc;
+	private final JLabel lblPlcState;
+	private final StatusLight lampMesAllow;
+	private final JLabel lblMesAllowState;
+	/** 漏推送时现场可点:强制 nextBatch */
+	private final JButton btnNext;
+
+	public StationPanel(MesClientProperties.StationConfig cfg, String serverIp) {
+		this.cfg = cfg;
+		this.profile = cfg.resolveProfile();
+		this.serverIp = serverIp == null ? "" : serverIp.trim();
+		this.plc = new DcPlcClient(cfg.getStationSn(), cfg.getPlcIp(), cfg.getPlcPort(),
+				this.profile, cfg.getMesAllowAddr());
+
+		setLayout(new BorderLayout(0, 0));
+		setBackground(UiTheme.BG);
+		setBorder(new EmptyBorder(0, 0, 0, 0));
+
+		String titleText = nvl(cfg.getTitle());
+		if (titleText.isEmpty()) {
+			titleText = profile.getTitle();
+		}
+
+		JPanel header = UiTheme.gradientHeader();
+		header.setBorder(new EmptyBorder(16, 20, 16, 20));
+		lblStation = new JLabel(titleText);
+		lblStation.setFont(UiTheme.FONT_TITLE);
+		lblStation.setForeground(Color.WHITE);
+		JLabel lblCode = new JLabel(nvl(cfg.getStationSn()) + "  ·  " + profile.name());
+		lblCode.setFont(new Font("Consolas", Font.BOLD, 13));
+		lblCode.setForeground(new Color(140, 210, 220));
+		JPanel titleCol = new JPanel();
+		titleCol.setOpaque(false);
+		titleCol.setLayout(new BoxLayout(titleCol, BoxLayout.Y_AXIS));
+		titleCol.add(lblStation);
+		titleCol.add(Box.createVerticalStrut(3));
+		titleCol.add(lblCode);
+
+		serverHeartbeat = new BreathingLight();
+		serverHeartbeat.setOnline(false);
+		lampPlc = new StatusLight();
+		lblPlcState = headerStateLabel("未连接");
+		lampMesAllow = new StatusLight();
+		lblMesAllowState = headerStateLabel("关");
+
+		JPanel east = new JPanel(new FlowLayout(FlowLayout.RIGHT, 14, 0));
+		east.setOpaque(false);
+		// 每台压机一套:MES 服务端呼吸灯 + PLC + MES允许
+		east.add(headerBreathingItem("MES", serverHeartbeat));
+		east.add(headerLampItem("PLC", lampPlc, lblPlcState));
+		east.add(headerLampItem("MES允许", lampMesAllow, lblMesAllowState));
+		header.add(titleCol, BorderLayout.WEST);
+		header.add(east, BorderLayout.EAST);
+
+		lblStatus = new JLabel("空闲:等待扫码下发批次…");
+		lblStatus.setFont(UiTheme.FONT_BODY);
+		lblStatus.setOpaque(true);
+		lblStatus.setBackground(UiTheme.OK_BG);
+		lblStatus.setForeground(UiTheme.OK_FG);
+		lblStatus.setBorder(new EmptyBorder(9, 16, 9, 16));
+
+		JPanel north = new JPanel(new BorderLayout(0, 0));
+		north.setOpaque(false);
+		north.add(header, BorderLayout.NORTH);
+		north.add(lblStatus, BorderLayout.SOUTH);
+		add(north, BorderLayout.NORTH);
+
+		JPanel main = new JPanel(new BorderLayout(0, 14));
+		main.setOpaque(false);
+		main.setBorder(new EmptyBorder(16, 20, 16, 20));
+
+		JPanel batchCard = UiTheme.card();
+		batchCard.setLayout(new BorderLayout(0, 10));
+		batchCard.add(UiTheme.sectionTitle("本批"), BorderLayout.NORTH);
+		JPanel batchGrid = new JPanel(new GridLayout(1, 2, 14, 0));
+		batchGrid.setOpaque(false);
+		batchGrid.setPreferredSize(new Dimension(10, UiTheme.TILE_PREF_H));
+		txtBatch = roField();
+		txtTarget = roField();
+		batchGrid.add(UiTheme.paramTile("批次码", txtBatch, UiTheme.STRIPE_SIDE));
+		batchGrid.add(UiTheme.paramTile("本批目标数量", txtTarget, UiTheme.STRIPE_SIDE));
+		batchCard.add(batchGrid, BorderLayout.CENTER);
+
+		JPanel runCard = UiTheme.card();
+		runCard.setLayout(new BorderLayout(0, 10));
+		runCard.add(UiTheme.sectionTitle("过程参数"), BorderLayout.NORTH);
+		JPanel grid = new JPanel(new GridLayout(2, 3, 14, 14));
+		grid.setOpaque(false);
+		txtDieHeight = roField();
+		txtStrokeCount = roField();
+		txtProduced = roField();
+		txtProduced.setFont(UiTheme.FONT_SN);
+		txtCylinderPressure = roField();
+		txtTonnage = roField();
+		txtPressSpm = roField();
+		grid.add(UiTheme.paramTile("生产高度", txtDieHeight, UiTheme.STRIPE_SIDE));
+		grid.add(UiTheme.paramTile("冲次数量", txtStrokeCount, UiTheme.STRIPE_SIDE));
+		grid.add(UiTheme.paramTile("本批已产", txtProduced, UiTheme.STRIPE_SIDE));
+		grid.add(UiTheme.paramTile("顶缸压力", txtCylinderPressure, UiTheme.STRIPE_SIDE));
+		grid.add(UiTheme.paramTile("生产吨位", txtTonnage, UiTheme.STRIPE_SIDE));
+		grid.add(UiTheme.paramTile("压机行程次数", txtPressSpm, UiTheme.STRIPE_SIDE));
+		runCard.add(grid, BorderLayout.CENTER);
+
+		main.add(batchCard, BorderLayout.NORTH);
+		main.add(runCard, BorderLayout.CENTER);
+		add(main, BorderLayout.CENTER);
+
+		JPanel actions = new JPanel(new BorderLayout(0, 0));
+		actions.setOpaque(false);
+		actions.setBorder(new EmptyBorder(0, 20, 16, 20));
+		JLabel tip = UiTheme.mutedLabel("正常靠 SSE 自动取批;未收到推送可点「取批次」,或等约 15 秒安全轮询");
+		btnNext = UiTheme.primaryBtn("取批次");
+		btnNext.addActionListener(new ActionListener() {
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				onManualNextClick();
+			}
+		});
+		JPanel btns = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 0));
+		btns.setOpaque(false);
+		btns.add(btnNext);
+		actions.add(tip, BorderLayout.WEST);
+		actions.add(btns, BorderLayout.EAST);
+		add(actions, BorderLayout.SOUTH);
+	}
+
+	public String getStationSn() {
+		return nvl(cfg.getStationSn());
+	}
+
+	/** 页签/导航名:机型标题 */
+	public String tabTitle() {
+		String t = nvl(cfg.getTitle());
+		return t.isEmpty() ? profile.getTitle() : t;
+	}
+
+	public void initPlc() {
+		plc.connect();
+		uiPlcLabel();
+		refreshSnapshotUi(plc.readSnapshot());
+	}
+
+	/**
+	 * 启动本工位独立周期任务;与另一台互不影响。
+	 *
+	 * @param periodMs 轮询间隔
+	 */
+	public void startStationLoop(int periodMs) {
+		stopStationLoop();
+		final int period = periodMs > 0 ? periodMs : 500;
+		final String sn = nvl(cfg.getStationSn());
+		stationScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
+			@Override
+			public Thread newThread(Runnable r) {
+				Thread t = new Thread(r, "dc-yt-tick-" + sn);
+				t.setDaemon(true);
+				return t;
+			}
+		});
+		stationScheduler.scheduleWithFixedDelay(new Runnable() {
+			@Override
+			public void run() {
+				try {
+					tick();
+				} catch (Throwable t) {
+					log.warn("工位[{}] 周期异常(已隔离,不影响其他压机): {}", sn, t.getMessage());
+				}
+			}
+		}, 800L, period, TimeUnit.MILLISECONDS);
+		log.info("工位[{}] 独立周期已启动 periodMs={}", sn, Integer.valueOf(period));
+	}
+
+	/** 停止本工位周期;退出时由 MainFrame 逐台调用 */
+	public void stopStationLoop() {
+		if (stationScheduler != null) {
+			stationScheduler.shutdownNow();
+			stationScheduler = null;
+		}
+	}
+
+	/**
+	 * 周期:重连、刷过程参数;空闲拉 PDA 批次;RUN 按冲次差结案。
+	 */
+	public void tick() {
+		if (busy.get()) {
+			return;
+		}
+		// 上一拍还在连 PLC / 读点,直接跳过本拍,防止死机拖垮线程池
+		if (!tickInFlight.compareAndSet(false, true)) {
+			return;
+		}
+		try {
+			plc.maintainConnection();
+			uiPlcLabel();
+			// 只刷灯,探活由 MainFrame 后台线程做,避免 HTTP 超时堵住 tick
+			uiServerHeartbeat();
+			DcRunSnapshot snap = plc.readSnapshot();
+			if (snap != null) {
+				lastSnap = snap;
+			}
+			refreshSnapshotUi(snap);
+			if (phase == Phase.IDLE) {
+				// 取批改由 SSE 门铃 / 断线兜底触发,tick 只刷灯与状态
+				if (!MainFrame.isMesServerOnline()) {
+					setStatusUi("空闲:MES/SSE 未连接,等待服务端…");
+				} else {
+					setStatusUi("空闲:等待扫码下发批次…");
+				}
+				return;
+			}
+			if (phase == Phase.DONE) {
+				// 上传曾中断:用挂起报文续传,不重新开批
+				retryPendingCompleteIfAny();
+				return;
+			}
+			if (phase == Phase.RUN) {
+				// PLC 断线时 snap.strokeCount 默认为 0,不能当冲次复位,否则已产会被搅乱
+				if (plc.isConnected() && snap != null && !nvl(snap.strokeCountText).isEmpty()) {
+					updateProducedAgainstStroke(snap.strokeCount);
+				}
+				final int producedUi = producedQty;
+				final String batchUi = batchCode;
+				final int targetUi = targetQty;
+				final boolean plcOk = plc.isConnected();
+				SwingUtilities.invokeLater(new Runnable() {
+					@Override
+					public void run() {
+						setText(txtProduced, String.valueOf(producedUi));
+					}
+				});
+				if (plcOk) {
+					setStatusUi("生产中 批次=" + batchUi + "  已产 " + producedUi + " / 目标 " + targetUi);
+				} else {
+					setStatusUi("生产中 批次=" + batchUi + "  已产 " + producedUi + " / 目标 " + targetUi
+							+ "(PLC 断开,已产保持)");
+				}
+				if (producedQty >= targetQty && targetQty > 0) {
+					finishBatch(producedQty, false);
+				}
+			}
+		} catch (Exception e) {
+			log.warn("工位[{}] tick 异常: {}", cfg.getStationSn(), e.getMessage());
+		} finally {
+			tickInFlight.set(false);
+		}
+	}
+
+	/** SSE / 兜底:空闲则 nextBatch */
+	public void tryAutoNextFromPush() {
+		if (phase != Phase.IDLE) {
+			return;
+		}
+		requestNextAsync();
+	}
+
+	/** SSE 门铃带工位校验 */
+	public void tryAutoNextFromPush(String enqueueStationSn) {
+		if (enqueueStationSn == null || !enqueueStationSn.trim().equalsIgnoreCase(getStationSn())) {
+			return;
+		}
+		tryAutoNextFromPush();
+	}
+
+	/**
+	 * SSE 清码:本机正占用同一批次码则关允许并回空闲。
+	 * 结案上传中(DONE+挂起报文)不打断。
+	 */
+	public void applyClearedFromPush(String clearedSn) {
+		String local = nvl(batchCode);
+		String remote = nvl(clearedSn);
+		if (local.isEmpty() || remote.isEmpty() || !local.equalsIgnoreCase(remote)) {
+			return;
+		}
+		if (phase == Phase.IDLE) {
+			return;
+		}
+		if (phase == Phase.DONE && pendingCompleteFields != null) {
+			log.info("工位[{}] 结案上传中收到清码 sn={},不打断", cfg.getStationSn(), local);
+			return;
+		}
+		if (!busy.compareAndSet(false, true)) {
+			return;
+		}
+		try {
+			log.info("工位[{}] 收到清码推送,复位本地 batch={}", cfg.getStationSn(), local);
+			plc.setMesAllow(false);
+			mesAllowOn = false;
+			pendingCompleteFields = null;
+			resetToIdle("服务端已清码 " + local);
+			MainFrame.setMenuStatus(cfg.getStationSn() + " 已清码 " + local, 0);
+		} finally {
+			busy.set(false);
+		}
+	}
+
+	/** 开批失败等场景:延迟再 next(清空节流,避免被 2s 间隔挡掉) */
+	private void scheduleNextRetry(long delayMs) {
+		final long wait = delayMs > 0L ? delayMs : 3000L;
+		new Thread(new Runnable() {
+			@Override
+			public void run() {
+				try {
+					Thread.sleep(wait);
+				} catch (InterruptedException ie) {
+					Thread.currentThread().interrupt();
+					return;
+				}
+				lastPollBatchAtMs = 0L;
+				tryAutoNextFromPush();
+			}
+		}, "dc-yt-next-retry-" + cfg.getStationSn()).start();
+	}
+
+	/**
+	 * 异步 nextBatch(SSE 门铃或断线兜底调用)。
+	 * HTTP 放后台,不堵本工位 PLC tick。
+	 */
+	public void requestNextAsync() {
+		if (phase != Phase.IDLE) {
+			return;
+		}
+		long now = System.currentTimeMillis();
+		if (now - lastPollBatchAtMs < POLL_BATCH_INTERVAL_MS) {
+			return;
+		}
+		lastPollBatchAtMs = now;
+		if (serverIp.isEmpty()) {
+			setStatusUi("空闲:等待扫码(server-ip 未配,仅可联调模拟)");
+			return;
+		}
+		if (!nextBusy.compareAndSet(false, true)) {
+			return;
+		}
+		new Thread(new Runnable() {
+			@Override
+			public void run() {
+				try {
+					JSONObject ret = MesDcApiClient.nextBatch(serverIp, cfg.getStationSn());
+					if (ret == null) {
+						setStatusUi("空闲:取批次无响应,稍后重试…");
+						return;
+					}
+					if (phase != Phase.IDLE) {
+						return;
+					}
+					if (!MesDcApiClient.isSuccess(ret)) {
+						setStatusUi("空闲:等待扫码下发批次…");
+						return;
+					}
+					String code = MesDcApiClient.dataStr(ret, "batchCode");
+					if (code.isEmpty()) {
+						code = MesDcApiClient.dataStr(ret, "sn");
+					}
+					int target = MesDcApiClient.dataInt(ret, "targetQty", 0);
+					if (target <= 0) {
+						target = MesDcApiClient.dataInt(ret, "qty", 0);
+					}
+					if (code.isEmpty() || target <= 0) {
+						log.warn("工位[{}] nextBatch 成功但缺 batchCode/targetQty: {}", cfg.getStationSn(), ret);
+						return;
+					}
+					startBatchFromPda(code, target);
+				} finally {
+					nextBusy.set(false);
+				}
+			}
+		}, "dc-yt-next-" + cfg.getStationSn()).start();
+	}
+
+	private void startBatchFromPda(String code, int target) {
+		if (phase == Phase.RUN || phase == Phase.DONE) {
+			return;
+		}
+		if (!busy.compareAndSet(false, true)) {
+			return;
+		}
+		try {
+			if (!plc.isConnected()) {
+				plc.connect();
+			}
+			Long base = plc.readStrokeCount();
+			if (base == null) {
+				// 服务端队列已是已取:必须稍后重试 nextBatch,否则 SSE 不会再响铃
+				setStatusUi("收到批次,但读冲次数量失败,将自动重试…");
+				MainFrame.setMenuStatus(cfg.getStationSn() + " 开批失败:读冲次", -1);
+				scheduleNextRetry(3000L);
+				return;
+			}
+			batchCode = code;
+			targetQty = target;
+			baseStrokeCount = base.longValue();
+			lastStrokeCount = baseStrokeCount;
+			producedQty = 0;
+			batchStartTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
+			boolean wrote = plc.setMesAllow(true);
+			mesAllowOn = wrote;
+			phase = Phase.RUN;
+			final String tip = (wrote ? "批次已开,MES允许已写" : "批次已开(允许点未配/写失败,本地仍盯冲次)")
+					+ "  起始冲次=" + baseStrokeCount;
+			final String codeUi = batchCode;
+			final int targetUi = targetQty;
+			SwingUtilities.invokeLater(new Runnable() {
+				@Override
+				public void run() {
+					setText(txtBatch, codeUi);
+					setText(txtTarget, String.valueOf(targetUi));
+					setText(txtProduced, "0");
+					setMesAllowLamp(mesAllowOn);
+					setStatusUi(tip);
+				}
+			});
+			MainFrame.setMenuStatus(cfg.getStationSn() + " 开批 " + batchCode + " 目标" + targetQty, 0);
+			log.info("工位[{}] 开批 batch={} target={} baseStroke={}",
+					cfg.getStationSn(), batchCode, Integer.valueOf(targetQty), Long.valueOf(baseStrokeCount));
+		} finally {
+			busy.set(false);
+		}
+	}
+
+	/**
+	 * 手动取批次:SSE 漏推 / 网络抖时立刻 nextBatch(不受 2s 节流)。
+	 * 仅空闲可用。
+	 */
+	public void onManualNextClick() {
+		if (phase != Phase.IDLE) {
+			setStatusUi("当前非空闲,无法取批次(进行中请用手动提交结案)");
+			return;
+		}
+		lastPollBatchAtMs = 0L;
+		setStatusUi("正在手动取批次…");
+		requestNextAsync();
+	}
+
+	/** 手动提交:密码 mes */
+	public void onManualSubmitClick() {
+		if (phase != Phase.RUN) {
+			setStatusUi("当前无进行中的批次,无法手动提交");
+			return;
+		}
+		if (!askMesPassword()) {
+			return;
+		}
+		finishBatch(producedQty, false, true);
+	}
+
+	private boolean askMesPassword() {
+		JPasswordField pf = new JPasswordField(12);
+		JPanel box = new JPanel(new BorderLayout(8, 8));
+		box.add(new JLabel("请输入密码"), BorderLayout.NORTH);
+		box.add(pf, BorderLayout.CENTER);
+		int opt = JOptionPane.showConfirmDialog(this, box, "手动提交",
+				JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
+		if (opt != JOptionPane.OK_OPTION) {
+			return false;
+		}
+		char[] input = pf.getPassword();
+		boolean ok = Arrays.equals(input, "mes".toCharArray());
+		Arrays.fill(input, '\0');
+		if (!ok) {
+			JOptionPane.showMessageDialog(this, "密码错误", "手动提交", JOptionPane.WARNING_MESSAGE);
+			return false;
+		}
+		return true;
+	}
+
+	private void finishBatch(final int qty, final boolean aborted) {
+		finishBatch(qty, aborted, false);
+	}
+
+	private void finishBatch(final int qty, final boolean aborted, final boolean manual) {
+		if (!busy.compareAndSet(false, true)) {
+			return;
+		}
+		phase = Phase.DONE;
+		final String codeSnap = batchCode;
+		final String timeSnap = batchStartTime;
+		final int targetSnap = targetQty;
+		new Thread(new Runnable() {
+			@Override
+			public void run() {
+				boolean fieldsReady = false;
+				try {
+					plc.setMesAllow(false);
+					mesAllowOn = false;
+					SwingUtilities.invokeLater(new Runnable() {
+						@Override
+						public void run() {
+							setMesAllowLamp(false);
+						}
+					});
+					String time = timeSnap;
+					if (time == null || time.isEmpty()) {
+						time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
+					}
+					final String packCode = DcPackCode.next();
+					String passResult = aborted ? "NG" : "OK";
+					DcRunSnapshot snap = lastSnap == null ? new DcRunSnapshot() : lastSnap;
+					final Map<String, String> fields = new LinkedHashMap<String, String>();
+					fields.put("stationSn", cfg.getStationSn());
+					fields.put("stationTitle", tabTitle());
+					fields.put("batchCode", codeSnap);
+					fields.put("packCode", packCode);
+					fields.put("qty", String.valueOf(qty));
+					fields.put("targetQty", String.valueOf(targetSnap));
+					fields.put("produceTime", time);
+					fields.put("aborted", aborted ? "1" : "0");
+					fields.put("manual", manual ? "1" : "0");
+					fields.put("result", passResult);
+					fields.put("pressProfile", profile.name());
+					fields.put("dieHeight", nvl(snap.dieHeight));
+					fields.put("strokeCount", nvl(snap.strokeCountText));
+					fields.put("cylinderPressure", nvl(snap.cylinderPressure));
+					fields.put("tonnage", nvl(snap.tonnage));
+					fields.put("pressSpm", nvl(snap.pressSpm));
+					fields.put("deviceRunning", snap.deviceRunning ? "1" : "0");
+					fields.put("deviceStateText", nvl(snap.deviceStateText));
+					// 本机记录先落;挂起报文供 DONE 续传
+					DcWorkRecordStore.add(packCode, codeSnap, time, qty, passResult);
+					MainFrame.refreshWorkRecords();
+					String how = aborted ? "已强制结束" : (manual ? "手动提交" : "本批达标");
+					pendingCompleteFields = fields;
+					pendingHow = how;
+					pendingPackCode = packCode;
+					pendingQty = qty;
+					pendingPrinted = false;
+					fieldsReady = true;
+					// 打印异步:打印机卡死不能挡 MES 结案
+					final String printTime = time;
+					new Thread(new Runnable() {
+						@Override
+						public void run() {
+							boolean ok = DcBatchPrinter.printPack(packCode, printTime, qty);
+							pendingPrinted = ok;
+							if (!ok) {
+								log.warn("工位[{}] 异步打印失败/无打印机 pack={}", cfg.getStationSn(), packCode);
+							}
+						}
+					}, "dc-yt-print-" + cfg.getStationSn()).start();
+					// 先放 busy:phase=DONE,tick 可刷灯并可走续传
+					busy.set(false);
+					uploadPendingComplete(true);
+				} catch (Exception ex) {
+					log.error("工位[{}] 结案异常: {}", cfg.getStationSn(), ex.getMessage(), ex);
+					setStatusUi("结案异常:" + ex.getMessage());
+					if (!fieldsReady) {
+						// 报文未备好:回到 RUN,可手动再提交
+						phase = Phase.RUN;
+					}
+				} finally {
+					busy.set(false);
+				}
+			}
+		}, "dc-yt-finish-" + cfg.getStationSn()).start();
+	}
+
+	/** DONE 态 tick 触发:有挂起结案则续传 */
+	private void retryPendingCompleteIfAny() {
+		if (pendingCompleteFields == null) {
+			return;
+		}
+		uploadPendingComplete(false);
+	}
+
+	/**
+	 * 上传挂起的结案报文;成功才回空闲。
+	 *
+	 * @param fromFinishThread true=结案线程内首轮(可多等几轮);false=tick 续传单次
+	 */
+	private void uploadPendingComplete(boolean fromFinishThread) {
+		final Map<String, String> fields = pendingCompleteFields;
+		if (fields == null) {
+			return;
+		}
+		if (!completeRetryBusy.compareAndSet(false, true)) {
+			return;
+		}
+		final String how = pendingHow;
+		final String packCode = pendingPackCode;
+		final int qty = pendingQty;
+		try {
+			int maxAttempts = fromFinishThread ? 12 : 1;
+			boolean uploaded = false;
+			for (int attempt = 1; attempt <= maxAttempts; attempt++) {
+				JSONObject ret = MesDcApiClient.completeBatch(serverIp, fields);
+				uploaded = MesDcApiClient.isSuccess(ret);
+				if (uploaded) {
+					MainFrame.setMesServerOnline(true);
+					break;
+				}
+				setStatusUi(how + "  包装码=" + packCode + "  上传失败,重试中…(#" + attempt + ")");
+				MainFrame.setMenuStatus(cfg.getStationSn() + " 上传失败重试 #" + attempt, -1);
+				log.warn("工位[{}] 结案上传失败 pack={} attempt={}",
+						cfg.getStationSn(), packCode, Integer.valueOf(attempt));
+				if (attempt < maxAttempts) {
+					try {
+						Thread.sleep(5000L);
+					} catch (InterruptedException ie) {
+						Thread.currentThread().interrupt();
+						break;
+					}
+				}
+			}
+			if (uploaded) {
+				pendingCompleteFields = null;
+				final String tip = how + "  包装码=" + packCode + "  数量=" + qty
+						+ (pendingPrinted ? "  已送打印" : "  打印已提交/待确认")
+						+ "  已上传";
+				resetToIdle(tip);
+				MainFrame.setMenuStatus(cfg.getStationSn() + " 结案 " + packCode + " x" + qty, 0);
+				log.info("工位[{}] 结案成功 pack={} qty={}", cfg.getStationSn(), packCode, Integer.valueOf(qty));
+			} else {
+				setStatusUi(how + "  包装码=" + packCode + "  等待续传…");
+			}
+		} finally {
+			completeRetryBusy.set(false);
+		}
+	}
+
+	/**
+	 * 按冲次累计本批已产;冲次变小则保留已产并重定起点。
+	 */
+	private void updateProducedAgainstStroke(long strokeCount) {
+		if (strokeCount < lastStrokeCount) {
+			int kept = producedQty;
+			baseStrokeCount = strokeCount - kept;
+			log.warn("工位[{}] 检测到冲次复位/变小:上次={} 本次={},保留已产={},重定起点={}",
+					cfg.getStationSn(),
+					Long.valueOf(lastStrokeCount),
+					Long.valueOf(strokeCount),
+					Integer.valueOf(kept),
+					Long.valueOf(baseStrokeCount));
+			setStatusUi("检测到冲次复位,已保留本批进度 " + kept + " / " + targetQty);
+		}
+		long producedLong = strokeCount - baseStrokeCount;
+		int produced = producedLong > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) producedLong;
+		if (produced < 0) {
+			produced = 0;
+		}
+		if (produced > producedQty) {
+			producedQty = produced;
+		}
+		lastStrokeCount = strokeCount;
+	}
+
+	private void resetToIdle(String msg) {
+		phase = Phase.IDLE;
+		batchCode = "";
+		targetQty = 0;
+		baseStrokeCount = 0L;
+		producedQty = 0;
+		lastStrokeCount = 0L;
+		batchStartTime = "";
+		mesAllowOn = false;
+		pendingCompleteFields = null;
+		pendingHow = "";
+		pendingPackCode = "";
+		pendingQty = 0;
+		pendingPrinted = false;
+		SwingUtilities.invokeLater(new Runnable() {
+			@Override
+			public void run() {
+				setText(txtBatch, "");
+				setText(txtTarget, "");
+				setText(txtProduced, "");
+				setMesAllowLamp(false);
+				setStatusUi(msg == null || msg.isEmpty()
+						? "空闲:等待扫码下发批次…" : msg + "  → 等待下一笔");
+			}
+		});
+	}
+
+	private void refreshSnapshotUi(final DcRunSnapshot s) {
+		if (s == null) {
+			return;
+		}
+		SwingUtilities.invokeLater(new Runnable() {
+			@Override
+			public void run() {
+				setText(txtDieHeight, s.dieHeight);
+				setText(txtStrokeCount, s.strokeCountText);
+				setText(txtCylinderPressure, s.cylinderPressure);
+				setText(txtTonnage, s.tonnage);
+				setText(txtPressSpm, s.pressSpm);
+				// 允许灯跟真实写点结果,不因 phase=RUN 就常绿
+				setMesAllowLamp(mesAllowOn);
+			}
+		});
+	}
+
+	/** 刷新 MES 允许灯;已在 EDT 时可直接调 */
+	private void setMesAllowLamp(final boolean on) {
+		Runnable r = new Runnable() {
+			@Override
+			public void run() {
+				if (plc.getMesAllowAddr().isEmpty()) {
+					lampMesAllow.setOn(false);
+					lblMesAllowState.setText("预留");
+					return;
+				}
+				lampMesAllow.setOn(on);
+				lblMesAllowState.setText(on ? "开" : "关");
+			}
+		};
+		if (SwingUtilities.isEventDispatchThread()) {
+			r.run();
+		} else {
+			SwingUtilities.invokeLater(r);
+		}
+	}
+
+	private void uiPlcLabel() {
+		final boolean ok = plc.isConnected();
+		SwingUtilities.invokeLater(new Runnable() {
+			@Override
+			public void run() {
+				lampPlc.setLevel(ok ? StatusLight.Level.ON : StatusLight.Level.FAULT);
+				lblPlcState.setText(ok ? "已连接" : "未连接");
+			}
+		});
+	}
+
+	/** 按 SSE 连接态刷新 MES 呼吸灯 */
+	private void uiServerHeartbeat() {
+		final boolean online = MainFrame.isMesServerOnline();
+		SwingUtilities.invokeLater(new Runnable() {
+			@Override
+			public void run() {
+				serverHeartbeat.setOnline(online);
+				serverHeartbeat.setToolTipText(online
+						? "服务端已连接(SSE 正常)"
+						: "服务端已断开(SSE 未连)");
+			}
+		});
+	}
+
+	private static JLabel headerStateLabel(String text) {
+		JLabel lb = new JLabel(text, SwingConstants.CENTER);
+		lb.setFont(new Font("微软雅黑", Font.PLAIN, 11));
+		lb.setForeground(new Color(200, 230, 235));
+		lb.setAlignmentX(Component.CENTER_ALIGNMENT);
+		return lb;
+	}
+
+	private static JPanel headerLampItem(String name, StatusLight lamp, JLabel stateLbl) {
+		JPanel p = new JPanel();
+		p.setOpaque(false);
+		p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
+		JLabel lb = new JLabel(name, SwingConstants.CENTER);
+		lb.setFont(new Font("微软雅黑", Font.PLAIN, 12));
+		lb.setForeground(new Color(160, 210, 220));
+		lb.setAlignmentX(Component.CENTER_ALIGNMENT);
+		lamp.setAlignmentX(Component.CENTER_ALIGNMENT);
+		stateLbl.setAlignmentX(Component.CENTER_ALIGNMENT);
+		p.add(lb);
+		p.add(Box.createVerticalStrut(2));
+		p.add(lamp);
+		p.add(Box.createVerticalStrut(2));
+		p.add(stateLbl);
+		return p;
+	}
+
+	/** 顶栏 MES 呼吸灯一组:名称在上、灯居中 */
+	private static JPanel headerBreathingItem(String name, BreathingLight lamp) {
+		JPanel p = new JPanel();
+		p.setOpaque(false);
+		p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
+		JLabel lb = new JLabel(name, SwingConstants.CENTER);
+		lb.setFont(new Font("微软雅黑", Font.PLAIN, 12));
+		lb.setForeground(new Color(160, 210, 220));
+		lb.setAlignmentX(Component.CENTER_ALIGNMENT);
+		lamp.setAlignmentX(Component.CENTER_ALIGNMENT);
+		p.add(lb);
+		p.add(Box.createVerticalStrut(4));
+		p.add(lamp);
+		return p;
+	}
+
+	private void setStatusUi(final String text) {
+		SwingUtilities.invokeLater(new Runnable() {
+			@Override
+			public void run() {
+				lblStatus.setText(text == null ? "" : text);
+				String t = text == null ? "" : text;
+				if (t.contains("失败") || t.contains("故障")) {
+					lblStatus.setBackground(UiTheme.ERR_BG);
+					lblStatus.setForeground(UiTheme.ERR_FG);
+				} else if (t.contains("生产中") || t.contains("已开") || t.contains("开批")) {
+					lblStatus.setBackground(UiTheme.RUN_BG);
+					lblStatus.setForeground(UiTheme.RUN_FG);
+				} else {
+					lblStatus.setBackground(UiTheme.OK_BG);
+					lblStatus.setForeground(UiTheme.OK_FG);
+				}
+			}
+		});
+	}
+
+	private static JTextField roField() {
+		JTextField t = new JTextField();
+		t.setEditable(false);
+		t.setFont(UiTheme.FONT_VALUE);
+		return t;
+	}
+
+	private static void setText(JTextField t, String v) {
+		if (t != null) {
+			t.setText(v == null ? "" : v);
+		}
+	}
+
+	private static String nvl(String s) {
+		return s == null ? "" : s.trim();
+	}
+}

+ 72 - 0
src/main/java/com/mes/ui/StatusLight.java

@@ -0,0 +1,72 @@
+package com.mes.ui;
+
+import javax.swing.*;
+import java.awt.*;
+
+/**
+ * 指示灯:灰 / 绿 / 红。
+ */
+public class StatusLight extends JComponent {
+
+	private static final long serialVersionUID = 1L;
+
+	private static final Color GRAY = new Color(120, 130, 140);
+	private static final Color GREEN = new Color(40, 220, 100);
+	private static final Color RED = new Color(230, 60, 50);
+
+	/** 灯色档:灭灰 / 亮绿 / 故障红 */
+	public enum Level {
+		OFF, ON, FAULT
+	}
+
+	private volatile Level level = Level.OFF;
+
+	public StatusLight() {
+		setPreferredSize(new Dimension(36, 28));
+		setMinimumSize(new Dimension(28, 24));
+		setOpaque(false);
+	}
+
+	/** 开关:true=绿,false=灰 */
+	public void setOn(boolean on) {
+		setLevel(on ? Level.ON : Level.OFF);
+	}
+
+	public boolean isOn() {
+		return level == Level.ON;
+	}
+
+	/** 设灯色档 */
+	public void setLevel(Level level) {
+		this.level = level == null ? Level.OFF : level;
+		repaint();
+	}
+
+	public Level getLevel() {
+		return level;
+	}
+
+	@Override
+	protected void paintComponent(Graphics g) {
+		super.paintComponent(g);
+		Graphics2D g2 = (Graphics2D) g.create();
+		try {
+			g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+			int w = getWidth();
+			int h = getHeight();
+			int r = Math.min(w, h) / 2 - 2;
+			int cx = w / 2;
+			int cy = h / 2;
+			Color c = GRAY;
+			if (level == Level.ON) {
+				c = GREEN;
+			} else if (level == Level.FAULT) {
+				c = RED;
+			}
+			g2.setColor(c);
+			g2.fillOval(cx - r, cy - r, r * 2, r * 2);
+		} finally {
+			g2.dispose();
+		}
+	}
+}

+ 225 - 0
src/main/java/com/mes/ui/UiTheme.java

@@ -0,0 +1,225 @@
+package com.mes.ui;
+
+import javax.swing.*;
+import javax.swing.border.Border;
+import javax.swing.border.EmptyBorder;
+import java.awt.*;
+
+/**
+ * 大冲客户端视觉主题:浅灰底 + 深蓝顶栏,字号偏大适合工控屏。
+ */
+public final class UiTheme {
+
+	private UiTheme() {
+	}
+
+	/** 页面底 */
+	public static final Color BG = new Color(236, 240, 245);
+	public static final Color CARD = Color.WHITE;
+	public static final Color LINE = new Color(210, 218, 228);
+	public static final Color TEXT = new Color(30, 41, 59);
+	public static final Color MUTED = new Color(100, 116, 139);
+
+	/** 顶栏:深蓝灰,不用发绿发紫的旧渐变 */
+	public static final Color HEADER_TOP = new Color(30, 41, 59);
+	public static final Color HEADER_BOTTOM = new Color(51, 65, 85);
+	/** 主强调:钢蓝 */
+	public static final Color ACCENT = new Color(37, 99, 235);
+	public static final Color ACCENT_DARK = new Color(29, 78, 216);
+	/** 次强调 */
+	public static final Color AMBER = new Color(217, 119, 6);
+	public static final Color AMBER_DARK = new Color(180, 95, 6);
+
+	public static final Color OK_BG = new Color(220, 252, 231);
+	public static final Color OK_FG = new Color(22, 101, 52);
+	public static final Color RUN_BG = new Color(219, 234, 254);
+	public static final Color RUN_FG = new Color(30, 64, 175);
+	public static final Color ERR_BG = new Color(254, 226, 226);
+	public static final Color ERR_FG = new Color(185, 28, 28);
+	public static final Color WARN_FG = new Color(217, 119, 6);
+
+	/** 参数格左侧色条(统一钢蓝,减少杂色) */
+	public static final Color STRIPE_SIDE = new Color(37, 99, 235);
+	public static final Color STRIPE_VOLT = STRIPE_SIDE;
+	public static final Color STRIPE_AMP = STRIPE_SIDE;
+	public static final Color STRIPE_WIRE = STRIPE_SIDE;
+	public static final Color STRIPE_JOB = STRIPE_SIDE;
+	public static final Color STRIPE_ERR = new Color(220, 38, 38);
+	public static final Color STRIPE_DEV = STRIPE_SIDE;
+
+	public static final Font FONT_TITLE = new Font("微软雅黑", Font.BOLD, 26);
+	public static final Font FONT_BODY = new Font("微软雅黑", Font.PLAIN, 18);
+	public static final Font FONT_LABEL = new Font("微软雅黑", Font.PLAIN, 16);
+	public static final Font FONT_SN = new Font("微软雅黑", Font.BOLD, 40);
+	/** 示值:工控大屏可读,铺满格子时不显空 */
+	public static final Font FONT_VALUE = new Font("微软雅黑", Font.BOLD, 36);
+	public static final Font FONT_BTN = new Font("微软雅黑", Font.BOLD, 16);
+
+	/** 参数格偏好高度(可随布局拉伸) */
+	public static final int TILE_PREF_H = 120;
+
+	public static void applyLookAndFeel() {
+		try {
+			for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
+				if ("Nimbus".equals(info.getName())) {
+					UIManager.setLookAndFeel(info.getClassName());
+					UIManager.put("nimbusBase", HEADER_BOTTOM);
+					UIManager.put("nimbusBlueGrey", new Color(71, 85, 105));
+					UIManager.put("control", BG);
+					UIManager.put("nimbusSelectionBackground", ACCENT);
+					UIManager.put("TabbedPane:TabbedPaneTab[Enabled].backgroundPainter", null);
+					return;
+				}
+			}
+			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
+		} catch (Exception ignored) {
+		}
+	}
+
+	/** 顶栏渐变面板 */
+	public static JPanel gradientHeader() {
+		return new JPanel(new BorderLayout(16, 0)) {
+			private static final long serialVersionUID = 1L;
+
+			@Override
+			protected void paintComponent(Graphics g) {
+				Graphics2D g2 = (Graphics2D) g.create();
+				g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+				GradientPaint gp = new GradientPaint(0, 0, HEADER_TOP, 0, getHeight(), HEADER_BOTTOM);
+				g2.setPaint(gp);
+				g2.fillRect(0, 0, getWidth(), getHeight());
+				g2.setColor(ACCENT);
+				g2.fillRect(0, getHeight() - 3, getWidth(), 3);
+				g2.dispose();
+			}
+		};
+	}
+
+	public static Border cardBorder() {
+		return BorderFactory.createCompoundBorder(
+				BorderFactory.createLineBorder(LINE),
+				new EmptyBorder(12, 14, 12, 14));
+	}
+
+	public static JPanel card() {
+		JPanel p = new JPanel();
+		p.setBackground(CARD);
+		p.setBorder(cardBorder());
+		return p;
+	}
+
+	/** 带左侧色条的参数格(输入框) */
+	public static JPanel paramTile(String label, JTextField field, Color stripe) {
+		return paramTile(label, (JComponent) field, stripe);
+	}
+
+	/**
+	 * 带左侧色条的参数格:标签在上、大字示值居中,格子可随布局拉伸填满空白。
+	 */
+	public static JPanel paramTile(String label, JComponent field, Color stripe) {
+		JPanel outer = new JPanel(new BorderLayout(0, 0));
+		outer.setOpaque(false);
+		outer.setPreferredSize(new Dimension(240, TILE_PREF_H));
+		JPanel stripeBar = new JPanel();
+		stripeBar.setPreferredSize(new Dimension(6, 10));
+		stripeBar.setBackground(stripe == null ? STRIPE_SIDE : stripe);
+		stripeBar.setOpaque(true);
+		JPanel inner = new JPanel(new BorderLayout(0, 8));
+		inner.setBackground(new Color(248, 250, 252));
+		inner.setBorder(new EmptyBorder(14, 16, 14, 16));
+		JLabel lb = mutedLabel(label);
+		inner.add(lb, BorderLayout.NORTH);
+		field.setBackground(new Color(248, 250, 252));
+		field.setFont(FONT_VALUE);
+		field.setForeground(TEXT);
+		if (field instanceof JTextField) {
+			JTextField tf = (JTextField) field;
+			tf.setBorder(BorderFactory.createEmptyBorder(4, 0, 0, 0));
+			tf.setHorizontalAlignment(SwingConstants.LEFT);
+		}
+		inner.add(field, BorderLayout.CENTER);
+		outer.add(stripeBar, BorderLayout.WEST);
+		outer.add(inner, BorderLayout.CENTER);
+		outer.setBorder(BorderFactory.createLineBorder(LINE));
+		return outer;
+	}
+
+	public static JLabel mutedLabel(String text) {
+		JLabel l = new JLabel(text);
+		l.setFont(FONT_LABEL);
+		l.setForeground(MUTED);
+		return l;
+	}
+
+	public static JLabel sectionTitle(String text) {
+		JLabel l = new JLabel(text);
+		l.setFont(new Font("微软雅黑", Font.BOLD, 18));
+		l.setForeground(TEXT);
+		return l;
+	}
+
+	public static JTextField valueField() {
+		JTextField f = new JTextField();
+		f.setEditable(false);
+		f.setFont(FONT_VALUE);
+		f.setForeground(TEXT);
+		f.setBackground(Color.WHITE);
+		f.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
+		return f;
+	}
+
+	public static JButton primaryBtn(String text) {
+		JButton b = new JButton(text) {
+			private static final long serialVersionUID = 1L;
+
+			@Override
+			protected void paintComponent(Graphics g) {
+				Graphics2D g2 = (Graphics2D) g.create();
+				g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+				GradientPaint gp = new GradientPaint(0, 0, ACCENT, 0, getHeight(), ACCENT_DARK);
+				g2.setPaint(gp);
+				g2.fillRoundRect(0, 0, getWidth(), getHeight(), 8, 8);
+				g2.dispose();
+				super.paintComponent(g);
+			}
+		};
+		b.setFont(FONT_BTN);
+		b.setPreferredSize(new Dimension(132, 44));
+		b.setFocusPainted(false);
+		b.setContentAreaFilled(false);
+		b.setBorderPainted(false);
+		b.setForeground(Color.WHITE);
+		b.setOpaque(false);
+		b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
+		return b;
+	}
+
+	public static JButton ghostBtn(String text) {
+		JButton b = new JButton(text);
+		b.setFont(new Font("微软雅黑", Font.PLAIN, 15));
+		int w = Math.max(100, (text == null ? 0 : text.length()) * 18 + 28);
+		b.setPreferredSize(new Dimension(w, 44));
+		b.setFocusPainted(false);
+		b.setBackground(CARD);
+		b.setForeground(TEXT);
+		b.setOpaque(true);
+		b.setBorder(BorderFactory.createCompoundBorder(
+				BorderFactory.createLineBorder(LINE),
+				new EmptyBorder(6, 14, 6, 14)));
+		b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
+		return b;
+	}
+
+	/** PLC 状态小胶囊底色 */
+	public static void stylePlcPill(JLabel label, boolean ok) {
+		label.setOpaque(true);
+		label.setBorder(new EmptyBorder(6, 12, 6, 12));
+		if (ok) {
+			label.setBackground(new Color(30, 64, 175));
+			label.setForeground(new Color(191, 219, 254));
+		} else {
+			label.setBackground(new Color(69, 40, 30));
+			label.setForeground(WARN_FG);
+		}
+	}
+}

+ 117 - 0
src/main/java/com/mes/ui/WorkRecordPanel.java

@@ -0,0 +1,117 @@
+package com.mes.ui;
+
+import com.mes.entity.DcWorkRecord;
+import com.mes.service.DcWorkRecordStore;
+
+import javax.swing.*;
+import javax.swing.border.EmptyBorder;
+import javax.swing.table.DefaultTableCellRenderer;
+import javax.swing.table.DefaultTableModel;
+import java.awt.*;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.util.List;
+
+/**
+ * 工作记录页:批次码、记录时间、数量、过站结果。
+ */
+public class WorkRecordPanel extends JPanel {
+
+	private static final long serialVersionUID = 1L;
+
+	private final DefaultTableModel model;
+	private final JLabel lblStatus;
+	private final JButton btnRefresh;
+
+	public WorkRecordPanel() {
+		setLayout(new BorderLayout(0, 0));
+		setBackground(UiTheme.BG);
+		setBorder(new EmptyBorder(0, 0, 0, 0));
+
+		JPanel header = UiTheme.gradientHeader();
+		header.setBorder(new EmptyBorder(12, 16, 12, 16));
+		JLabel title = new JLabel("工作记录");
+		title.setFont(UiTheme.FONT_TITLE);
+		title.setForeground(Color.WHITE);
+		// 顶栏深绿底:按钮用半透明描边,避免 ghost 白底 + 白字变成空白块
+		btnRefresh = new JButton("刷新");
+		btnRefresh.setFont(new Font("微软雅黑", Font.PLAIN, 14));
+		btnRefresh.setForeground(Color.WHITE);
+		btnRefresh.setFocusPainted(false);
+		btnRefresh.setContentAreaFilled(false);
+		btnRefresh.setOpaque(false);
+		btnRefresh.setBorder(BorderFactory.createCompoundBorder(
+				BorderFactory.createLineBorder(new Color(140, 210, 220)),
+				new EmptyBorder(6, 14, 6, 14)));
+		btnRefresh.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
+		btnRefresh.addActionListener(new ActionListener() {
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				reload();
+			}
+		});
+		header.add(title, BorderLayout.WEST);
+		header.add(btnRefresh, BorderLayout.EAST);
+		add(header, BorderLayout.NORTH);
+
+		String[] cols = new String[] { "包装码", "批次码", "记录时间", "数量", "结果" };
+		model = new DefaultTableModel(cols, 0) {
+			private static final long serialVersionUID = 1L;
+
+			@Override
+			public boolean isCellEditable(int row, int column) {
+				return false;
+			}
+		};
+		JTable table = new JTable(model);
+		table.setFont(UiTheme.FONT_BODY);
+		table.setRowHeight(28);
+		table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 13));
+		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+		table.setAutoCreateRowSorter(true);
+		DefaultTableCellRenderer center = new DefaultTableCellRenderer();
+		center.setHorizontalAlignment(SwingConstants.CENTER);
+		for (int i = 0; i < table.getColumnCount(); i++) {
+			table.getColumnModel().getColumn(i).setCellRenderer(center);
+		}
+		table.getColumnModel().getColumn(0).setPreferredWidth(160);
+		table.getColumnModel().getColumn(1).setPreferredWidth(160);
+		table.getColumnModel().getColumn(2).setPreferredWidth(150);
+		table.getColumnModel().getColumn(3).setPreferredWidth(70);
+		table.getColumnModel().getColumn(4).setPreferredWidth(70);
+
+		JScrollPane scroll = new JScrollPane(table);
+		scroll.setBorder(BorderFactory.createEmptyBorder(12, 16, 8, 16));
+		scroll.getViewport().setBackground(UiTheme.CARD);
+		add(scroll, BorderLayout.CENTER);
+
+		lblStatus = new JLabel(" ");
+		lblStatus.setFont(UiTheme.FONT_BODY);
+		lblStatus.setBorder(new EmptyBorder(8, 16, 12, 16));
+		lblStatus.setForeground(UiTheme.MUTED);
+		add(lblStatus, BorderLayout.SOUTH);
+
+		reload();
+	}
+
+	/** 从本机记录库刷新表格 */
+	public void reload() {
+		List<DcWorkRecord> list = DcWorkRecordStore.list();
+		model.setRowCount(0);
+		for (int i = 0; i < list.size(); i++) {
+			DcWorkRecord r = list.get(i);
+			if (r == null) {
+				continue;
+			}
+			model.addRow(new Object[] {
+					r.packCode,
+					r.batchCode,
+					r.recordTime,
+					Integer.valueOf(r.qty),
+					r.result
+			});
+		}
+		lblStatus.setText("共 " + list.size() + " 条");
+		lblStatus.setForeground(UiTheme.MUTED);
+	}
+}

+ 89 - 0
src/main/java/com/mes/util/SingleInstanceLock.java

@@ -0,0 +1,89 @@
+package com.mes.util;
+
+/**
+ * 单实例文件锁:防止同一客户端重复启动。
+ */
+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 SingleInstanceLock {
+    private FileChannel channel;
+
+    private FileLock lock;
+
+    private File file;
+
+    private static SingleInstanceLock instance = null;
+
+    /**
+     * 获取唯一进程限制的实例
+     * @Title: getInstance
+     * @return  唯一进程实例
+     */
+    public static SingleInstanceLock getInstance(){
+        if(instance == null){
+            instance = new SingleInstanceLock();
+        }
+        return instance;
+    }
+
+    /**
+     * 进程是否正在运行
+     * @Title: isAppActive
+     * @return  运行与否
+     */
+    public boolean isAppActive() {
+        // 必须赋给成员变量,shutdown 时才能删掉 .lock
+        this.file = new File(".lock");
+        try {
+            channel = new RandomAccessFile(this.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 {
+            if (file != null) {
+                file.delete();
+            }
+        } catch (Exception e) {
+            // ignore
+        }
+    }
+
+    private void closeLock() {
+        try {
+            lock.release();
+        } catch (Exception e) {
+
+        }
+
+        try {
+            channel.close();
+        } catch (Exception e) {
+
+        }
+    }
+}

+ 47 - 0
src/main/java/com/mes/util/UiImages.java

@@ -0,0 +1,47 @@
+package com.mes.util;
+
+import java.net.URL;
+
+import javax.swing.ImageIcon;
+
+
+/**
+ * 界面图片资源统一入口。
+ * <p>
+ * 资源目录:{@code classpath:/images/}
+ * <ul>
+ *   <li>{@code images/} — 登录背景、窗口图标等</li>
+ *   <li>{@code images/icons/} — 按钮/菜单/状态图标</li>
+ * </ul>
+ * </p>
+ */
+public final class UiImages {
+
+	/** 图片根路径 */
+	public static final String ROOT = "/images/";
+	/** 图标子目录 */
+	public static final String ICONS = ROOT + "icons/";
+
+	private UiImages() {
+	}
+
+	/** 取 images/ 下资源 URL,例如 background.png */
+	public static URL of(String fileName) {
+		return UiImages.class.getResource(ROOT + fileName);
+	}
+
+	/** 取 images/icons/ 下图标 URL,例如 logo.png */
+	public static URL icon(String fileName) {
+		return UiImages.class.getResource(ICONS + fileName);
+	}
+
+	/** 图标 ImageIcon */
+	public static ImageIcon iconImage(String fileName) {
+		return new ImageIcon(icon(fileName));
+	}
+
+	/** images/ 下 ImageIcon */
+	public static ImageIcon image(String fileName) {
+		return new ImageIcon(of(fileName));
+	}
+}

+ 37 - 0
src/main/resources/config/application.yml

@@ -0,0 +1,37 @@
+# 一拖二大冲:TE2-800 + TL4-1600
+# 取批次 →MES允许=true → 轮询冲次 → 达标允许=false → 打印
+
+spring:
+  main:
+    web-application-type: none
+    banner-mode: off
+  application:
+    name: mesclient-dachong-yt
+
+logging:
+  level:
+    root: INFO
+    com.mes: INFO
+
+mes:
+  app-title: MES 一拖二大冲
+  server-ip: 127.0.0.1
+  tick-ms: 500
+  printer-name:
+  stations:
+    - id: 1
+      title: TE2-800
+      station-sn: DC-TE2
+      press-profile: TE2_800
+      plc-ip: 192.168.0.1
+      plc-port: 102
+      # MES允许:
+      mes-allow-addr:
+    - id: 2
+      title: TL4-1600
+      station-sn: DC-TL4
+      press-profile: TL4_1600
+      plc-ip: 192.168.1.99
+      plc-port: 102
+      # MES允许:点表 DB76.DBX128.1
+      mes-allow-addr: DB76.128.1

TEMPAT SAMPAH
src/main/resources/images/background.png


TEMPAT SAMPAH
src/main/resources/images/close_bt.png


TEMPAT SAMPAH
src/main/resources/images/icon.ico


TEMPAT SAMPAH
src/main/resources/images/icons/a_side.png


TEMPAT SAMPAH
src/main/resources/images/icons/b_side.png


TEMPAT SAMPAH
src/main/resources/images/icons/bar_add.png


TEMPAT SAMPAH
src/main/resources/images/icons/bar_bookmark.png


TEMPAT SAMPAH
src/main/resources/images/icons/bar_cmd_go.png


TEMPAT SAMPAH
src/main/resources/images/icons/bar_edit.png


TEMPAT SAMPAH
src/main/resources/images/icons/bar_pause.png


TEMPAT SAMPAH
src/main/resources/images/icons/bar_sampling.png


TEMPAT SAMPAH
src/main/resources/images/icons/bar_setting.png


TEMPAT SAMPAH
src/main/resources/images/icons/bar_stop.png


TEMPAT SAMPAH
src/main/resources/images/icons/close_bt.png


TEMPAT SAMPAH
src/main/resources/images/icons/company_setting_logo.png


TEMPAT SAMPAH
src/main/resources/images/icons/delete.png


TEMPAT SAMPAH
src/main/resources/images/icons/department_setting_logo.png


TEMPAT SAMPAH
src/main/resources/images/icons/download.png


TEMPAT SAMPAH
src/main/resources/images/icons/equipment_setting_logo.png


TEMPAT SAMPAH
src/main/resources/images/icons/gj_001_1_20.png


TEMPAT SAMPAH
src/main/resources/images/icons/gj_001_21_40.png


TEMPAT SAMPAH
src/main/resources/images/icons/gj_001_41_60.png


TEMPAT SAMPAH
src/main/resources/images/icons/green_dot.png


TEMPAT SAMPAH
src/main/resources/images/icons/grey_dot.png


TEMPAT SAMPAH
src/main/resources/images/icons/icon.png


TEMPAT SAMPAH
src/main/resources/images/icons/inductance_logo.png


TEMPAT SAMPAH
src/main/resources/images/icons/insulation_logo.png


TEMPAT SAMPAH
src/main/resources/images/icons/login.png


TEMPAT SAMPAH
src/main/resources/images/icons/logo.png


TEMPAT SAMPAH
src/main/resources/images/icons/logoff.png


TEMPAT SAMPAH
src/main/resources/images/icons/menu_data_analysis.png


TEMPAT SAMPAH
src/main/resources/images/icons/menu_data_preprocess.png


TEMPAT SAMPAH
src/main/resources/images/icons/menu_file.png


TEMPAT SAMPAH
src/main/resources/images/icons/menu_setting.png


TEMPAT SAMPAH
src/main/resources/images/icons/min_bt.png


TEMPAT SAMPAH
src/main/resources/images/icons/ng_bg.png


TEMPAT SAMPAH
src/main/resources/images/icons/ok_bg.png


TEMPAT SAMPAH
src/main/resources/images/icons/open_file.png


TEMPAT SAMPAH
src/main/resources/images/icons/refresh.png


TEMPAT SAMPAH
src/main/resources/images/icons/reset_logo.png


TEMPAT SAMPAH
src/main/resources/images/icons/resistance_logo.png


TEMPAT SAMPAH
src/main/resources/images/icons/save_bg.png


TEMPAT SAMPAH
src/main/resources/images/icons/scan_barcode.png


TEMPAT SAMPAH
src/main/resources/images/icons/tree_folder_icon.png


TEMPAT SAMPAH
src/main/resources/images/icons/tree_leaf_icon.png


TEMPAT SAMPAH
src/main/resources/images/icons/user.png


TEMPAT SAMPAH
src/main/resources/images/icons/vertical_line.png


TEMPAT SAMPAH
src/main/resources/images/icons/zoom_in.png


TEMPAT SAMPAH
src/main/resources/images/icons/zoom_out.png


TEMPAT SAMPAH
src/main/resources/images/info_bt.png


TEMPAT SAMPAH
src/main/resources/images/min_bt.png


+ 44 - 0
src/main/resources/logback.xml

@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<configuration>
+
+    <!-- 定义日志文件的存储位置及文件名 -->
+    <property name="LOG_HOME" value="D:/Logs"/>
+    <property name="PROJECT_NAME" value="log"/>
+
+    <!-- 控制台输出 -->
+    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+        <encoder>
+            <pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level  %logger{36} - %msg%n</pattern>
+        </encoder>
+        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
+            <level>INFO</level>
+        </filter>
+    </appender>
+
+    <!-- 文件输出 -->
+    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
+        <file>${LOG_HOME}/${PROJECT_NAME}/${PROJECT_NAME}.log</file>
+        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+            <fileNamePattern>${LOG_HOME}/${PROJECT_NAME}/archived/${PROJECT_NAME}_%d{yyyy-MM-dd}.log</fileNamePattern>
+            <!-- 保留最近 1个月内的日志-->
+            <maxHistory>30</maxHistory>  <!-- 如果删除该项配置,则logback无法自动删除旧日志, 导致totalSizeCap也将失去作用-->
+            <!-- 滚动文件总大小不超过1GB-->
+            <totalSizeCap>1GB</totalSizeCap>
+        </rollingPolicy>
+        <encoder>
+            <pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level  %logger{36} - %msg%n</pattern>
+        </encoder>
+    </appender>
+
+    <!-- 根Logger -->
+    <root level="info">
+        <appender-ref ref="STDOUT" />
+        <appender-ref ref="FILE" />
+    </root>
+
+    <logger name="org.slf4j" level="ERROR"/>
+    <logger name="ch.qos.logback" level="ERROR"/>
+    <logger name="ch.qos.logback.classic.joran.action.ConfigurationAction" level="OFF"/>
+
+</configuration>