udp调试页面的完全适配

This commit is contained in:
2026-05-15 14:27:49 +08:00
parent e998261002
commit da2620f17d
11 changed files with 1773 additions and 28 deletions

View File

@@ -0,0 +1,261 @@
package com.ruoyi.mill.controller;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.mill.protocol.MillDataCodec;
import com.ruoyi.mill.protocol.MillDataField;
import com.ruoyi.mill.protocol.MillDataSchema;
import com.ruoyi.mill.udp.MillDataRecord;
import com.ruoyi.mill.udp.MillDataStore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.*;
/**
* 新协议报文调试控制器
* 帧格式:[4字节LE ID][4字节LE 数据体长度][数据体]
*/
@Api(tags = "轧线 - 新协议报文调试")
@RestController
@RequestMapping("/mill/data")
public class MillDataController extends BaseController {
private static final Logger log = LoggerFactory.getLogger(MillDataController.class);
@Autowired
private MillDataStore millDataStore;
// ── Schema 查询 ────────────────────────────────────────────────────
@ApiOperation("获取所有报文Schema定义")
@GetMapping("/schemas")
public AjaxResult getSchemas() {
Map<String, Object> result = new LinkedHashMap<>();
Map<Integer, String> descs = MillDataSchema.getIdDescriptions();
List<Map<String, Object>> schemaList = new ArrayList<>();
for (Map.Entry<Integer, List<MillDataField>> entry : MillDataSchema.getAllSchemas().entrySet()) {
int id = entry.getKey();
List<MillDataField> schema = entry.getValue();
Map<String, Object> item = new LinkedHashMap<>();
item.put("id", id);
item.put("description", descs.getOrDefault(id, ""));
item.put("totalBytes", schema.stream().mapToInt(MillDataField::byteLength).sum());
List<Map<String, Object>> fields = new ArrayList<>();
for (MillDataField f : schema) {
Map<String, Object> fd = new LinkedHashMap<>();
fd.put("name", f.getName());
fd.put("description", f.getDescription());
fd.put("unit", f.getUnit());
fd.put("type", f.getType().name());
fd.put("byteLength", f.byteLength());
if (f.hasBits()) {
List<Map<String, Object>> bits = new ArrayList<>();
for (Map.Entry<Integer, String> be : f.getBitNames().entrySet()) {
Map<String, Object> bit = new LinkedHashMap<>();
bit.put("index", be.getKey());
bit.put("name", be.getValue());
bit.put("description", f.getBitDescriptions().getOrDefault(be.getKey(), ""));
bits.add(bit);
}
fd.put("bits", bits);
}
fields.add(fd);
}
item.put("fields", fields);
schemaList.add(item);
}
result.put("schemas", schemaList);
return success(result);
}
// ── 发送 ──────────────────────────────────────────────────────────
@ApiOperation("发送新协议报文到指定IP:Port")
@PostMapping("/send")
public AjaxResult send(@RequestBody Map<String, Object> req) {
try {
// 目标地址
String host = (String) req.get("host");
Object portObj = req.get("port");
if (host == null || host.isEmpty()) return error("host不能为空");
if (portObj == null) return error("port不能为空");
int port = ((Number) portObj).intValue();
// 报文ID
Object idObj = req.get("id");
if (idObj == null) return error("id不能为空");
int id = ((Number) idObj).intValue();
List<MillDataField> schema = MillDataSchema.getSchema(id);
if (schema == null) return error("未知报文ID: " + id);
// 字段值
@SuppressWarnings("unchecked")
Map<String, Object> values = req.containsKey("fields")
? (Map<String, Object>) req.get("fields")
: Collections.emptyMap();
byte[] frame = MillDataCodec.encodePacket(id, schema, values);
// UDP发送
boolean ok = udpSend(host, port, frame);
// 解码已发送的数据体用于记录
byte[] body = Arrays.copyOfRange(frame, 8, frame.length);
Map<String, Object> decoded = MillDataCodec.decodeBody(schema, body);
millDataStore.addOutbound(id, frame, decoded, ok, host, port);
if (ok) {
log.info("[MILL-DATA] 发送成功 id={} -> {}:{} frameLen={}", id, host, port, frame.length);
Map<String, Object> resp = new LinkedHashMap<>();
resp.put("frameLength", frame.length);
resp.put("dataLength", frame.length - 8);
resp.put("hexPreview", MillDataCodec.toHexString(Arrays.copyOf(frame, Math.min(frame.length, 32))));
return success(resp);
} else {
return error("UDP发送失败");
}
} catch (Exception e) {
log.error("[MILL-DATA] 发送异常", e);
return error("发送异常: " + e.getMessage());
}
}
@ApiOperation("发送原始Hex报文到指定IP:Port")
@PostMapping("/sendRaw")
public AjaxResult sendRaw(@RequestBody Map<String, Object> req) {
try {
String host = (String) req.get("host");
Object portObj = req.get("port");
String hexStr = (String) req.get("hex");
if (host == null || host.isEmpty()) return error("host不能为空");
if (portObj == null) return error("port不能为空");
if (hexStr == null || hexStr.isEmpty()) return error("hex不能为空");
int port = ((Number) portObj).intValue();
hexStr = hexStr.replaceAll("[\\s\\-]", "");
if (hexStr.length() % 2 != 0) return error("hex字符串长度必须为偶数");
byte[] frame = new byte[hexStr.length() / 2];
for (int i = 0; i < frame.length; i++) {
frame[i] = (byte) Integer.parseInt(hexStr.substring(i * 2, i * 2 + 2), 16);
}
int packetId = MillDataCodec.peekId(frame);
List<MillDataField> schema = MillDataSchema.getSchema(packetId);
boolean ok = udpSend(host, port, frame);
Map<String, Object> decoded = null;
if (schema != null && frame.length >= 8) {
byte[] body = Arrays.copyOfRange(frame, 8, frame.length);
decoded = MillDataCodec.decodeBody(schema, body);
}
millDataStore.addOutbound(packetId, frame, decoded, ok, host, port);
if (ok) {
Map<String, Object> r = new LinkedHashMap<>();
r.put("frameLength", frame.length);
return success(r);
} else {
return error("UDP发送失败");
}
} catch (Exception e) {
log.error("[MILL-DATA] 原始发送异常", e);
return error("发送异常: " + e.getMessage());
}
}
// ── 解析 ──────────────────────────────────────────────────────────
@ApiOperation("解析Hex字节为字段值")
@PostMapping("/parse")
public AjaxResult parse(@RequestBody Map<String, Object> req) {
try {
String hexStr = (String) req.get("hex");
if (hexStr == null || hexStr.isEmpty()) return error("hex不能为空");
hexStr = hexStr.replaceAll("[\\s\\-]", "");
byte[] data = new byte[hexStr.length() / 2];
for (int i = 0; i < data.length; i++) {
data[i] = (byte) Integer.parseInt(hexStr.substring(i * 2, i * 2 + 2), 16);
}
Map<String, Object> result = MillDataCodec.decodePacket(data, MillDataSchema.getAllSchemas());
// 将rawBody转为hex展示
byte[] rawBody = (byte[]) result.get("rawBody");
if (rawBody != null) {
result.put("rawBodyHex", MillDataCodec.toHexString(rawBody));
result.remove("rawBody");
}
return success(result);
} catch (Exception e) {
log.error("[MILL-DATA] 解析异常", e);
return error("解析异常: " + e.getMessage());
}
}
// ── 历史记录 ──────────────────────────────────────────────────────
@ApiOperation("获取报文历史记录")
@GetMapping("/history")
public AjaxResult history(
@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "50") Integer pageSize) {
List<MillDataRecord> rows = millDataStore.getHistory(pageNum, pageSize);
Map<String, Object> result = new LinkedHashMap<>();
result.put("rows", rows);
result.put("total", millDataStore.getTotalCount());
return success(result);
}
@ApiOperation("获取统计信息")
@GetMapping("/stats")
public AjaxResult stats() {
Map<String, Object> stats = new LinkedHashMap<>();
int total = millDataStore.getTotalCount();
long success = millDataStore.countSuccess();
stats.put("total", total);
stats.put("inbound", millDataStore.countInbound());
stats.put("outbound", millDataStore.countOutbound());
stats.put("successRate", total > 0 ? Math.round(success * 100.0 / total) : 100);
return success(stats);
}
@ApiOperation("清空历史记录")
@DeleteMapping("/history")
public AjaxResult clearHistory() {
millDataStore.clear();
return success();
}
// ── 内部工具 ──────────────────────────────────────────────────────
private boolean udpSend(String host, int port, byte[] data) {
try (DatagramSocket socket = new DatagramSocket()) {
socket.setSoTimeout(3000);
InetAddress addr = InetAddress.getByName(host);
DatagramPacket pkt = new DatagramPacket(data, data.length, addr, port);
socket.send(pkt);
return true;
} catch (Exception e) {
log.warn("[MILL-DATA] UDP发送失败 {}:{} : {}", host, port, e.getMessage());
return false;
}
}
}

View File

@@ -0,0 +1,178 @@
package com.ruoyi.mill.protocol;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.*;
/**
* 新协议编解码器
*
* 帧格式:
* [4字节 LITTLE_ENDIAN] ID (uint32)
* [4字节 LITTLE_ENDIAN] 数据体字节数 (uint32)
* [N字节] 数据体
*
* 数据体字段编码规则(全部小端存储):
* I4 → 4字节有符号整数
* I2 → 2字节有符号整数
* F4 → 4字节 IEEE-754 单精度浮点
* 位字段从所属 I4 字段中按位提取bit0 = LSB
*/
public final class MillDataCodec {
private MillDataCodec() {}
// ── 编码 ──────────────────────────────────────────────────────────
/**
* 编码完整报文含8字节头
*/
public static byte[] encodePacket(int id, List<MillDataField> schema, Map<String, Object> values) {
byte[] body = encodeBody(schema, values);
ByteBuffer buf = ByteBuffer.allocate(8 + body.length).order(ByteOrder.LITTLE_ENDIAN);
buf.putInt(id);
buf.putInt(body.length);
buf.put(body);
return buf.array();
}
/**
* 仅编码数据体(不含头)
*/
public static byte[] encodeBody(List<MillDataField> schema, Map<String, Object> values) {
int totalLen = schema.stream().mapToInt(MillDataField::byteLength).sum();
ByteBuffer buf = ByteBuffer.allocate(totalLen).order(ByteOrder.LITTLE_ENDIAN);
for (MillDataField field : schema) {
switch (field.getType()) {
case I4: {
int intVal;
if (field.hasBits()) {
intVal = 0;
for (Map.Entry<Integer, String> e : field.getBitNames().entrySet()) {
Object bitVal = values.get(e.getValue());
if (isTruthy(bitVal)) {
intVal |= (1 << e.getKey());
}
}
// 如果也直接提供了整数值,以整数值为准
Object raw = values.get(field.getName());
if (raw instanceof Number) intVal = ((Number) raw).intValue();
} else {
Object raw = values.getOrDefault(field.getName(), 0);
intVal = raw instanceof Number ? ((Number) raw).intValue() : 0;
}
buf.putInt(intVal);
break;
}
case I2: {
Object raw = values.getOrDefault(field.getName(), 0);
short shortVal = raw instanceof Number ? ((Number) raw).shortValue() : 0;
buf.putShort(shortVal);
break;
}
case F4: {
Object raw = values.getOrDefault(field.getName(), 0f);
float floatVal = raw instanceof Number ? ((Number) raw).floatValue() : 0f;
buf.putFloat(floatVal);
break;
}
}
}
return buf.array();
}
// ── 解码 ──────────────────────────────────────────────────────────
/**
* 解码完整报文,返回头信息 + 字段值Map
* @return id→packetId, dataLength→body字节数, fields→字段Map
*/
public static Map<String, Object> decodePacket(byte[] data, Map<Integer, List<MillDataField>> schemas) {
Map<String, Object> result = new LinkedHashMap<>();
if (data.length < 8) {
result.put("error", "报文过短至少需要8字节头");
return result;
}
ByteBuffer buf = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);
int id = buf.getInt();
int dataLen = buf.getInt();
result.put("id", id);
result.put("dataLength", dataLen);
int bodyLen = Math.min(dataLen, data.length - 8);
byte[] body = new byte[bodyLen];
buf.get(body);
result.put("rawBody", body);
List<MillDataField> schema = schemas != null ? schemas.get(id) : null;
if (schema != null) {
Map<String, Object> fields = decodeBody(schema, body);
result.put("fields", fields);
result.put("schemaMatched", true);
} else {
result.put("schemaMatched", false);
}
return result;
}
/**
* 仅解码数据体
*/
public static Map<String, Object> decodeBody(List<MillDataField> schema, byte[] body) {
ByteBuffer buf = ByteBuffer.wrap(body).order(ByteOrder.LITTLE_ENDIAN);
Map<String, Object> result = new LinkedHashMap<>();
for (MillDataField field : schema) {
if (buf.remaining() < field.byteLength()) break;
switch (field.getType()) {
case I4: {
int val = buf.getInt();
result.put(field.getName(), val);
if (field.hasBits()) {
for (Map.Entry<Integer, String> e : field.getBitNames().entrySet()) {
result.put(e.getValue(), (val >> e.getKey()) & 1);
}
}
break;
}
case I2: {
result.put(field.getName(), (int) buf.getShort());
break;
}
case F4: {
result.put(field.getName(), buf.getFloat());
break;
}
}
}
return result;
}
// ── 工具方法 ──────────────────────────────────────────────────────
/** 将字节数组转为16进制字符串含空格 */
public static String toHexString(byte[] data) {
if (data == null || data.length == 0) return "";
StringBuilder sb = new StringBuilder(data.length * 3);
for (byte b : data) {
sb.append(String.format("%02X ", b));
}
return sb.toString().trim();
}
/** 读取报文头中的ID前4字节LE不足则返回-1 */
public static int peekId(byte[] data) {
if (data == null || data.length < 4) return -1;
return ByteBuffer.wrap(data, 0, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();
}
private static boolean isTruthy(Object val) {
if (val == null) return false;
if (val instanceof Boolean) return (Boolean) val;
if (val instanceof Number) return ((Number) val).intValue() != 0;
if (val instanceof String) return "1".equals(val) || "true".equalsIgnoreCase((String) val);
return false;
}
}

View File

@@ -0,0 +1,79 @@
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→bitNameindex→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;
}
}

View File

@@ -0,0 +1,155 @@
package com.ruoyi.mill.protocol;
import java.util.*;
import static com.ruoyi.mill.protocol.MillDataField.*;
/**
* 新协议报文 Schema 定义
*
* 报文帧结构:
* [4字节 LE] ID
* [4字节 LE] 数据体长度
* [N字节] 数据体(各字段小端存储)
*
* ID=1202 (0x000004B2)100ms周期发送数据体138字节
* no.1 counter I4 4B offset=0
* no.2 passNo I2 2B offset=4 (道次号)
* no.3 rolledLength F4 4B offset=6 (当前道次轧制长度 m)
* no.4 entryCoilerLen F4 4B offset=10
* no.5 exitCoilerLen F4 4B offset=14
* no.6 millStatus I4 4B offset=18 (含9个位字段 bit0~bit8)
* no.7 entryThick F4 4B offset=22 (入口厚度设定值 mm)
* no.8 entryThickDev F4 4B offset=26 (入口厚度偏差 mm)
* no.9 exitThick F4 4B offset=30
* no.10 exitThickDev F4 4B offset=34
* no.11 topLimit F4 4B offset=38 (偏差上限 %)
* no.12 botLimit F4 4B offset=42 (偏差下限 %)
* no.13 ffSc F4 4B offset=46 (前馈辊缝修正)
* no.14 spare14 F4 4B offset=50 (备用)
* no.15 fbSc F4 4B offset=54 (反馈辊缝修正)
* no.16 mfSc F4 4B offset=58 (秒流量辊缝修正)
* no.17 entryTension F4 4B offset=62 (kN)
* no.18 entryTensionDiff F4 4B offset=66
* no.19 exitTension F4 4B offset=70
* no.20 exitTensionDiff F4 4B offset=74
* no.21 entrySpeed F4 4B offset=78 (m/min)
* no.22 exitSpeed F4 4B offset=82
* no.23 standSpeed F4 4B offset=86
* no.24 rollForce F4 4B offset=90 (kN)
* no.25 rollForceDiff F4 4B offset=94
* no.26 rollgap F4 4B offset=98 (mm)
* no.27 rollgapDiff F4 4B offset=102
* no.28 forwardslip F4 4B offset=106
* no.29 power F4 4B offset=110 (kW)
* no.30 torque F4 4B offset=114 (kNm)
* no.31 irbendMeasure F4 4B offset=118 (kN)
* no.32 irbendReference F4 4B offset=122
* no.33 wrbendMeasure F4 4B offset=126
* no.34 wrbendReference F4 4B offset=130
* no.35 irshift F4 4B offset=134 (mm)
* Total: 138 bytes
*/
public final class MillDataSchema {
private MillDataSchema() {}
public static final int ID_1202 = 1202;
public static final List<MillDataField> SCHEMA_1202 = Collections.unmodifiableList(Arrays.asList(
// no.1
i4("counter", "计数器", "-"),
// no.2 I2 = 2字节
i2("passNo", "道次号", "-"),
// no.3~5
f4("rolledLength", "当前道次轧制长度", "m"),
f4("entryCoilerLen", "入口卷取机长度", "m"),
f4("exitCoilerLen", "出口卷取机长度", "m"),
// no.6 I4含位字段
i4WithBits("millStatus", "轧机状态",
bits(
0, "millDecelerating",
1, "millAccelerating",
2, "entryGaugeMeterHealthy",
3, "exitGaugeMeterHealthy",
4, "entrySpeedMeterHealthy",
5, "exitSpeedMeterHealthy"
),
bits(
0, "轧机减速中",
1, "轧机加速中",
2, "入口测厚仪健康",
3, "出口测厚仪健康",
4, "入口测速仪健康",
5, "出口测速仪健康"
)
),
// no.7~13
f4("entryThick", "入口厚度设定值", "mm"),
f4("entryThickDev", "入口厚度偏差", "mm"),
f4("exitThick", "出口厚度", "mm"),
f4("exitThickDev", "出口厚度偏差", "mm"),
f4("topLimit", "偏差上限", "%"),
f4("botLimit", "偏差下限", "%"),
f4("ffSc", "前馈辊缝修正", ""),
// no.14 备用
f4("spare14", "备用字段14", ""),
// no.15~16
f4("fbSc", "反馈辊缝修正", ""),
f4("mfSc", "秒流量辊缝修正", ""),
// no.17~20
f4("entryTension", "入口张力", "kN"),
f4("entryTensionDiff", "入口张力差", "kN"),
f4("exitTension", "出口张力", "kN"),
f4("exitTensionDiff", "出口张力差", "kN"),
// no.21~23
f4("entrySpeed", "入口速度", "m/min"),
f4("exitSpeed", "出口速度", "m/min"),
f4("standSpeed", "机架速度", "m/min"),
// no.24~27
f4("rollForce", "轧制力", "kN"),
f4("rollForceDiff", "轧制力差", "kN"),
f4("rollgap", "辊缝", "mm"),
f4("rollgapDiff", "辊缝差", "mm"),
// no.28~30
f4("forwardslip", "前滑值", ""),
f4("power", "功率", "kW"),
f4("torque", "扭矩", "kNm"),
// no.31~35
f4("irbendMeasure", "工作辊弯辊实测", "kN"),
f4("irbendReference", "工作辊弯辊设定", "kN"),
f4("wrbendMeasure", "支撑辊弯辊实测", "kN"),
f4("wrbendReference", "支撑辊弯辊设定", "kN"),
f4("irshift", "工作辊横移", "mm")
));
// ── Schema 注册表 ──────────────────────────────────────────────────
private static final Map<Integer, List<MillDataField>> SCHEMA_MAP;
private static final Map<Integer, String> ID_DESCRIPTIONS;
static {
Map<Integer, List<MillDataField>> m = new LinkedHashMap<>();
m.put(ID_1202, SCHEMA_1202);
SCHEMA_MAP = Collections.unmodifiableMap(m);
Map<Integer, String> d = new LinkedHashMap<>();
d.put(ID_1202, "100ms周期数据轧机实时状态");
ID_DESCRIPTIONS = Collections.unmodifiableMap(d);
}
public static List<MillDataField> getSchema(int id) {
return SCHEMA_MAP.get(id);
}
public static Map<Integer, List<MillDataField>> getAllSchemas() {
return SCHEMA_MAP;
}
public static Map<Integer, String> getIdDescriptions() {
return ID_DESCRIPTIONS;
}
public static boolean isKnownId(int id) {
return SCHEMA_MAP.containsKey(id);
}
}

View File

@@ -0,0 +1,78 @@
package com.ruoyi.mill.udp;
import com.ruoyi.mill.protocol.MillDataCodec;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
/**
* 新协议报文记录(发送/接收)
*/
public class MillDataRecord {
private static final DateTimeFormatter FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
private long id;
private int packetId;
private String direction; // IN / OUT
private String timestamp;
private int dataLength;
private String rawHex; // 完整报文16进制
private Map<String, Object> fields; // 解析后字段
private boolean success;
private String targetHost;
private int targetPort;
private String sourceHost;
private int sourcePort;
private MillDataRecord() {}
public static MillDataRecord inbound(long id, int packetId, byte[] rawFrame,
Map<String, Object> fields,
String sourceHost, int sourcePort) {
MillDataRecord r = new MillDataRecord();
r.id = id;
r.packetId = packetId;
r.direction = "IN";
r.timestamp = LocalDateTime.now().format(FMT);
r.dataLength = rawFrame.length;
r.rawHex = MillDataCodec.toHexString(rawFrame);
r.fields = fields;
r.success = true;
r.sourceHost = sourceHost;
r.sourcePort = sourcePort;
return r;
}
public static MillDataRecord outbound(long id, int packetId, byte[] rawFrame,
Map<String, Object> fields,
boolean success,
String targetHost, int targetPort) {
MillDataRecord r = new MillDataRecord();
r.id = id;
r.packetId = packetId;
r.direction = "OUT";
r.timestamp = LocalDateTime.now().format(FMT);
r.dataLength = rawFrame.length;
r.rawHex = MillDataCodec.toHexString(rawFrame);
r.fields = fields;
r.success = success;
r.targetHost = targetHost;
r.targetPort = targetPort;
return r;
}
public long getId() { return id; }
public int getPacketId() { return packetId; }
public String getDirection() { return direction; }
public String getTimestamp() { return timestamp; }
public int getDataLength() { return dataLength; }
public String getRawHex() { return rawHex; }
public Map<String, Object> getFields() { return fields; }
public boolean isSuccess() { return success; }
public String getTargetHost() { return targetHost; }
public int getTargetPort() { return targetPort; }
public String getSourceHost() { return sourceHost; }
public int getSourcePort() { return sourcePort; }
}

View File

@@ -0,0 +1,75 @@
package com.ruoyi.mill.udp;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
/**
* 新协议报文记录仓库线程安全最多保留1000条
*/
@Component
public class MillDataStore {
private static final int MAX_RECORDS = 1000;
private final CopyOnWriteArrayList<MillDataRecord> records = new CopyOnWriteArrayList<>();
private final AtomicLong idGen = new AtomicLong(0);
public MillDataRecord addInbound(int packetId, byte[] rawFrame,
java.util.Map<String, Object> fields,
String sourceHost, int sourcePort) {
MillDataRecord r = MillDataRecord.inbound(idGen.incrementAndGet(), packetId, rawFrame,
fields, sourceHost, sourcePort);
records.add(0, r);
trim();
return r;
}
public MillDataRecord addOutbound(int packetId, byte[] rawFrame,
java.util.Map<String, Object> fields,
boolean success,
String targetHost, int targetPort) {
MillDataRecord r = MillDataRecord.outbound(idGen.incrementAndGet(), packetId, rawFrame,
fields, success, targetHost, targetPort);
records.add(0, r);
trim();
return r;
}
public List<MillDataRecord> getHistory(int pageNum, int pageSize) {
int total = records.size();
int from = (pageNum - 1) * pageSize;
if (from >= total) return Collections.emptyList();
return new ArrayList<>(records.subList(from, Math.min(from + pageSize, total)));
}
public int getTotalCount() {
return records.size();
}
public long countInbound() {
return records.stream().filter(r -> "IN".equals(r.getDirection())).count();
}
public long countOutbound() {
return records.stream().filter(r -> "OUT".equals(r.getDirection())).count();
}
public long countSuccess() {
return records.stream().filter(MillDataRecord::isSuccess).count();
}
public void clear() {
records.clear();
}
private void trim() {
while (records.size() > MAX_RECORDS) {
records.remove(records.size() - 1);
}
}
}

View File

@@ -1,5 +1,8 @@
package com.ruoyi.mill.udp;
import com.ruoyi.mill.protocol.MillDataCodec;
import com.ruoyi.mill.protocol.MillDataField;
import com.ruoyi.mill.protocol.MillDataSchema;
import com.ruoyi.mill.protocol.TelegramCodec;
import com.ruoyi.mill.protocol.TelegramSchema;
import org.slf4j.Logger;
@@ -12,6 +15,7 @@ import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
@@ -92,6 +96,40 @@ public class UdpSender {
return false;
}
// ── 新协议发送 ────────────────────────────────────────────────────
/**
* 新协议发送报文到指定IP:Port
* 帧格式 = [4字节LE ID][4字节LE 数据体长度][数据体]
*/
public boolean sendMillData(int id, String host, int port, Map<String, Object> values) {
List<MillDataField> schema = MillDataSchema.getSchema(id);
if (schema == null) {
log.error("[MILL-DATA] 未知报文ID: {}", id);
return false;
}
byte[] frame = MillDataCodec.encodePacket(id, schema, values);
return sendMillDataRaw(id, host, port, frame, schema, values);
}
public boolean sendMillDataRaw(int id, String host, int port, byte[] frame,
List<MillDataField> schema,
Map<String, Object> values) {
try (DatagramSocket socket = new DatagramSocket()) {
socket.setSoTimeout(props.getTimeout());
InetAddress addr = InetAddress.getByName(host);
DatagramPacket pkt = new DatagramPacket(frame, frame.length, addr, port);
socket.send(pkt);
log.info("[MILL-DATA] 发送成功 id={} -> {}:{} frameLen={}", id, host, port, frame.length);
return true;
} catch (Exception e) {
log.warn("[MILL-DATA] 发送失败 id={} -> {}:{} : {}", id, host, port, e.getMessage());
return false;
}
}
// ── 旧协议内部方法 ────────────────────────────────────────────────
private Map<String, Object> decodePayload(String tcNo, byte[] payload) {
try {
java.util.List<com.ruoyi.mill.protocol.FieldDef> schema = TelegramSchema.getSchema(tcNo);

View File

@@ -1,5 +1,8 @@
package com.ruoyi.mill.udp;
import com.ruoyi.mill.protocol.MillDataCodec;
import com.ruoyi.mill.protocol.MillDataField;
import com.ruoyi.mill.protocol.MillDataSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -11,16 +14,22 @@ import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* UDP 接收服务
* 监听来自 L3 的下行电文,解析电文号后交 TelegramDispatcher 处理
* UDP接收服务,支持两种帧格式自动识别:
*
* 电文帧结构iXComPCS 第18章
* 前6字节 ASCII = 电文号 (TC_NO)
* 后续字节 = 电文体 (payload)
* 新协议(优先判断
* [4字节 LITTLE_ENDIAN] 报文ID (uint32已知ID在MillDataSchema中)
* [4字节 LITTLE_ENDIAN] 数据体长度
* [N字节] 数据体(各字段小端存储)
*
* 旧协议iXComPCS 第18章
* [6字节 ASCII] 电文号 (TC_NO)
* [N字节] 电文体
*/
@Component
public class UdpServer {
@@ -34,6 +43,9 @@ public class UdpServer {
@Autowired
private TelegramDispatcher dispatcher;
@Autowired
private MillDataStore millDataStore;
private DatagramSocket socket;
private volatile boolean running;
private final ExecutorService executor = Executors.newSingleThreadExecutor(
@@ -62,34 +74,28 @@ public class UdpServer {
try {
DatagramPacket pkt = new DatagramPacket(buf, buf.length);
socket.receive(pkt);
// 打印接收到的原始数据信息
String senderAddr = pkt.getAddress().getHostAddress();
int senderPort = pkt.getPort();
byte[] data = Arrays.copyOf(pkt.getData(), pkt.getLength());
log.info("[UDP-RECV] <<<< 收到UDP数据包 - 来源: {}:{}, 长度: {} bytes",
senderAddr, senderPort, data.length);
if (data.length < TC_NO_LEN) {
log.warn("[UDP-RECV] 收到过短数据包,长度={}, 忽略", data.length);
log.info("[UDP-RECV] <<<< {}:{} len={}", senderAddr, senderPort, data.length);
if (data.length < 4) {
log.warn("[UDP-RECV] 数据包过短({} bytes),丢弃", data.length);
continue;
}
String tcNo = new String(data, 0, TC_NO_LEN, StandardCharsets.US_ASCII).trim();
byte[] payload = Arrays.copyOfRange(data, TC_NO_LEN, data.length);
log.info("[UDP-RECV] 电文号: '{}', Payload长度: {} bytes", tcNo, payload.length);
// 打印前32字节的十六进制数据
StringBuilder hexDump = new StringBuilder();
for (int i = 0; i < Math.min(data.length, 32); i++) {
hexDump.append(String.format("%02X ", data[i]));
// 优先尝试新协议前4字节LE读取ID判断是否已注册
int candidateId = MillDataCodec.peekId(data);
if (data.length >= 8 && MillDataSchema.isKnownId(candidateId)) {
handleNewProtocol(data, candidateId, senderAddr, senderPort);
} else if (data.length >= TC_NO_LEN) {
handleOldProtocol(data, senderAddr, senderPort);
} else {
log.warn("[UDP-RECV] 无法识别的短包({} bytes),丢弃", data.length);
}
log.debug("[UDP-RECV] 数据预览: {}", hexDump.toString());
dispatcher.dispatch(tcNo, data, payload);
} catch (Exception e) {
if (running) {
log.error("[UDP-SERVER] 接收异常", e);
@@ -97,4 +103,38 @@ public class UdpServer {
}
}
}
/** 处理新协议帧 */
private void handleNewProtocol(byte[] data, int packetId, String senderAddr, int senderPort) {
int dataLen = java.nio.ByteBuffer.wrap(data, 4, 4)
.order(java.nio.ByteOrder.LITTLE_ENDIAN).getInt();
int bodyLen = Math.min(dataLen, data.length - 8);
byte[] body = Arrays.copyOfRange(data, 8, 8 + bodyLen);
List<MillDataField> schema = MillDataSchema.getSchema(packetId);
Map<String, Object> fields = null;
if (schema != null) {
try {
fields = MillDataCodec.decodeBody(schema, body);
} catch (Exception e) {
log.warn("[UDP-RECV][NEW] 解码数据体失败 id={}: {}", packetId, e.getMessage());
}
}
millDataStore.addInbound(packetId, data, fields, senderAddr, senderPort);
log.info("[UDP-RECV][NEW] id={} dataLen={} bodyDecoded={}", packetId, dataLen, fields != null);
// 打印前32字节hex
if (log.isDebugEnabled()) {
log.debug("[UDP-RECV][NEW] hex: {}", MillDataCodec.toHexString(Arrays.copyOf(data, Math.min(data.length, 32))));
}
}
/** 处理旧协议帧iXComPCS */
private void handleOldProtocol(byte[] data, String senderAddr, int senderPort) {
String tcNo = new String(data, 0, TC_NO_LEN, StandardCharsets.US_ASCII).trim();
byte[] payload = Arrays.copyOfRange(data, TC_NO_LEN, data.length);
log.info("[UDP-RECV][OLD] tcNo='{}' payloadLen={}", tcNo, payload.length);
dispatcher.dispatch(tcNo, data, payload);
}
}

View File

@@ -0,0 +1,45 @@
import request from '@/utils/request'
/** 获取所有报文Schema定义 */
export function getSchemas() {
return request({ url: '/mill/data/schemas', method: 'get' })
}
/**
* 发送报文(字段表单模式)
* @param {Object} data - { host, port, id, fields: {} }
*/
export function sendPacket(data) {
return request({ url: '/mill/data/send', method: 'post', data })
}
/**
* 发送原始Hex报文
* @param {Object} data - { host, port, hex: '...' }
*/
export function sendRawPacket(data) {
return request({ url: '/mill/data/sendRaw', method: 'post', data })
}
/**
* 解析Hex为字段值
* @param {Object} data - { hex: '...' }
*/
export function parsePacket(data) {
return request({ url: '/mill/data/parse', method: 'post', data })
}
/** 获取报文历史 */
export function getHistory(query) {
return request({ url: '/mill/data/history', method: 'get', params: query })
}
/** 获取统计信息 */
export function getStats() {
return request({ url: '/mill/data/stats', method: 'get' })
}
/** 清空历史记录 */
export function clearHistory() {
return request({ url: '/mill/data/history', method: 'delete' })
}

View File

@@ -0,0 +1,796 @@
<template>
<div class="mill-debug">
<!-- 顶栏 -->
<div class="top-bar">
<span class="top-title">报文调试工具</span>
<span class="top-proto">帧格式[4B LE ID] [4B LE 长度] [数据体小端]</span>
<div class="top-right">
<el-tag size="small" type="info"> {{ stats.inbound }}</el-tag>
<el-tag size="small" type="warning" style="margin-left:6px"> {{ stats.outbound }}</el-tag>
<el-switch v-model="autoRefresh" active-text="自动刷新" inactive-text="" size="mini" style="margin-left:12px" />
</div>
</div>
<!-- 主体左发送 / 右接收 -->
<el-row :gutter="14" class="body-row">
<!-- 左列发送 -->
<el-col :span="11" class="left-col">
<!-- 目标地址 + 模板 -->
<el-card class="panel-card" shadow="never">
<div slot="header" class="ph"><i class="el-icon-s-promotion" /> 发送配置</div>
<el-form :model="sf" size="small" label-width="72px" class="cfg-form">
<el-row :gutter="8">
<el-col :span="15">
<el-form-item label="目标IP">
<el-input v-model="sf.host" placeholder="127.0.0.1" />
</el-form-item>
</el-col>
<el-col :span="9">
<el-form-item label="端口">
<el-input-number v-model="sf.port" :min="1" :max="65535" :controls="false" style="width:100%" />
</el-form-item>
</el-col>
</el-row>
<el-form-item label="报文模板">
<el-select v-model="sf.schemaId" style="width:100%" @change="onSchemaChange">
<el-option v-for="s in schemas" :key="s.id" :value="s.id"
:label="`ID = ${s.id} ${s.description}${s.totalBytes}字节)`" />
</el-select>
</el-form-item>
</el-form>
</el-card>
<!-- 字段输入 -->
<el-card class="panel-card fields-card" shadow="never" style="margin-top:10px">
<div slot="header" class="ph">
<i class="el-icon-edit-outline" /> 字段值
<div class="ph-right">
<el-button size="mini" @click="fillTest">测试数据</el-button>
<el-button size="mini" @click="resetFields">清空</el-button>
</div>
</div>
<div class="fields-scroll" v-if="curSchema">
<template v-for="fd in curSchema.fields">
<!-- I4含位字段 -->
<div v-if="fd.bits && fd.bits.length" :key="fd.name" class="bit-block">
<div class="bit-hdr">
<span class="fn">{{ fd.name }}</span>
<span class="fdesc">{{ fd.description }}</span>
<span class="badge i4">I4</span>
<el-input-number v-model="fv[fd.name]" size="mini" :controls="false"
placeholder="整体值" style="width:88px;margin-left:auto"
@change="v => syncBitsFrom(fd, v)" />
</div>
<div class="bits-wrap">
<el-tooltip v-for="bit in fd.bits" :key="bit.name" :content="`bit${bit.index}: ${bit.description}`" placement="top">
<label class="bit-label" :class="{ active: bv[bit.name] }">
<el-switch v-model="bv[bit.name]" @change="syncIntFrom(fd)" />
<span>{{ bit.name }}</span>
</label>
</el-tooltip>
</div>
</div>
<!-- 普通字段 -->
<div v-else :key="fd.name" class="field-row">
<span class="fn">{{ fd.name }}</span>
<span class="fdesc">{{ fd.description }}</span>
<span :class="['badge', fd.type.toLowerCase()]">{{ fd.type }}</span>
<el-input-number v-model="fv[fd.name]" size="mini" :controls="false"
:precision="fd.type==='F4' ? 4 : 0"
style="width:110px;margin-left:auto"
@change="v => { fv = { ...fv, [fd.name]: v } }" />
<span class="unit">{{ fd.unit }}</span>
</div>
</template>
</div>
<div v-else class="empty-hint">请先选择报文模板</div>
</el-card>
<!-- 发送按钮 -->
<div class="send-row">
<el-button type="primary" icon="el-icon-s-promotion" :loading="sending" @click="doSend">
{{ sending ? '发送中' : '发送报文' }}
</el-button>
<span v-if="lastResult" :class="['send-tip', lastResult.ok ? 'ok' : 'err']">
{{ lastResult.msg }}
</span>
</div>
</el-col>
<!-- 右列格式预览 + 接收 -->
<el-col :span="13" class="right-col">
<!-- 报文格式预览实时 -->
<el-card class="panel-card" shadow="never">
<div slot="header" class="ph">
<i class="el-icon-view" /> 报文预览实时
<el-tag size="mini" type="info" style="margin-left:8px">
{{ previewBytes.length }} 字节
</el-tag>
</div>
<el-tabs v-model="previewTab" type="card" size="small">
<!-- JSON -->
<el-tab-pane label="JSON字段值" name="json">
<pre class="code-block json-block">{{ previewJson }}</pre>
</el-tab-pane>
<!-- Hex -->
<el-tab-pane label="Hex十六进制" name="hex">
<div class="hex-legend">
<span class="leg hdr-leg"> 头部 8字节ID + 数据长度</span>
<span class="leg body-leg"> 数据体</span>
</div>
<div class="hex-dump" v-html="previewHexHtml" />
</el-tab-pane>
<!-- 二进制 -->
<el-tab-pane label="Binary二进制" name="bin">
<div class="hex-legend">
<span class="leg hdr-leg"> 头部 8字节</span>
<span class="leg body-leg"> 数据体</span>
<span style="margin-left:auto;font-size:11px;color:#909399">每行8字节 · 含偏移量</span>
</div>
<div class="bin-dump" v-html="previewBinHtml" />
</el-tab-pane>
</el-tabs>
</el-card>
<!-- 接收记录 -->
<el-card class="panel-card recv-card" shadow="never" style="margin-top:10px">
<div slot="header" class="ph">
<i class="el-icon-download" /> 接收记录
<el-button size="mini" icon="el-icon-delete" @click="doClear" style="margin-left:auto">清空</el-button>
</div>
<el-table ref="histTable" :data="history" size="mini" height="200"
highlight-current-row @current-change="onSelect" style="width:100%">
<el-table-column label="方向" width="52" align="center">
<template slot-scope="{ row }">
<el-tag :type="row.direction==='IN'?'success':'warning'" size="mini">
{{ row.direction==='IN'?'收':'发' }}
</el-tag>
</template>
</el-table-column>
<el-table-column prop="packetId" label="ID" width="55" align="center" />
<el-table-column prop="timestamp" label="时间" min-width="150" />
<el-table-column prop="dataLength" label="B" width="45" align="center" />
<el-table-column label="地址" min-width="110">
<template slot-scope="{ row }">
<span class="addr">{{ row.direction==='IN'
? `${row.sourceHost}:${row.sourcePort}`
: `${row.targetHost}:${row.targetPort}` }}</span>
</template>
</el-table-column>
</el-table>
<!-- 选中报文多格式展示 -->
<div v-if="sel" class="detail-area">
<el-tabs v-model="detailTab" type="card" size="small">
<el-tab-pane label="JSON字段值" name="json">
<pre class="code-block json-block">{{ selJson }}</pre>
</el-tab-pane>
<el-tab-pane label="Hex十六进制" name="hex">
<div class="hex-legend">
<span class="leg hdr-leg"> 头部</span>
<span class="leg body-leg"> 数据体</span>
</div>
<div class="hex-dump" v-html="selHexHtml" />
</el-tab-pane>
<el-tab-pane label="Binary二进制" name="bin">
<div class="hex-legend">
<span class="leg hdr-leg"> 头部</span>
<span class="leg body-leg"> 数据体</span>
</div>
<div class="bin-dump" v-html="selBinHtml" />
</el-tab-pane>
</el-tabs>
</div>
<div v-else class="empty-hint" style="padding:12px 0"> 点击记录查看详情</div>
</el-card>
</el-col>
</el-row>
</div>
</template>
<script>
import {
getSchemas, sendPacket, getHistory, getStats, clearHistory
} from '@/api/mill/millData'
export default {
name: 'MillDebug',
data() {
return {
schemas: [],
curSchema: null,
// 发送表单
sf: { host: '127.0.0.1', port: 9000, schemaId: null },
fv: {}, // field values: name → Number
bv: {}, // bit values: bitName → Boolean
sending: false,
lastResult: null,
// 预览
previewTab: 'hex',
// 接收
history: [],
stats: { inbound: 0, outbound: 0 },
sel: null,
detailTab: 'hex',
autoRefresh: true,
timer: null
}
},
computed: {
// ── 实时预览(自动追踪 fv / bv 变化)──────────────────────────
previewBytes() {
if (!this.curSchema || !this.sf.schemaId) return []
const merged = {}
for (const fd of this.curSchema.fields) {
if (fd.bits && fd.bits.length) {
let v = 0
for (const b of fd.bits) { if (this.bv[b.name]) v |= (1 << b.index) }
merged[fd.name] = v
} else {
merged[fd.name] = this.fv[fd.name] || 0
}
}
return this.encodePacket(this.sf.schemaId, this.curSchema.fields, merged)
},
previewJson() {
if (!this.curSchema) return '{}'
const obj = {}
for (const fd of this.curSchema.fields) {
if (fd.bits && fd.bits.length) {
obj[fd.name] = this.fv[fd.name] || 0
for (const b of fd.bits) obj[b.name] = this.bv[b.name] ? 1 : 0
} else {
obj[fd.name] = this.fv[fd.name] || 0
}
}
return JSON.stringify(obj, null, 2)
},
previewHexHtml() {
return this.buildHexHtml(this.previewBytes)
},
previewBinHtml() {
return this.buildBinHtml(this.previewBytes)
},
// ── 选中记录计算 ───────────────────────────────────────────────
selJson() {
if (!this.sel || !this.sel.fields) return '(无解析数据)'
return JSON.stringify(this.sel.fields, null, 2)
},
selHexHtml() {
if (!this.sel) return ''
return this.buildHexHtml(this.hexStrToBytes(this.sel.rawHex))
},
selBinHtml() {
if (!this.sel) return ''
return this.buildBinHtml(this.hexStrToBytes(this.sel.rawHex))
}
},
created() {
this.loadSchemas()
this.loadHistory()
this.loadStats()
this.timer = setInterval(() => {
if (this.autoRefresh) { this.loadHistory(); this.loadStats() }
}, 2000)
},
beforeDestroy() {
clearInterval(this.timer)
},
methods: {
// ── Schema ──────────────────────────────────────────────────────
async loadSchemas() {
try {
const res = await getSchemas()
this.schemas = (res.data && res.data.schemas) || []
if (this.schemas.length && !this.sf.schemaId) {
this.sf.schemaId = this.schemas[0].id
this.onSchemaChange(this.schemas[0].id)
}
} catch { /**/ }
},
onSchemaChange(id) {
this.curSchema = this.schemas.find(s => s.id === id) || null
// 整体替换对象 → Vue 2 会完整观察新对象的所有 key
const newFv = {}
const newBv = {}
if (this.curSchema) {
for (const fd of this.curSchema.fields) {
newFv[fd.name] = 0
if (fd.bits) for (const b of fd.bits) newBv[b.name] = false
}
}
this.fv = newFv
this.bv = newBv
},
// ── 位字段同步 ───────────────────────────────────────────────────
syncBitsFrom(fd, val) {
const v = val || 0
const newBv = { ...this.bv }
for (const b of (fd.bits || [])) newBv[b.name] = !!((v >> b.index) & 1)
this.bv = newBv
},
syncIntFrom(fd) {
let v = 0
for (const b of (fd.bits || [])) { if (this.bv[b.name]) v |= (1 << b.index) }
this.fv = { ...this.fv, [fd.name]: v }
},
// ── 测试 / 清空 ──────────────────────────────────────────────────
fillTest() {
if (!this.curSchema) return
const newFv = {}
const newBv = {}
for (const fd of this.curSchema.fields) {
if (fd.name === 'counter') newFv[fd.name] = 1
else if (fd.name === 'passNo') newFv[fd.name] = 3
else if (fd.type === 'I4' || fd.type === 'I2') newFv[fd.name] = 0
else newFv[fd.name] = parseFloat((Math.random() * 100).toFixed(3))
if (fd.bits) {
for (const b of fd.bits) newBv[b.name] = !!((newFv[fd.name] >> b.index) & 1)
}
}
this.fv = newFv
this.bv = newBv
},
resetFields() {
if (this.curSchema) this.onSchemaChange(this.sf.schemaId)
},
// ── 发送 ─────────────────────────────────────────────────────────
async doSend() {
if (!this.sf.host) return this.$message.warning('请输入目标IP')
if (!this.sf.schemaId) return this.$message.warning('请选择报文模板')
this.sending = true
this.lastResult = null
try {
// previewBytes computed 里已经合并了位字段,直接复用同一份 merged 逻辑
const merged = {}
for (const fd of (this.curSchema ? this.curSchema.fields : [])) {
if (fd.bits && fd.bits.length) {
let v = 0
for (const b of fd.bits) { if (this.bv[b.name]) v |= (1 << b.index) }
merged[fd.name] = v
} else {
merged[fd.name] = this.fv[fd.name] || 0
}
}
await sendPacket({ host: this.sf.host, port: this.sf.port, id: this.sf.schemaId, fields: merged })
this.lastResult = { ok: true, msg: `✓ 已发送 → ${this.sf.host}:${this.sf.port}` }
this.$message.success(this.lastResult.msg)
await this.loadHistory()
await this.loadStats()
} catch (e) {
this.lastResult = { ok: false, msg: `${e.message}` }
this.$message.error(this.lastResult.msg)
} finally {
this.sending = false
}
},
// ── 历史 ─────────────────────────────────────────────────────────
async loadHistory() {
try {
const res = await getHistory({ pageNum: 1, pageSize: 100 })
const rows = (res.data && res.data.rows) || []
const selId = this.sel && this.sel.id
this.history = rows
if (selId) {
const found = rows.find(r => r.id === selId)
this.$nextTick(() => {
this.sel = found || this.sel
if (found && this.$refs.histTable) {
this.$refs.histTable.setCurrentRow(found)
}
})
}
} catch { /**/ }
},
async loadStats() {
try {
const res = await getStats()
this.stats = res.data || this.stats
} catch { /**/ }
},
async doClear() {
try {
await this.$confirm('确定清空所有记录?', '提示', { type: 'warning' })
await clearHistory()
this.history = []
this.sel = null
this.stats = { inbound: 0, outbound: 0 }
} catch { /**/ }
},
onSelect(row) {
this.sel = row
this.detailTab = row && row.fields ? 'json' : 'hex'
},
// ══════════════════════════════════════════════════════════════
// 前端小端编码(与后端 MillDataCodec 一致)
// ══════════════════════════════════════════════════════════════
encodePacket(id, fields, values) {
// 计算数据体大小
const bodyLen = fields.reduce((s, f) => s + (f.type === 'I2' ? 2 : 4), 0)
const total = 8 + bodyLen
const buf = new ArrayBuffer(total)
const dv = new DataView(buf)
let off = 0
// 头部
dv.setUint32(off, id, true); off += 4 // LE ID
dv.setUint32(off, bodyLen, true); off += 4 // LE length
// 数据体
for (const fd of fields) {
const v = values[fd.name] || 0
if (fd.type === 'I4') { dv.setInt32(off, v | 0, true); off += 4 }
else if (fd.type === 'I2') { dv.setInt16(off, v | 0, true); off += 2 }
else { dv.setFloat32(off, parseFloat(v) || 0, true); off += 4 }
}
return Array.from(new Uint8Array(buf))
},
// ══════════════════════════════════════════════════════════════
// 格式化工具
// ══════════════════════════════════════════════════════════════
hexStrToBytes(hexStr) {
if (!hexStr) return []
return hexStr.split(/\s+/).filter(Boolean).map(h => parseInt(h, 16))
},
/** Hex dump HTML每行16字节头部前8字节蓝色其余绿色 */
buildHexHtml(bytes) {
if (!bytes || !bytes.length) return '<span style="color:#666">(无数据)</span>'
const rows = []
for (let i = 0; i < bytes.length; i += 16) {
const rowBytes = bytes.slice(i, i + 16)
const offset = i.toString(16).padStart(4, '0').toUpperCase()
const hexParts = rowBytes.map((b, j) => {
const abs = i + j
const hex = b.toString(16).padStart(2, '0').toUpperCase()
const cls = abs < 8 ? 'hdr' : 'body'
return `<span class="hx ${cls}">${hex}</span>`
})
// 中间空格
if (rowBytes.length > 8) {
hexParts.splice(8, 0, '<span class="hx-gap"> </span>')
}
rows.push(`<div class="dump-row"><span class="off">${offset}</span> ${hexParts.join(' ')}</div>`)
}
return rows.join('')
},
/** Binary dump HTML每行8字节每字节8位头部蓝色 */
buildBinHtml(bytes) {
if (!bytes || !bytes.length) return '<span style="color:#666">(无数据)</span>'
const rows = []
for (let i = 0; i < bytes.length; i += 8) {
const rowBytes = bytes.slice(i, i + 8)
const offset = i.toString(16).padStart(4, '0').toUpperCase()
const binParts = rowBytes.map((b, j) => {
const abs = i + j
const bits = b.toString(2).padStart(8, '0')
const cls = abs < 8 ? 'hdr' : 'body'
return `<span class="bx ${cls}">${bits}</span>`
})
rows.push(`<div class="dump-row"><span class="off">${offset}</span> ${binParts.join(' ')}</div>`)
}
return rows.join('')
}
}
}
</script>
<style scoped lang="scss">
// ── 全局 ─────────────────────────────────────────────────────────────
.mill-debug {
height: 100vh;
display: flex;
flex-direction: column;
background: #f0f2f5;
overflow: hidden;
}
// ── 顶栏 ─────────────────────────────────────────────────────────────
.top-bar {
display: flex;
align-items: center;
padding: 8px 16px;
background: #1c2b3a;
color: #c8d8e8;
flex-shrink: 0;
.top-title { font-size: 15px; font-weight: 700; color: #fff; margin-right: 16px; }
.top-proto { font-family: monospace; font-size: 12px; color: #6a8aab; flex: 1; }
.top-right { display: flex; align-items: center; }
}
// ── 主体 ─────────────────────────────────────────────────────────────
.body-row {
flex: 1;
overflow: hidden;
margin: 10px 10px 0 !important;
.left-col, .right-col {
height: 100%;
overflow-y: auto;
padding-bottom: 10px;
}
}
// ── 卡片 ─────────────────────────────────────────────────────────────
.panel-card {
border-radius: 6px;
::v-deep .el-card__body { padding: 10px 12px; }
}
.ph {
display: flex;
align-items: center;
font-weight: 600;
font-size: 13px;
color: #303133;
gap: 6px;
.ph-right { margin-left: auto; display: flex; gap: 6px; }
}
// ── 配置表单 ─────────────────────────────────────────────────────────
.cfg-form ::v-deep .el-form-item { margin-bottom: 8px; }
// ── 字段列表 ─────────────────────────────────────────────────────────
.fields-card {
::v-deep .el-card__body { padding: 0; }
}
.fields-scroll {
max-height: 340px;
overflow-y: auto;
}
.field-row {
display: flex;
align-items: center;
padding: 5px 12px;
font-size: 12px;
border-bottom: 1px solid #f5f5f5;
gap: 6px;
&:hover { background: #f8fbff; }
&:last-child { border-bottom: none; }
}
.fn {
width: 128px;
font-family: 'Courier New', monospace;
font-size: 12px;
color: #1f3c5e;
flex-shrink: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.fdesc {
flex: 1;
color: #909399;
font-size: 11px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.unit {
width: 40px;
font-size: 11px;
color: #c0c4cc;
flex-shrink: 0;
}
// ── 位字段块 ─────────────────────────────────────────────────────────
.bit-block {
border-left: 3px solid #409eff;
background: #f0f7ff;
margin: 2px 0;
}
.bit-hdr {
display: flex;
align-items: center;
padding: 5px 12px;
gap: 6px;
font-size: 12px;
border-bottom: 1px dashed #c8dcf0;
}
.bits-wrap {
display: flex;
flex-wrap: wrap;
gap: 6px;
padding: 6px 12px 8px 20px;
}
.bit-label {
display: flex;
align-items: center;
gap: 4px;
font-size: 11px;
color: #606266;
cursor: pointer;
padding: 2px 6px;
border-radius: 3px;
background: #fff;
border: 1px solid #ddd;
transition: all .15s;
&.active {
background: #ecf5ff;
border-color: #409eff;
color: #409eff;
font-weight: 600;
}
::v-deep .el-switch { transform: scale(0.75); }
}
// ── 类型徽章 ─────────────────────────────────────────────────────────
.badge {
flex-shrink: 0;
font-size: 10px;
font-weight: 700;
padding: 1px 5px;
border-radius: 3px;
font-family: monospace;
&.i4 { background: #ecf5ff; color: #409eff; }
&.i2 { background: #f0f9eb; color: #67c23a; }
&.f4 { background: #fdf6ec; color: #e6a23c; }
}
// ── 发送按钮行 ───────────────────────────────────────────────────────
.send-row {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 4px 4px;
.send-tip { font-size: 12px; }
.ok { color: #67c23a; }
.err { color: #f56c6c; }
}
// ── 代码块 ───────────────────────────────────────────────────────────
.code-block {
margin: 0;
padding: 10px;
font-family: 'Courier New', monospace;
font-size: 12px;
line-height: 1.6;
color: #2d6a2d;
background: #f6fff6;
border-radius: 0 0 4px 4px;
overflow-x: auto;
max-height: 240px;
overflow-y: auto;
border: 1px solid #e0ede0;
}
.json-block {
color: #1a6b1a;
}
// ── 图例 ─────────────────────────────────────────────────────────────
.hex-legend {
display: flex;
align-items: center;
gap: 12px;
padding: 4px 10px;
background: #f5f7fa;
border-bottom: 1px solid #e4e7ed;
font-size: 11px;
.leg { display: flex; align-items: center; gap: 4px; }
.hdr-leg { color: #1a6db5; font-weight: 600; }
.body-leg { color: #2a7a2a; font-weight: 600; }
}
// ── Hex dump ─────────────────────────────────────────────────────────
.hex-dump {
background: #fff;
border: 1px solid #e4e7ed;
padding: 8px 10px;
border-radius: 0 0 4px 4px;
font-family: 'Courier New', monospace;
font-size: 12.5px;
line-height: 1.9;
overflow-x: auto;
max-height: 240px;
overflow-y: auto;
::v-deep .dump-row { white-space: nowrap; }
::v-deep .off { color: #aaa; margin-right: 10px; font-size: 11px; user-select: none; }
::v-deep .hx-gap { display: inline-block; width: 10px; }
::v-deep .hx.hdr { color: #1a6db5; font-weight: 600; }
::v-deep .hx.body { color: #2a7a2a; }
}
// ── Binary dump ──────────────────────────────────────────────────────
.bin-dump {
background: #fff;
border: 1px solid #e4e7ed;
padding: 8px 10px;
border-radius: 0 0 4px 4px;
font-family: 'Courier New', monospace;
font-size: 11.5px;
line-height: 1.9;
overflow-x: auto;
max-height: 240px;
overflow-y: auto;
::v-deep .dump-row { white-space: nowrap; }
::v-deep .off { color: #aaa; margin-right: 10px; font-size: 11px; user-select: none; }
::v-deep .bx { letter-spacing: 1px; }
::v-deep .bx.hdr { color: #1a6db5; font-weight: 600; }
::v-deep .bx.body { color: #2a7a2a; }
}
// ── 接收卡片 ─────────────────────────────────────────────────────────
.recv-card {
.addr { font-family: monospace; font-size: 11px; color: #606266; }
}
.detail-area {
margin-top: 8px;
border: 1px solid #ebeef5;
border-radius: 4px;
overflow: hidden;
::v-deep .el-tabs__header { margin: 0; }
}
// ── 空态 ─────────────────────────────────────────────────────────────
.empty-hint {
text-align: center;
color: #c0c4cc;
font-size: 13px;
padding: 20px 0;
}
</style>

View File

@@ -267,7 +267,7 @@ export default {
// 配置表单
configForm: {
localPort: 8080,
localPort: 8090,
remotePort: 8081,
remoteHost: '192.168.1.100',
bufferSize: 8192,