zxl 3 недель назад
Родитель
Сommit
8aa5efedbb

+ 81 - 1
src/main/java/com/mes/service/MesDcApiClient.java

@@ -4,13 +4,20 @@ import com.alibaba.fastjson2.JSONObject;
 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.io.UnsupportedEncodingException;
+import java.net.HttpURLConnection;
+import java.net.URL;
 import java.net.URLEncoder;
 import java.util.LinkedHashMap;
 import java.util.Map;
 
 /**
- * 一拖二大冲工控机 HTTP:取批次 / 结案一次上传(按批次码追溯+过程参数)。
+ * 一拖二大冲工控机 HTTP:取批次 / 结案 / 过程参数采样上传。
  */
 public final class MesDcApiClient {
 
@@ -38,6 +45,16 @@ public final class MesDcApiClient {
 	}
 
 	/**
+	 * 压机过程参数批量上报(JSON):落 mes_flex_dc_yt_press_param,供曲线。
+	 * 路径:{@code /js/a/mes/mesFlexDcYt/uploadPressParam}。
+	 *
+	 * @param body 含 batchCode、stationSn、pressNo、pressModel、samples[]
+	 */
+	public static JSONObject uploadPressParam(String serverIp, JSONObject body) {
+		return postJson(serverIp, "/js/a/mes/mesFlexDcYt/uploadPressParam", body);
+	}
+
+	/**
 	 * 探活服务端(不取码、不结案):短超时连 8980。
 	 * 须在独立线程调用,勿放进工位 tick,否则不通时会卡住指示灯刷新。
 	 */
@@ -127,6 +144,69 @@ public final class MesDcApiClient {
 		}
 	}
 
+	/** JSON POST(过程参数采样) */
+	private static JSONObject postJson(String serverIp, String path, JSONObject body) {
+		HttpURLConnection connection = null;
+		InputStream is = null;
+		OutputStream os = null;
+		BufferedReader br = null;
+		try {
+			String url = "http://" + nvl(serverIp) + ":8980" + path;
+			String json = body == null ? "{}" : body.toJSONString();
+			log.debug("dc JSON POST {} body={}", path, json);
+			connection = (HttpURLConnection) new URL(url).openConnection();
+			connection.setRequestMethod("POST");
+			connection.setConnectTimeout(15000);
+			connection.setReadTimeout(60000);
+			connection.setDoOutput(true);
+			connection.setDoInput(true);
+			connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
+			os = connection.getOutputStream();
+			os.write(json.getBytes("UTF-8"));
+			if (connection.getResponseCode() != 200) {
+				log.warn("HTTP {} => {}", url, Integer.valueOf(connection.getResponseCode()));
+				return null;
+			}
+			is = connection.getInputStream();
+			br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
+			StringBuilder sbf = new StringBuilder();
+			String temp;
+			while ((temp = br.readLine()) != null) {
+				sbf.append(temp);
+			}
+			String raw = sbf.toString();
+			if (raw.isEmpty()) {
+				return null;
+			}
+			return JSONObject.parseObject(raw);
+		} catch (Exception e) {
+			log.debug("dc JSON 请求异常 path={} err={}", path, e.getMessage());
+			return null;
+		} 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();
+			}
+		}
+	}
+
 	private static String toForm(Map<String, String> fields) throws UnsupportedEncodingException {
 		StringBuilder sb = new StringBuilder();
 		sb.append("__ajax=json");

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

@@ -1,5 +1,6 @@
 package com.mes.ui;
 
+import com.alibaba.fastjson2.JSONArray;
 import com.alibaba.fastjson2.JSONObject;
 import com.mes.config.DcPressProfiles;
 import com.mes.config.MesClientProperties;
@@ -17,9 +18,11 @@ import java.awt.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.text.SimpleDateFormat;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Date;
 import java.util.LinkedHashMap;
+import java.util.List;
 import java.util.Map;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
@@ -37,6 +40,12 @@ public class StationPanel extends JPanel {
 
 	/** 兜底轮询最小间隔(SSE 正常时不走 tick 取批) */
 	private static final long POLL_BATCH_INTERVAL_MS = 2000L;
+	/** 过程参数采样间隔(毫秒),对齐自动化大冲曲线上报 */
+	private static final long SAMPLE_MS = 1000L;
+	/** 缓冲满多少点再批量上报 */
+	private static final int UPLOAD_MAX = 20;
+	/** 采样缓冲上限,失败回塞时防内存涨爆 */
+	private static final int SAMPLE_BUF_CAP = 100;
 
 	public enum Phase {
 		IDLE, RUN, DONE
@@ -74,6 +83,10 @@ public class StationPanel extends JPanel {
 	private volatile int pendingQty;
 	private volatile boolean pendingPrinted;
 	private final AtomicBoolean completeRetryBusy = new AtomicBoolean(false);
+	/** 过程参数采样缓冲(供曲线) */
+	private final List<Map<String, String>> sampleBuf = new ArrayList<Map<String, String>>();
+	private volatile long lastSampleAtMs;
+	private final AtomicBoolean sampleUploading = new AtomicBoolean(false);
 
 	private final JLabel lblStation;
 	private final JLabel lblStatus;
@@ -311,6 +324,10 @@ public class StationPanel extends JPanel {
 				if (plc.isConnected() && snap != null && !nvl(snap.strokeCountText).isEmpty()) {
 					updateProducedAgainstStroke(snap.strokeCount);
 				}
+				// 生产中按间隔采样过程参数,供管理端曲线
+				if (plc.isConnected() && snap != null) {
+					offerSample(snap);
+				}
 				final int producedUi = producedQty;
 				final String batchUi = batchCode;
 				final int targetUi = targetQty;
@@ -328,6 +345,7 @@ public class StationPanel extends JPanel {
 							+ "(PLC 断开,已产保持)");
 				}
 				if (producedQty >= targetQty && targetQty > 0) {
+					// 尾点采样在 finishBatch 线程里按本批码刷出,避免与 resetToIdle 清缓冲打架
 					finishBatch(producedQty, false);
 				}
 			}
@@ -612,6 +630,8 @@ public class StationPanel extends JPanel {
 			public void run() {
 				boolean fieldsReady = false;
 				try {
+					// 先把本批采样尽量送出(短等),再结案;避免尾点丢失或失败回塞串到下一批
+					flushSamplesForBatch(codeSnap);
 					plc.setMesAllow(false);
 					mesAllowOn = false;
 					SwingUtilities.invokeLater(new Runnable() {
@@ -749,6 +769,152 @@ public class StationPanel extends JPanel {
 	}
 
 	/**
+	 * RUN 态采样过程参数入缓冲;满 UPLOAD_MAX 异步上报。
+	 */
+	private void offerSample(DcRunSnapshot snap) {
+		if (snap == null || batchCode == null || batchCode.isEmpty()) {
+			return;
+		}
+		long now = System.currentTimeMillis();
+		if (now - lastSampleAtMs < SAMPLE_MS) {
+			return;
+		}
+		lastSampleAtMs = now;
+		Map<String, String> pt = new LinkedHashMap<String, String>();
+		pt.put("sampleTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
+		pt.put("dieHeight", nvl(snap.dieHeight));
+		pt.put("strokeCount", nvl(snap.strokeCountText));
+		pt.put("cylinderPressure", nvl(snap.cylinderPressure));
+		pt.put("tonnage", nvl(snap.tonnage));
+		pt.put("pressSpm", nvl(snap.pressSpm));
+		pt.put("energyKwh", nvl(snap.energyKwh));
+		pt.put("deviceRunning", snap.deviceRunning ? "1" : "0");
+		pt.put("deviceStateText", nvl(snap.deviceStateText));
+		boolean needFlush = false;
+		synchronized (sampleBuf) {
+			sampleBuf.add(pt);
+			// 失败回塞过多时丢最旧点,避免内存涨
+			while (sampleBuf.size() > SAMPLE_BUF_CAP) {
+				sampleBuf.remove(0);
+			}
+			needFlush = sampleBuf.size() >= UPLOAD_MAX;
+		}
+		if (needFlush) {
+			flushSamplesAsync(batchCode);
+		}
+	}
+
+	/**
+	 * 结案前:等在途上传结束,再刷光本批缓冲并短等,降低尾点丢失。
+	 */
+	private void flushSamplesForBatch(String batch) {
+		if (batch == null || batch.isEmpty()) {
+			return;
+		}
+		waitSampleUploadIdle(3000L);
+		flushSamplesAsync(batch);
+		waitSampleUploadIdle(5000L);
+	}
+
+	private void waitSampleUploadIdle(long maxWaitMs) {
+		long deadline = System.currentTimeMillis() + maxWaitMs;
+		while (sampleUploading.get() && System.currentTimeMillis() < deadline) {
+			try {
+				Thread.sleep(50L);
+			} catch (InterruptedException e) {
+				Thread.currentThread().interrupt();
+				return;
+			}
+		}
+	}
+
+	/**
+	 * 异步批量上报采样点。
+	 * @param forceBatch 指定批次码(结案时用快照);空则用当前 batchCode
+	 */
+	private void flushSamplesAsync(String forceBatch) {
+		final String batch = (forceBatch != null && !forceBatch.isEmpty()) ? forceBatch : batchCode;
+		if (batch == null || batch.isEmpty()) {
+			return;
+		}
+		final List<Map<String, String>> chunk;
+		synchronized (sampleBuf) {
+			if (sampleBuf.isEmpty()) {
+				return;
+			}
+			chunk = new ArrayList<Map<String, String>>(sampleBuf);
+			sampleBuf.clear();
+		}
+		if (serverIp == null || serverIp.isEmpty()) {
+			return;
+		}
+		if (!sampleUploading.compareAndSet(false, true)) {
+			// 已有上传在途:塞回缓冲,下轮再刷(须仍是同一批才有意义)
+			if (batch.equals(batchCode)) {
+				synchronized (sampleBuf) {
+					sampleBuf.addAll(0, chunk);
+					while (sampleBuf.size() > SAMPLE_BUF_CAP) {
+						sampleBuf.remove(sampleBuf.size() - 1);
+					}
+				}
+			}
+			return;
+		}
+		new Thread(new Runnable() {
+			@Override
+			public void run() {
+				try {
+					JSONObject body = new JSONObject();
+					body.put("batchCode", batch);
+					body.put("stationSn", cfg.getStationSn());
+					body.put("pressNo", Integer.valueOf(cfg.getId()));
+					body.put("pressModel", nvl(cfg.getPressProfile()));
+					body.put("stationTitle", nvl(cfg.getTitle()));
+					JSONArray arr = new JSONArray();
+					for (Map<String, String> pt : chunk) {
+						arr.add(new JSONObject(pt));
+					}
+					body.put("samples", arr);
+					JSONObject ret = MesDcApiClient.uploadPressParam(serverIp, body);
+					if (!MesDcApiClient.isSuccess(ret)) {
+						log.warn("工位[{}] 采样上报失败 batch={}: {}",
+								cfg.getStationSn(), batch, MesDcApiClient.messageOf(ret));
+						// 仅本批仍在产时回塞,避免串到下一批
+						requeueSamplesIfSameBatch(batch, chunk);
+					} else {
+						log.info("工位[{}] 采样上报成功 points={} batch={}",
+								cfg.getStationSn(), Integer.valueOf(chunk.size()), batch);
+					}
+				} catch (Exception ex) {
+					log.warn("工位[{}] 采样上报异常 batch={}: {}",
+							cfg.getStationSn(), batch, ex.getMessage());
+					requeueSamplesIfSameBatch(batch, chunk);
+				} finally {
+					sampleUploading.set(false);
+				}
+			}
+		}, "dc-yt-press-upload-" + cfg.getStationSn()).start();
+	}
+
+	/** 上报失败回塞:只有当前仍是同一批次才回塞,防串批 */
+	private void requeueSamplesIfSameBatch(String batch, List<Map<String, String>> chunk) {
+		if (chunk == null || chunk.isEmpty()) {
+			return;
+		}
+		if (batch == null || !batch.equals(batchCode)) {
+			log.warn("工位[{}] 采样失败且批次已切换/已空闲,丢弃 points={} oldBatch={}",
+					cfg.getStationSn(), Integer.valueOf(chunk.size()), batch);
+			return;
+		}
+		synchronized (sampleBuf) {
+			sampleBuf.addAll(0, chunk);
+			while (sampleBuf.size() > SAMPLE_BUF_CAP) {
+				sampleBuf.remove(sampleBuf.size() - 1);
+			}
+		}
+	}
+
+	/**
 	 * 按冲次累计本批已产;冲次变小则保留已产并重定起点。
 	 */
 	private void updateProducedAgainstStroke(long strokeCount) {
@@ -779,6 +945,9 @@ public class StationPanel extends JPanel {
 		batchCode = "";
 		targetQty = 0;
 		baseStrokeCount = 0L;
+		synchronized (sampleBuf) {
+			sampleBuf.clear();
+		}
 		producedQty = 0;
 		lastStrokeCount = 0L;
 		batchStartTime = "";