package com.mes.connect.addressParser; import com.mes.connect.IndustrialInterface.AddressParser; import com.mes.connect.protocol.ProtocolAddress; import com.mes.connect.protocol.ProtocolType; /** * S7地址解析器 */ public class S7AddressParser implements AddressParser { @Override public ProtocolAddress parse(String address) { // 格式示例: "S7.DB1.DBX10.2" 或 "S7.M100" //位地址:S7.DB1.DBX0.0 (DB1 块中的字节 0 的位 0) //字节地址:S7.DB1.DBB0 (DB1 块中的字节 0) //字地址:S7.DB1.DBW0 (DB1 块中的字 0) //双字地址:S7.DB1.DBD0 (DB1 块中的双字 0) if (!address.startsWith("S7.")) { throw new IllegalArgumentException("Invalid S7 address format: " + address); } String[] parts = address.substring(3).split("\\."); if (parts.length < 2) { throw new IllegalArgumentException("Invalid S7 address format: " + address); } // 解析DB号 int dbNumber = 0; int area = 0x84; // 默认DB区域 if (parts[0].startsWith("DB")) { dbNumber = Integer.parseInt(parts[0].substring(2)); } else if (parts[0].equals("I")) { area = 0x81; // 输入区域 } else if (parts[0].equals("Q")) { area = 0x82; // 输出区域 } else if (parts[0].equals("M")) { area = 0x83; // 内存区域 } else { throw new IllegalArgumentException("Invalid S7 area: " + parts[0]); } // 解析地址类型和地址值 String addressPart = parts[1]; int addressValue = 0; int bit = 0; if (area == 0x84) { // DB区域 if (addressPart.startsWith("DBX")) { // 位地址 String[] bitParts = addressPart.substring(3).split("\\."); addressValue = Integer.parseInt(bitParts[0]); if (bitParts.length > 1) { bit = Integer.parseInt(bitParts[1]); } } else if (addressPart.startsWith("DBW")) { // 字地址 addressValue = Integer.parseInt(addressPart.substring(3)); } else if (addressPart.startsWith("DBD")) { // 双字地址 addressValue = Integer.parseInt(addressPart.substring(3)); } else { throw new IllegalArgumentException("Invalid S7 DB address type: " + addressPart); } } else { // I/Q/M区域 if (addressPart.startsWith("X")) { // 位地址 String[] bitParts = addressPart.substring(1).split("\\."); addressValue = Integer.parseInt(bitParts[0]); if (bitParts.length > 1) { bit = Integer.parseInt(bitParts[1]); } } else { // 字地址 addressValue = Integer.parseInt(addressPart); } } return new ProtocolAddress(ProtocolType.S7, area, dbNumber, addressValue, bit); } }