zxl 4 недель назад
Родитель
Сommit
ce2025d1fe

+ 102 - 34
src/main/java/com/mes/service/HgPlcClient.java

@@ -3,29 +3,34 @@ package com.mes.service;
 import com.mes.entity.WeldParams;
 import HslCommunication.Core.Types.OperateResult;
 import HslCommunication.Core.Types.OperateResultExOne;
-import HslCommunication.Profinet.Melsec.MelsecMcNet;
+import HslCommunication.Profinet.Melsec.MelsecMcUdp;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * 单工位弧焊 PLC(三菱 MC 协议):一拖五每站独立连接。
+ * 单工位弧焊 PLC(三菱 MC UDP binary):一拖五每站独立连接。
  * <p>
- * 点位与现场五站表一致(各站地址相同,仅 IP 不同):
- * MES启用 L180;设备运行 M1200;
- * A面运行/完成 M1216/M1222,B面 M1217/M1223;
- * R1 电压/电流/送丝 D822/D803/D805,R2 为 D826/D807/D809;
- * A/B JOB 号 D970/D980。
+ * 现场约定:MC 协议 UDP 二进制,默认端口 5006。
+ * 断线重连:指数退避 2s→4s→8s→16s→30s(封顶后固定 30s),连上后复位。
+ * 点位:L180=MES允许启动;M1200 设备运行;A/B 面 M1216/1222、M1217/1223;
+ * R1=D822/803/805+D970;R2=D826/807/809+D980。
  * </p>
  */
 public class HgPlcClient {
 
 	private static final Logger log = LoggerFactory.getLogger(HgPlcClient.class);
 
-	/** Melsoft 默认 TCP 端口 */
-	public static final int DEFAULT_PORT = 6000;
+	/** 现场 MC UDP binary 端口 */
+	public static final int DEFAULT_PORT = 5006;
+	/** UDP 收包超时(毫秒) */
+	private static final int RECEIVE_TIMEOUT_MS = 5000;
+	/** 断线后首次重连间隔:2 秒 */
+	private static final long RETRY_INITIAL_MS = 2L * 1000L;
+	/** 重连间隔上限:30 秒(指数退避封顶后固定) */
+	private static final long RETRY_MAX_MS = 30L * 1000L;
 
-	/** MES 启用/屏蔽 */
-	private static final String ADDR_MES_ENABLE = "L180";
+	/** MES 允许启动信号(true=允许设备启动,false=屏蔽) */
+	private static final String ADDR_MES_ALLOW_START = "L180";
 	/** 设备运行中 */
 	private static final String ADDR_DEVICE_RUN = "M1200";
 	/** A 面运行中 / 完成 */
@@ -49,8 +54,13 @@ public class HgPlcClient {
 	private final String stationSn;
 	private final String plcIp;
 	private final int plcPort;
-	private MelsecMcNet plc;
+	/** MC UDP binary(非 TCP Melsoft) */
+	private MelsecMcUdp plc;
 	private volatile boolean connected;
+	/** 下次允许重连探活的时间戳 */
+	private volatile long nextRetryAtMs;
+	/** 当前重连间隔:2s → 4s → 8s → 16s → 30s(封顶) */
+	private volatile long currentRetryDelayMs = RETRY_INITIAL_MS;
 
 	public HgPlcClient(String stationSn, String plcIp) {
 		this(stationSn, plcIp, DEFAULT_PORT);
@@ -79,7 +89,19 @@ public class HgPlcClient {
 	}
 
 	/**
-	 * 建立 MC 连接;失败只记日志,不抛,避免拖死其它工位。
+	 * tick 调用:未连接时按指数退避自动重连(2s→4s→8s→16s→30s)。
+	 * 已连接则直接返回,不探活。
+	 */
+	public void maintainConnection() {
+		if (isConnected()) {
+			return;
+		}
+		connect();
+	}
+
+	/**
+	 * 建立 MC UDP 通道;UDP 无长连接握手,用轻量读验证可达。
+	 * 失败只记日志并指数退避,避免关机站把整条 tick 线程堵死。
 	 */
 	public synchronized void connect() {
 		if (plcIp.isEmpty()) {
@@ -87,6 +109,10 @@ public class HgPlcClient {
 			log.warn("工位[{}] PLC IP 为空,跳过连接", stationSn);
 			return;
 		}
+		long now = System.currentTimeMillis();
+		if (now < nextRetryAtMs) {
+			return;
+		}
 		try {
 			if (plc != null) {
 				try {
@@ -95,29 +121,32 @@ public class HgPlcClient {
 					// ignore
 				}
 			}
-			plc = new MelsecMcNet(plcIp, plcPort);
-			plc.SetPersistentConnection();
-			OperateResult r = plc.ConnectServer();
-			if (r == null || !r.IsSuccess) {
-				connected = false;
-				String msg = r == null ? "null" : r.Message;
-				log.warn("工位[{}] 三菱 PLC 连接失败 {}:{} {}", stationSn, plcIp, plcPort, msg);
+			// MC 协议 · UDP · binary,端口默认 5006
+			plc = new MelsecMcUdp(plcIp, plcPort);
+			plc.setReceiveTimeOut(RECEIVE_TIMEOUT_MS);
+			// 轻量读验证:通了才算已连接
+			OperateResultExOne<Boolean> probe = plc.ReadBool(ADDR_DEVICE_RUN);
+			if (probe == null || !probe.IsSuccess) {
+				String msg = probe == null ? "null" : probe.Message;
+				long waitSec = scheduleRetryAfterFailure() / 1000L;
+				log.warn("工位[{}] 三菱 PLC UDP 不通 {}:{} {}({}s 后再试)",
+						stationSn, plcIp, plcPort, msg, Long.valueOf(waitSec));
 				return;
 			}
-			// 轻量读验证
-			readBool(ADDR_DEVICE_RUN);
 			connected = true;
-			log.info("工位[{}] 三菱 PLC 已连接 {}:{}", stationSn, plcIp, plcPort);
+			resetRetryBackoff();
+			log.info("工位[{}] 三菱 PLC 已连接(MC UDP binary) {}:{}", stationSn, plcIp, plcPort);
 		} catch (Exception e) {
-			connected = false;
 			plc = null;
-			log.warn("工位[{}] PLC 连接异常 {}: {}", stationSn, plcIp, e.getMessage());
+			long waitSec = scheduleRetryAfterFailure() / 1000L;
+			log.warn("工位[{}] PLC 连接异常 {}: {}({}s 后再试)",
+					stationSn, plcIp, e.getMessage(), Long.valueOf(waitSec));
 		}
 	}
 
-	/** MES 允许进站:写 L180 */
+	/** 写 L180:MES 允许启动信号 */
 	public boolean setMesAllowEntry(boolean allow) {
-		return writeBool(ADDR_MES_ENABLE, allow);
+		return writeBool(ADDR_MES_ALLOW_START, allow);
 	}
 
 	/** 设备运行中 M1200(监控展示) */
@@ -146,7 +175,7 @@ public class HgPlcClient {
 	}
 
 	/**
-	 * 任一面已启动(用于撤销 MES 允许进站)。
+	 * 任一面已启动(用于撤销 L180 允许启动信号)。
 	 */
 	public boolean isAnySideRunning() {
 		return isARunning() || isBRunning();
@@ -188,7 +217,7 @@ public class HgPlcClient {
 			p.errorCode = "";
 		} catch (Exception e) {
 			log.warn("工位[{}] 采参失败 side={}: {}", stationSn, s, e.getMessage());
-			connected = false;
+			markDisconnectedAndResetBackoff();
 		}
 		return p;
 	}
@@ -218,13 +247,13 @@ public class HgPlcClient {
 			OperateResultExOne<Boolean> r = plc.ReadBool(addr);
 			if (r == null || !r.IsSuccess) {
 				log.warn("工位[{}] 读位 {} 失败: {}", stationSn, addr, r == null ? "null" : r.Message);
-				connected = false;
+				markDisconnectedWithBackoff();
 				return false;
 			}
 			return Boolean.TRUE.equals(r.Content);
 		} catch (Exception e) {
 			log.warn("工位[{}] 读位 {} 异常: {}", stationSn, addr, e.getMessage());
-			connected = false;
+			markDisconnectedWithBackoff();
 			return false;
 		}
 	}
@@ -237,13 +266,13 @@ public class HgPlcClient {
 			OperateResult r = plc.Write(addr, value);
 			if (r == null || !r.IsSuccess) {
 				log.warn("工位[{}] 写位 {}={} 失败: {}", stationSn, addr, value, r == null ? "null" : r.Message);
-				connected = false;
+				markDisconnectedWithBackoff();
 				return false;
 			}
 			return true;
 		} catch (Exception e) {
 			log.warn("工位[{}] 写位 {}={} 异常: {}", stationSn, addr, value, e.getMessage());
-			connected = false;
+			markDisconnectedWithBackoff();
 			return false;
 		}
 	}
@@ -253,9 +282,48 @@ public class HgPlcClient {
 		OperateResultExOne<Short> r = plc.ReadInt16(addr);
 		if (r == null || !r.IsSuccess || r.Content == null) {
 			log.warn("工位[{}] 读字 {} 失败: {}", stationSn, addr, r == null ? "null" : r.Message);
-			connected = false;
+			markDisconnectedWithBackoff();
 			return "";
 		}
 		return String.valueOf(r.Content.shortValue());
 	}
+
+	/**
+	 * 通讯中途失败:断开,并从 2s 起重新退避(刚掉线应较快重试)。
+	 */
+	private void markDisconnectedWithBackoff() {
+		markDisconnectedAndResetBackoff();
+	}
+
+	private void markDisconnectedAndResetBackoff() {
+		connected = false;
+		currentRetryDelayMs = RETRY_INITIAL_MS;
+		nextRetryAtMs = System.currentTimeMillis() + currentRetryDelayMs;
+	}
+
+	/**
+	 * 一次重连失败:按当前间隔等待,并把间隔翻倍(封顶 30s)。
+	 *
+	 * @return 本次实际等待的毫秒数(打日志用)
+	 */
+	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;
+	}
+
+	/** 连上后清退避,下次断线再从 2s 起 */
+	private void resetRetryBackoff() {
+		currentRetryDelayMs = RETRY_INITIAL_MS;
+		nextRetryAtMs = 0L;
+	}
 }

+ 87 - 7
src/main/java/com/mes/ui/StationPanel.java

@@ -24,8 +24,9 @@ import java.util.concurrent.atomic.AtomicBoolean;
 /**
  * 单个工位面板:一个工位编码,A/B 面由 PLC 点位识别(入队/取码不分面)。
  * <p>
- * 取码 → 写 L180 允许进站 → 哪面先运行就绑定哪面 →
+ * 取码 → 写 L180(MES允许启动)→ 哪面先运行就绑定哪面 →
  * 运行中每秒采参进集合 → 该面运行结束 → 集合一次性 uploadAndSubmit。
+ * 取码后超半小时未结案:丢弃采样并清队列,须重新扫码。
  * </p>
  */
 public class StationPanel extends JPanel {
@@ -34,6 +35,8 @@ public class StationPanel extends JPanel {
 
 	/** 运行中采参间隔(毫秒) */
 	private static final long SAMPLE_INTERVAL_MS = 1000L;
+	/** 取码后本件最长保留:半小时;超时丢弃采样并清队列,需重新扫码 */
+	private static final long MAX_JOB_MS = 30L * 60L * 1000L;
 
 	/** IDLE 空闲;HOLD 已取码等启动;RUN 已识别焊接面加工中;UPLOAD 上传中 */
 	public enum Phase {
@@ -53,6 +56,12 @@ public class StationPanel extends JPanel {
 	private volatile boolean seenRunning;
 	/** 上次采参时间,控制每秒一条 */
 	private volatile long lastSampleAtMs;
+	/** 取码成功时刻;用于半小时超时丢弃 */
+	private volatile long jobStartedAtMs;
+	/** 监控用 M1200 上次读取时间;空闲时降频,避免 500ms tick 狂读 UDP */
+	private volatile long lastPlcStatusAtMs;
+	/** 缓存的设备运行状态(降频刷新) */
+	private volatile boolean cachedDeviceRunning;
 	/**
 	 * 运行中采样集合:结束后一次性上传(勿在循环打库)。
 	 * 仅本面板 tick/上传线程访问,tick 单线程调度。
@@ -107,7 +116,8 @@ public class StationPanel extends JPanel {
 		titleCol.add(lblStation);
 		titleCol.add(Box.createVerticalStrut(3));
 		titleCol.add(lblCode);
-		lblPlc = new JLabel("PLC " + nvl(cfg.getPlcIp()) + "  ·  未连接");
+		// 现场 MC UDP binary:5006
+		lblPlc = new JLabel("PLC " + nvl(cfg.getPlcIp()) + ":5006(UDP)  ·  未连接");
 		lblPlc.setFont(UiTheme.FONT_BODY);
 		UiTheme.stylePlcPill(lblPlc, false);
 		serverHeartbeat = new BreathingLight();
@@ -160,7 +170,7 @@ public class StationPanel extends JPanel {
 
 		JPanel paramCard = UiTheme.card();
 		paramCard.setLayout(new BorderLayout(0, 12));
-		paramCard.add(UiTheme.sectionTitle("过程参数(运行中每秒刷新,结束后集合上传)"), BorderLayout.NORTH);
+		paramCard.add(UiTheme.sectionTitle("过程参数"), BorderLayout.NORTH);
 		JPanel paramGrid = new JPanel(new GridLayout(4, 2, 12, 12));
 		paramGrid.setOpaque(false);
 		txtVoltage = UiTheme.valueField();
@@ -173,7 +183,7 @@ public class StationPanel extends JPanel {
 		paramGrid.add(UiTheme.paramTile("电压", txtVoltage, UiTheme.STRIPE_VOLT));
 		paramGrid.add(UiTheme.paramTile("电流", txtCurrent, UiTheme.STRIPE_AMP));
 		paramGrid.add(UiTheme.paramTile("送丝速度", txtWire, UiTheme.STRIPE_WIRE));
-		paramGrid.add(UiTheme.paramTile("焊接面(客户端识别)", txtSide, UiTheme.STRIPE_SIDE));
+		paramGrid.add(UiTheme.paramTile("焊接面", txtSide, UiTheme.STRIPE_SIDE));
 		paramGrid.add(UiTheme.paramTile("JOB号", txtJobNo, UiTheme.STRIPE_JOB));
 		paramGrid.add(UiTheme.paramTile("错误代码", txtErrorCode, UiTheme.STRIPE_ERR));
 		paramGrid.add(UiTheme.paramTile("设备", txtDeviceType, UiTheme.STRIPE_DEV));
@@ -319,12 +329,22 @@ public class StationPanel extends JPanel {
 	/**
 	 * HOLD:等 A 或 B 运行 → 绑定 activeSide;
 	 * RUN:运行中每秒采参入集合;运行结束后集合一次性上传。
+	 * 取码后超过半小时未正常结案:丢弃采样、清服务端队列,需重新扫码。
 	 */
 	public void tick() {
 		if (busy.get()) {
 			return;
 		}
 		try {
+			// 断线自动重连:2s→4s→8s→16s→30s 指数退避
+			plc.maintainConnection();
+			// 半小时超时:HOLD/RUN 丢弃本件(UPLOAD 中不打断)
+			if ((phase == Phase.HOLD || phase == Phase.RUN) && isJobTimedOut()) {
+				discardJobByTimeout();
+				uiPlcLabel();
+				uiServerHeartbeat();
+				return;
+			}
 			if (phase == Phase.HOLD) {
 				String side = detectRunningSide();
 				if (side != null) {
@@ -415,6 +435,50 @@ public class StationPanel extends JPanel {
 		refreshParamsUi(wp);
 	}
 
+	/** 取码后是否已超过半小时 */
+	private boolean isJobTimedOut() {
+		return jobStartedAtMs > 0L && (System.currentTimeMillis() - jobStartedAtMs) >= MAX_JOB_MS;
+	}
+
+	/**
+	 * 半小时超时:丢弃内存采样、关 L180、清服务端队列,界面回空闲;须 PDA 重新扫码入队。
+	 */
+	private void discardJobByTimeout() {
+		final String sn = nvl(currentSn);
+		final int points = sampleBuffer.size();
+		log.warn("工位[{}] 本件超时半小时,丢弃采样 points={} sn={}", cfg.getStationSn(), Integer.valueOf(points), sn);
+		sampleBuffer.clear();
+		plc.setMesAllowEntry(false);
+		if (!busy.compareAndSet(false, true)) {
+			// 并发占用时仍先本地复位,避免继续采参涨内存
+			resetToIdle("本件超时半小时已丢弃,请重新扫码");
+			MainFrame.setMenuStatus(cfg.getStationSn() + " 超时丢弃 " + sn, -1);
+			return;
+		}
+		setStatusUi("本件超时半小时,丢弃数据并清码...");
+		new Thread(new Runnable() {
+			@Override
+			public void run() {
+				try {
+					if (!sn.isEmpty()) {
+						JSONObject ret = MesFlexApiClient.clear(serverIp, sn, cfg.getStationSn(), userCode);
+						if (!MesFlexApiClient.isSuccess(ret)) {
+							log.warn("工位[{}] 超时清码失败 sn={} msg={}", cfg.getStationSn(), sn,
+									MesFlexApiClient.messageOf(ret));
+						}
+					}
+				} catch (Exception e) {
+					log.warn("工位[{}] 超时清码异常: {}", cfg.getStationSn(), e.getMessage());
+				} finally {
+					plc.setMesAllowEntry(false);
+					resetToIdle("本件超时半小时已丢弃,请重新扫码");
+					MainFrame.setMenuStatus(cfg.getStationSn() + " 超时丢弃 " + sn, -1);
+					busy.set(false);
+				}
+			}
+		}, "hg-timeout-" + cfg.getStationSn()).start();
+	}
+
 	public void requestNextAsync() {
 		if (!busy.compareAndSet(false, true)) {
 			return;
@@ -508,6 +572,8 @@ public class StationPanel extends JPanel {
 		seenRunning = false;
 		lastSampleAtMs = 0L;
 		sampleBuffer.clear();
+		// 半小时计时从取码成功开始(含等启动 + 采参)
+		jobStartedAtMs = System.currentTimeMillis();
 		phase = Phase.HOLD;
 		SwingUtilities.invokeLater(new Runnable() {
 			@Override
@@ -634,6 +700,7 @@ public class StationPanel extends JPanel {
 		activeSide = "";
 		seenRunning = false;
 		lastSampleAtMs = 0L;
+		jobStartedAtMs = 0L;
 		sampleBuffer.clear();
 		SwingUtilities.invokeLater(new Runnable() {
 			@Override
@@ -692,15 +759,28 @@ public class StationPanel extends JPanel {
 
 	private void uiPlcLabel() {
 		final boolean ok = plc.isConnected();
-		final boolean run = ok && plc.isDeviceRunning();
+		boolean run = false;
+		if (ok) {
+			long now = System.currentTimeMillis();
+			// 空闲监控:最多 2 秒读一次 M1200;加工态仍走 tick 里的面信号
+			if (now - lastPlcStatusAtMs >= 2000L) {
+				cachedDeviceRunning = plc.isDeviceRunning();
+				lastPlcStatusAtMs = now;
+			}
+			run = cachedDeviceRunning;
+		} else {
+			cachedDeviceRunning = false;
+			lastPlcStatusAtMs = 0L;
+		}
+		final boolean runUi = run;
 		SwingUtilities.invokeLater(new Runnable() {
 			@Override
 			public void run() {
 				if (ok) {
-					lblPlc.setText("PLC " + nvl(cfg.getPlcIp()) + "  ·  已连接" + (run ? " · 设备运行" : ""));
+					lblPlc.setText("PLC " + nvl(cfg.getPlcIp()) + ":5006(UDP)  ·  已连接" + (runUi ? " · 设备运行" : ""));
 					UiTheme.stylePlcPill(lblPlc, true);
 				} else {
-					lblPlc.setText("PLC " + nvl(cfg.getPlcIp()) + "  ·  未连接");
+					lblPlc.setText("PLC " + nvl(cfg.getPlcIp()) + ":5006(UDP)  ·  未连接");
 					UiTheme.stylePlcPill(lblPlc, false);
 				}
 			}

+ 2 - 2
src/main/resources/config/application.yml

@@ -11,8 +11,8 @@ logging:
     root: INFO
     com.mes: INFO
 
-# 弧焊一拖五:每站一个工位编码 + 一台三菱 PLC
-# 点位:L180 MES启用;M1216/M1222=A运行/完成;M1217/M1223=B;R1=D822/803/805+D970;R2=D826/807/809+D980
+# 弧焊一拖五:每站一个工位编码 + 一台三菱 PLC(MC UDP binary,端口 5006)
+# 点位:L180=MES允许启动;M1216/M1222=A运行/完成;M1217/M1223=B;R1=D822/803/805+D970;R2=D826/807/809+D980
 mes:
   app-title: MES 弧焊客户端
   server-ip: 127.0.0.1