huang
2 天以前 14763d895151f3ddad09906f2233057b8b967881
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package com.mes.plc.client.impl;
 
import com.mes.connect.modbus.ModbusTcpClient;
import com.mes.device.entity.DeviceConfig;
import com.mes.plc.client.PlcClient;
import lombok.extern.slf4j.Slf4j;
 
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
 
/**
 * Modbus协议PLC客户端实现
 * <p>
 * 基于项目中已有的Modbus实现
 * </p>
 *
 * @author huang
 * @date 2025/12/19
 */
@Slf4j
public class ModbusPlcClient implements PlcClient {
    
    // PLC IP地址
    private final String plcIp;
    
    // PLC端口
    private final int plcPort;
    
    // 从站地址
    private final int unitId;
    
    // Modbus客户端实例
    private ModbusTcpClient modbusClient;
    
    // 连接状态
    private boolean connected = false;
    
    // 超时时间(毫秒)
    private int timeout = 5000;
    
    /**
     * 构造函数
     *
     * @param device 设备配置
     */
    public ModbusPlcClient(DeviceConfig device) {
        this.plcIp = device.getPlcIp();
        this.plcPort = device.getPlcPort() != null ? device.getPlcPort() : 502;
        
        // 从配置中获取从站地址,默认1
        int unitIdValue = 1;
        try {
            Map<String, Object> extraParams = parseExtraParams(device.getExtraParams());
            if (extraParams != null) {
                Object unitIdObj = extraParams.get("unitId");
                if (unitIdObj instanceof Number) {
                    unitIdValue = ((Number) unitIdObj).intValue();
                } else if (unitIdObj instanceof String) {
                    unitIdValue = Integer.parseInt((String) unitIdObj);
                }
            }
        } catch (Exception e) {
            log.warn("解析unitId失败,使用默认值1: deviceId={}", device.getId(), e);
        }
        this.unitId = unitIdValue;
    }
    
    /**
     * 解析设备的extraParams
     *
     * @param extraParamsJson extraParams的JSON字符串
     * @return 解析后的Map
     */
    private Map<String, Object> parseExtraParams(String extraParamsJson) {
        if (extraParamsJson == null || extraParamsJson.isEmpty()) {
            return null;
        }
        
        try {
            // 这里简化处理,实际项目中应该使用Jackson或Gson解析
            // 由于项目中已有ObjectMapper,这里暂时返回空Map,后续完善
            return new HashMap<>();
        } catch (Exception e) {
            log.error("解析extraParams失败: {}", extraParamsJson, e);
            return null;
        }
    }
    
    @Override
    public boolean connect() {
        try {
            if (modbusClient != null && isConnected()) {
                return true;
            }
            
            // 创建Modbus客户端实例
            this.modbusClient = new ModbusTcpClient(this.plcIp, this.plcPort, this.unitId);
            
            // 连接PLC
            this.modbusClient.connect();
            this.connected = true;
            log.info("Modbus PLC连接成功: {}:{},从站地址: {}", this.plcIp, this.plcPort, this.unitId);
            return true;
        } catch (Exception e) {
            log.error("Modbus PLC连接失败: {}:{}", this.plcIp, this.plcPort, e);
            this.connected = false;
            return false;
        }
    }
    
    @Override
    public void disconnect() {
        try {
            if (this.modbusClient != null) {
                this.modbusClient.disconnect();
                log.info("Modbus PLC断开连接: {}:{}", this.plcIp, this.plcPort);
            }
        } catch (Exception e) {
            log.error("Modbus PLC断开连接失败: {}:{}", this.plcIp, this.plcPort, e);
        } finally {
            this.connected = false;
            this.modbusClient = null;
        }
    }
    
    @Override
    public Map<String, Object> readAllData() {
        if (!isConnected() && !connect()) {
            log.error("Modbus PLC未连接,无法读取数据: {}:{}", this.plcIp, this.plcPort);
            return Collections.emptyMap();
        }
        
        try {
            // TODO: 实现Modbus读取所有数据
            // 这里暂时返回空Map,后续完善
            log.warn("Modbus readAllData未实现,返回空Map");
            return new HashMap<>();
        } catch (Exception e) {
            log.error("Modbus PLC读取所有数据失败: {}:{}", this.plcIp, this.plcPort, e);
            this.connected = false;
            return Collections.emptyMap();
        }
    }
    
    @Override
    public Map<String, Object> readData(String... fields) {
        if (!isConnected() && !connect()) {
            log.error("Modbus PLC未连接,无法读取数据: {}:{}", this.plcIp, this.plcPort);
            return Collections.emptyMap();
        }
        
        try {
            // TODO: 实现Modbus读取指定字段数据
            // 这里暂时返回空Map,后续完善
            log.warn("Modbus readData未实现,返回空Map");
            return new HashMap<>();
        } catch (Exception e) {
            log.error("Modbus PLC读取数据失败: {}:{}", this.plcIp, this.plcPort, e);
            this.connected = false;
            return Collections.emptyMap();
        }
    }
    
    @Override
    public boolean writeData(Map<String, Object> data) {
        if (!isConnected() && !connect()) {
            log.error("Modbus PLC未连接,无法写入数据: {}:{}", this.plcIp, this.plcPort);
            return false;
        }
        
        try {
            // TODO: 实现Modbus写入数据
            // 这里暂时返回true,后续完善
            log.warn("Modbus writeData未实现,返回成功");
            return true;
        } catch (Exception e) {
            log.error("Modbus PLC写入数据失败: {}:{}", this.plcIp, this.plcPort, e);
            this.connected = false;
            return false;
        }
    }
    
    @Override
    public boolean isConnected() {
        try {
            if (!this.connected || this.modbusClient == null) {
                return false;
            }
            // 检查连接状态
            return this.modbusClient.isConnected();
        } catch (Exception e) {
            this.connected = false;
            return false;
        }
    }
    
    @Override
    public String getPlcType() {
        return "MODBUS";
    }
    
    @Override
    public int getTimeout() {
        return this.timeout;
    }
    
    @Override
    public void setTimeout(int timeout) {
        this.timeout = timeout;
        // ModbusTcpClient不支持直接设置超时,这里仅记录超时时间
    }
}