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.MesClientProperties; import com.mes.entity.DcPressSnapshot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 单台压机 S7 客户端:按 yml 点表读过程参数。 * IP 或冲次地址未配则不连,避免拖死其它站。 */ public class DcPressPlcClient { private static final Logger log = LoggerFactory.getLogger(DcPressPlcClient.class); private static final long RETRY_INITIAL_MS = 2L * 1000L; private static final long RETRY_MAX_MS = 30L * 1000L; private final MesClientProperties.PressConfig cfg; private S7PLC plc; private volatile boolean connected; private volatile long nextRetryAtMs; private volatile long currentRetryDelayMs = RETRY_INITIAL_MS; public DcPressPlcClient(MesClientProperties.PressConfig cfg) { this.cfg = cfg; } public MesClientProperties.PressConfig getCfg() { return cfg; } public String getStationSn() { return nvl(cfg.getStationSn()); } public int getPressNo() { return cfg.getPressNo(); } public boolean isConnected() { return connected && plc != null; } /** tick:未连接按退避重连 */ public void maintainConnection() { if (isConnected()) { return; } connect(); } /** 连接并用冲次探活;IP/冲次地址空则跳过 */ public synchronized void connect() { if (isConnected()) { return; } long now = System.currentTimeMillis(); if (now < nextRetryAtMs) { return; } String ip = nvl(cfg.getPlcIp()); String strokeAddr = nvl(cfg.getStrokeCountAddr()); if (ip.isEmpty() || strokeAddr.isEmpty()) { connected = false; long waitSec = scheduleRetryAfterFailure() / 1000L; log.warn("压机[{}] PLC IP 或冲次地址未配置,跳过连接({}s 后再试)", cfg.getPressNo(), Long.valueOf(waitSec)); return; } try { int port = cfg.getPlcPort() <= 0 ? 102 : cfg.getPlcPort(); plc = new S7PLC(EPlcType.S1200, ip, port); plc.readUInt32(strokeAddr); connected = true; resetRetryBackoff(); log.info("压机[{}] {} PLC 已连接 {}:{}", Integer.valueOf(cfg.getPressNo()), nvl(cfg.getTitle()), ip, Integer.valueOf(port)); } catch (Exception e) { connected = false; plc = null; long waitSec = scheduleRetryAfterFailure() / 1000L; log.warn("压机[{}] PLC 连接失败 — {}({}s 后再试)", Integer.valueOf(cfg.getPressNo()), e.getMessage(), Long.valueOf(waitSec)); } } /** 轮询读本机过程参数;地址空则对应字段留空 */ public DcPressSnapshot readSnapshot() { DcPressSnapshot s = new DcPressSnapshot(); if (!ensurePlc()) { return s; } try { String strokeAddr = nvl(cfg.getStrokeCountAddr()); if (!strokeAddr.isEmpty()) { long stroke = plc.readUInt32(strokeAddr); s.strokeCount = stroke; s.strokeCountText = String.valueOf(stroke); } s.dieHeight = readFloatText(cfg.getDieHeightAddr()); s.cylinderPressure = readFloatText(cfg.getCylinderPressureAddr()); String tonAddr = nvl(cfg.getTonnageAddr()); if (!tonAddr.isEmpty()) { if (cfg.isTonnageDint()) { s.tonnage = String.valueOf(plc.readInt32(tonAddr)); } else { s.tonnage = fmtFloat(plc.readFloat32(tonAddr)); } } s.pressSpm = readFloatText(cfg.getPressSpmAddr()); s.airCushion = readFloatText(cfg.getAirCushionAddr()); s.ejectorStroke = readFloatText(cfg.getEjectorStrokeAddr()); // 能耗 DINT String energyAddr = nvl(cfg.getEnergyAddr()); if (!energyAddr.isEmpty()) { s.energyKwh = String.valueOf(plc.readInt32(energyAddr)); } String runAddr = nvl(cfg.getDeviceRunAddr()); if (!runAddr.isEmpty()) { s.deviceRunning = plc.readBoolean(runAddr); s.deviceStateText = s.deviceRunning ? "运行" : "停止"; } } catch (Exception e) { log.warn("压机[{}] 读过程参数失败: {}", Integer.valueOf(cfg.getPressNo()), e.getMessage()); markDisconnectedAndResetBackoff(); } return s; } /** 仅读冲次;失败返回 null */ public Long readStrokeCount() { String strokeAddr = nvl(cfg.getStrokeCountAddr()); if (strokeAddr.isEmpty() || !ensurePlc()) { return null; } try { return Long.valueOf(plc.readUInt32(strokeAddr)); } catch (Exception e) { markDisconnectedAndResetBackoff(); return null; } } private String readFloatText(String addr) { if (isBlank(addr) || plc == null) { return ""; } return fmtFloat(plc.readFloat32(addr.trim())); } private boolean ensurePlc() { if (isConnected()) { return true; } connect(); return isConnected(); } 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(); } private static String nvl(String s) { return s == null ? "" : s.trim(); } 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; } }