huang
16 小时以前 9c489617b002e71859597097c9d1d2f1b9fc0e56
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
package com.mes.plc.client.impl;
 
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mes.connect.modbus.ModbusTcpClient;
import com.mes.device.entity.DeviceConfig;
import com.mes.device.util.ConfigJsonHelper;
import com.mes.plc.client.PlcClient;
import lombok.extern.slf4j.Slf4j;
 
import java.io.IOException;
import java.util.*;
 
/**
 * 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;
 
    // 设备配置
    private final DeviceConfig device;
 
    // Modbus客户端实例
    private ModbusTcpClient modbusClient;
 
    // 连接状态
    private boolean connected = false;
 
    // 超时时间(毫秒)
    private int timeout = 5000;
 
    // ObjectMapper用于JSON解析
    private final ObjectMapper objectMapper = new ObjectMapper();
 
    // 地址映射缓存:字段名 -> Modbus地址
    private Map<String, String> addressMappingCache;
 
    /**
     * 构造函数
     *
     * @param device 设备配置
     */
    public ModbusPlcClient(DeviceConfig device) {
        this.device = 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;
 
        // 初始化地址映射
        this.addressMappingCache = loadAddressMapping();
    }
 
    /**
     * 解析设备的extraParams
     *
     * @param extraParamsJson extraParams的JSON字符串
     * @return 解析后的Map
     */
    private Map<String, Object> parseExtraParams(String extraParamsJson) {
        if (extraParamsJson == null || extraParamsJson.isEmpty()) {
            return new HashMap<>();
        }
 
        try {
            TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {};
            return objectMapper.readValue(extraParamsJson, typeRef);
        } catch (Exception e) {
            log.error("解析extraParams失败: {}", extraParamsJson, e);
            return new HashMap<>();
        }
    }
 
    /**
     * 加载地址映射配置(从configJson或extraParams.addressMapping)
     *
     * @return 字段名 -> Modbus地址的映射
     */
    private Map<String, String> loadAddressMapping() {
        Map<String, String> mapping = new HashMap<>();
 
        try {
            // 1. 优先从configJson获取
            Map<String, Object> configParams = ConfigJsonHelper.parseToMap(device.getConfigJson(), objectMapper);
            if (!configParams.isEmpty()) {
                for (Map.Entry<String, Object> entry : configParams.entrySet()) {
                    String fieldName = entry.getKey();
                    Object addressObj = entry.getValue();
                    if (addressObj != null) {
                        mapping.put(fieldName, String.valueOf(addressObj));
                    }
                }
                if (!mapping.isEmpty()) {
                    log.info("从configJson加载Modbus地址映射成功: deviceId={}, count={}", device.getId(), mapping.size());
                    return mapping;
                }
            }
 
            // 2. 从extraParams.addressMapping获取
            Map<String, Object> extraParams = parseExtraParams(device.getExtraParams());
            Object addressMappingObj = extraParams.get("addressMapping");
            if (addressMappingObj != null) {
                if (addressMappingObj instanceof Map) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> addrMap = (Map<String, Object>) addressMappingObj;
                    for (Map.Entry<String, Object> entry : addrMap.entrySet()) {
                        mapping.put(entry.getKey(), String.valueOf(entry.getValue()));
                    }
                } else if (addressMappingObj instanceof String) {
                    // 如果是JSON字符串,解析它
                    TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {};
                    Map<String, Object> addrMap = objectMapper.readValue((String) addressMappingObj, typeRef);
                    for (Map.Entry<String, Object> entry : addrMap.entrySet()) {
                        mapping.put(entry.getKey(), String.valueOf(entry.getValue()));
                    }
                }
                if (!mapping.isEmpty()) {
                    log.info("从extraParams.addressMapping加载Modbus地址映射成功: deviceId={}, count={}", device.getId(), mapping.size());
                    return mapping;
                }
            }
 
            log.warn("未找到Modbus地址映射配置: deviceId={}", device.getId());
        } catch (Exception e) {
            log.error("加载Modbus地址映射失败: deviceId={}", device.getId(), e);
        }
 
        return mapping;
    }
 
    /**
     * 获取字段对应的Modbus地址
     *
     * @param fieldName 字段名
     * @return Modbus地址(格式:功能码.寄存器地址,如 "3.40001")
     */
    private String getModbusAddress(String fieldName) {
        String address = addressMappingCache.get(fieldName);
        if (address == null || address.isEmpty()) {
            log.warn("字段 {} 未找到Modbus地址映射: deviceId={}", fieldName, device.getId());
            return null;
        }
        return address;
    }
 
    /**
     * 推断数据类型(根据字段名或值)
     */
    private String inferDataType(String fieldName, Object value) {
        if (value == null) {
            // 根据字段名推断
            String lowerName = fieldName.toLowerCase();
            if (lowerName.contains("float") || lowerName.contains("real")) {
                return "float";
            } else if (lowerName.contains("string") || lowerName.contains("str") || lowerName.contains("id")) {
                return "string";
            }
            return "int"; // 默认int
        }
 
        // 根据值类型推断
        if (value instanceof Float || value instanceof Double) {
            return "float";
        } else if (value instanceof String) {
            return "string";
        } else if (value instanceof Number) {
            return "int";
        }
        return "int";
    }
 
    @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 {
            if (addressMappingCache.isEmpty()) {
                log.warn("Modbus地址映射为空,无法读取所有数据: deviceId={}", device.getId());
                return Collections.emptyMap();
            }
 
            // 读取所有配置的字段
            Map<String, Object> result = new HashMap<>();
            for (String fieldName : addressMappingCache.keySet()) {
                try {
                    Object value = readFieldValue(fieldName);
                    if (value != null) {
                        result.put(fieldName, value);
                    }
                } catch (Exception e) {
                    log.warn("读取字段失败: fieldName={}, deviceId={}, error={}", fieldName, device.getId(), e.getMessage());
                }
            }
 
            log.info("Modbus读取所有数据成功: deviceId={}, fieldCount={}", device.getId(), result.size());
            return result;
        } 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();
        }
 
        if (fields == null || fields.length == 0) {
            return readAllData();
        }
 
        try {
            Map<String, Object> result = new HashMap<>();
            for (String fieldName : fields) {
                if (fieldName == null || fieldName.isEmpty()) {
                    continue;
                }
                try {
                    Object value = readFieldValue(fieldName);
                    if (value != null) {
                        result.put(fieldName, value);
                    }
                } catch (Exception e) {
                    log.warn("读取字段失败: fieldName={}, deviceId={}, error={}", fieldName, device.getId(), e.getMessage());
                }
            }
 
            log.info("Modbus读取指定字段数据成功: deviceId={}, fields={}, resultCount={}",
                    device.getId(), Arrays.toString(fields), result.size());
            return result;
        } catch (Exception e) {
            log.error("Modbus PLC读取数据失败: {}:{}", this.plcIp, this.plcPort, e);
            this.connected = false;
            return Collections.emptyMap();
        }
    }
 
    /**
     * 读取单个字段的值
     */
    private Object readFieldValue(String fieldName) throws IOException {
        String address = getModbusAddress(fieldName);
        if (address == null) {
            return null;
        }
 
        // 根据字段名推断数据类型(优先从配置中获取)
        String dataType = inferDataType(fieldName, null);
 
        // 从extraParams中获取字段的数据类型配置
        Map<String, Object> extraParams = parseExtraParams(device.getExtraParams());
        @SuppressWarnings("unchecked")
        Map<String, Object> fieldConfigs = (Map<String, Object>) extraParams.get("fieldConfigs");
        if (fieldConfigs != null) {
            @SuppressWarnings("unchecked")
            Map<String, Object> fieldConfig = (Map<String, Object>) fieldConfigs.get(fieldName);
            if (fieldConfig != null && fieldConfig.get("dataType") != null) {
                dataType = String.valueOf(fieldConfig.get("dataType"));
            }
        }
 
        // 根据数据类型读取
        switch (dataType.toLowerCase()) {
            case "float":
            case "real":
                return modbusClient.readFloat(address);
            case "string":
            case "str":
                // 字符串需要指定长度,默认32字符
                int stringLength = 32;
                if (fieldConfigs != null) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> fieldConfig = (Map<String, Object>) fieldConfigs.get(fieldName);
                    if (fieldConfig != null && fieldConfig.get("length") != null) {
                        stringLength = ((Number) fieldConfig.get("length")).intValue();
                    }
                }
                return modbusClient.readString(address, stringLength);
            case "int":
            case "integer":
            case "word":
            default:
                return modbusClient.readRegister(address);
        }
    }
 
    @Override
    public boolean writeData(Map<String, Object> data) {
        if (!isConnected() && !connect()) {
            log.error("Modbus PLC未连接,无法写入数据: {}:{}", this.plcIp, this.plcPort);
            return false;
        }
 
        if (data == null || data.isEmpty()) {
            log.warn("写入数据为空,跳过操作: deviceId={}", device.getId());
            return true;
        }
 
        try {
            int successCount = 0;
            int failCount = 0;
 
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                String fieldName = entry.getKey();
                Object value = entry.getValue();
 
                if (value == null) {
                    continue; // 跳过null值
                }
 
                try {
                    writeFieldValue(fieldName, value);
                    successCount++;
                } catch (Exception e) {
                    log.error("写入字段失败: fieldName={}, value={}, deviceId={}, error={}",
                            fieldName, value, device.getId(), e.getMessage());
                    failCount++;
                }
            }
 
            if (failCount > 0) {
                log.warn("Modbus写入数据部分失败: deviceId={}, success={}, fail={}",
                        device.getId(), successCount, failCount);
                return false;
            }
 
            log.info("Modbus写入数据成功: deviceId={}, fieldCount={}", device.getId(), successCount);
            return true;
        } catch (Exception e) {
            log.error("Modbus PLC写入数据失败: {}:{}", this.plcIp, this.plcPort, e);
            this.connected = false;
            return false;
        }
    }
 
    /**
     * 写入单个字段的值
     */
    private void writeFieldValue(String fieldName, Object value) throws IOException {
        String address = getModbusAddress(fieldName);
        if (address == null) {
            throw new IllegalArgumentException("字段 " + fieldName + " 未找到Modbus地址映射");
        }
 
        // 根据值类型推断数据类型
        String dataType = inferDataType(fieldName, value);
 
        // 从extraParams中获取字段的数据类型配置
        Map<String, Object> extraParams = parseExtraParams(device.getExtraParams());
        @SuppressWarnings("unchecked")
        Map<String, Object> fieldConfigs = (Map<String, Object>) extraParams.get("fieldConfigs");
        if (fieldConfigs != null) {
            @SuppressWarnings("unchecked")
            Map<String, Object> fieldConfig = (Map<String, Object>) fieldConfigs.get(fieldName);
            if (fieldConfig != null && fieldConfig.get("dataType") != null) {
                dataType = String.valueOf(fieldConfig.get("dataType"));
            }
        }
 
        // 根据数据类型写入
        switch (dataType.toLowerCase()) {
            case "float":
            case "real":
                float floatValue;
                if (value instanceof Number) {
                    floatValue = ((Number) value).floatValue();
                } else {
                    floatValue = Float.parseFloat(String.valueOf(value));
                }
                modbusClient.writeFloat(address, floatValue);
                break;
            case "string":
            case "str":
                String stringValue = String.valueOf(value);
                modbusClient.writeString(address, stringValue);
                break;
            case "int":
            case "integer":
            case "word":
            default:
                int intValue;
                if (value instanceof Number) {
                    intValue = ((Number) value).intValue();
                } else {
                    intValue = Integer.parseInt(String.valueOf(value));
                }
                modbusClient.writeRegister(address, intValue);
                break;
        }
    }
 
    @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;
    }
}