package com.zy.acs.charge.protocol; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @Component @Slf4j public class ModbusConnectionManager { @Autowired private ModbusAdapter modbusAdapter; @Value("${charger.modbus.retry.max-attempts:3}") private int maxRetry; @Value("${charger.modbus.retry.initial-delay:1000}") private long initialDelay; @PostConstruct public void startAsyncConnect() { // 启动异步线程尝试连接 new Thread(() -> { for (int i = 0; i < maxRetry; i++) { try { modbusAdapter.connect(); log.info("Modbus connection established after {} attempts", i + 1); // 可选:启动心跳 startHeartbeat(); return; } catch (Exception e) { log.warn("Modbus connection attempt {} failed: {}", i + 1, e.getMessage()); if (i < maxRetry - 1) { try { Thread.sleep(initialDelay); } catch (InterruptedException ignored) { } } } } log.error("Failed to connect to Modbus charger after {} attempts", maxRetry); }).start(); } private void startHeartbeat() { // 实现心跳 } }