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);
|
}
|
}
|