严智鑫
2025-06-13 d14cdaf28222bfef468185e34de7c823f1436b19
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
package com.mes.connect.addressParser;
 
import com.mes.connect.IndustrialInterface.AddressParser;
import com.mes.connect.protocol.ProtocolAddress;
import com.mes.connect.protocol.ProtocolType;
 
/**
 * Modbus地址解析器
 */
public class ModbusAddressParser implements AddressParser {
    @Override
    public ProtocolAddress parse(String address) {
        // 格式示例: "MB.4x0001" 或 "MB.0x100.2"
        if (!address.startsWith("MB.")) {
            throw new IllegalArgumentException("Invalid Modbus address format: " + address);
        }
        
        String[] parts = address.substring(3).split("\\.");
        
        if (parts.length < 1) {
            throw new IllegalArgumentException("Invalid Modbus address format: " + address);
        }
        
        // 解析区域
        String areaStr = parts[0];
        int functionCode;
        
        if (areaStr.startsWith("0x")) {
            functionCode = 1; // 1读线圈 5写单个线圈
        } else if (areaStr.startsWith("1x")) {
            functionCode = 2; // 读离散输入
        } else if (areaStr.startsWith("3x")) {
            functionCode = 4; // 读输入寄存器
        } else if (areaStr.startsWith("4x")) {
            functionCode = 3; // 读保持寄存器
        } else {
            throw new IllegalArgumentException("Invalid Modbus area: " + areaStr);
        }
        
        // 解析地址
        int addressValue = Integer.parseInt(areaStr.substring(2));
        if (functionCode == 3 || functionCode == 4) {
            addressValue--; // Modbus保持寄存器和输入寄存器地址从0开始
        }
        
        // 解析位地址(如果有)
        int bit = 0;
        if (parts.length > 1) {
            bit = Integer.parseInt(parts[1]);
        }
        
        return new ProtocolAddress(ProtocolType.MODBUS_TCP, functionCode, 0, addressValue, bit);
    }
}