zhang
17 小时以前 08ebc631c8b5775146cfd1709a28dab4a54c4b77
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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() {
        // 实现心跳
    }
 
}