80 lines
3.1 KiB
Java
80 lines
3.1 KiB
Java
package com.ruoyi.mill.protocol;
|
||
|
||
import java.util.Collections;
|
||
import java.util.LinkedHashMap;
|
||
import java.util.Map;
|
||
|
||
/**
|
||
* 新协议字段定义
|
||
* 报文格式:[4字节LE ID][4字节LE 数据长度][数据体]
|
||
* 数据体:每个字段小端存储
|
||
*/
|
||
public class MillDataField {
|
||
|
||
public enum DataType {
|
||
I4, // 4字节有符号整数(小端)
|
||
I2, // 2字节有符号整数(小端)
|
||
F4 // 4字节IEEE-754单精度浮点(小端)
|
||
}
|
||
|
||
private final String name;
|
||
private final String description;
|
||
private final String unit;
|
||
private final DataType type;
|
||
// I4类型可含位字段:index→bitName,index→bitDescription
|
||
private final Map<Integer, String> bitNames;
|
||
private final Map<Integer, String> bitDescriptions;
|
||
|
||
private MillDataField(String name, String description, String unit, DataType type,
|
||
Map<Integer, String> bitNames, Map<Integer, String> bitDescriptions) {
|
||
this.name = name;
|
||
this.description = description;
|
||
this.unit = unit;
|
||
this.type = type;
|
||
this.bitNames = bitNames != null ? Collections.unmodifiableMap(bitNames) : Collections.emptyMap();
|
||
this.bitDescriptions = bitDescriptions != null ? Collections.unmodifiableMap(bitDescriptions) : Collections.emptyMap();
|
||
}
|
||
|
||
public static MillDataField i4(String name, String description, String unit) {
|
||
return new MillDataField(name, description, unit, DataType.I4, null, null);
|
||
}
|
||
|
||
public static MillDataField i4WithBits(String name, String description,
|
||
Map<Integer, String> bitNames,
|
||
Map<Integer, String> bitDescriptions) {
|
||
return new MillDataField(name, description, "", DataType.I4, bitNames, bitDescriptions);
|
||
}
|
||
|
||
public static MillDataField i2(String name, String description, String unit) {
|
||
return new MillDataField(name, description, unit, DataType.I2, null, null);
|
||
}
|
||
|
||
public static MillDataField f4(String name, String description, String unit) {
|
||
return new MillDataField(name, description, unit, DataType.F4, null, null);
|
||
}
|
||
|
||
public int byteLength() {
|
||
return type == DataType.I2 ? 2 : 4;
|
||
}
|
||
|
||
public boolean hasBits() {
|
||
return !bitNames.isEmpty();
|
||
}
|
||
|
||
public String getName() { return name; }
|
||
public String getDescription() { return description; }
|
||
public String getUnit() { return unit; }
|
||
public DataType getType() { return type; }
|
||
public Map<Integer, String> getBitNames() { return bitNames; }
|
||
public Map<Integer, String> getBitDescriptions() { return bitDescriptions; }
|
||
|
||
/** 构建位字段Map的便捷方法 */
|
||
public static Map<Integer, String> bits(Object... indexAndName) {
|
||
Map<Integer, String> map = new LinkedHashMap<>();
|
||
for (int i = 0; i + 1 < indexAndName.length; i += 2) {
|
||
map.put((Integer) indexAndName[i], (String) indexAndName[i + 1]);
|
||
}
|
||
return map;
|
||
}
|
||
}
|