LIN报文和高速数据服务功能

This commit is contained in:
2025-10-28 23:09:10 +08:00
parent 3b0eb86eb2
commit 46d086e74a
2 changed files with 98 additions and 20 deletions

View File

@@ -97,6 +97,15 @@ namespace CapMachine.Wpf.LinDrive
private List<FrameReadCtx> RecvFrameCtxs = new List<FrameReadCtx>();
// 接收缓冲池(重用,避免每轮分配)
private IntPtr RecvMsgBufferPtr = IntPtr.Zero;
private int RecvMsgBufferCapacity = 1024;
private readonly int LinMsgSize = Marshal.SizeOf(typeof(USB2LIN_EX.LIN_EX_MSG));
// 控制台调试输出开关(默认关闭,防止日志风暴)
public bool EnableConsoleDebugLog { get; set; } = false;
// 保护接收缓冲的并发锁(接收读与关闭释放之间的互斥)
private readonly object RecvBufferSync = new object();
/// <summary>
/// 开始LDF文件写入
/// </summary>
@@ -494,6 +503,48 @@ namespace CapMachine.Wpf.LinDrive
}
}
// 从适配器读取原始LIN报文并写入高速记录服务
lock (RecvBufferSync)
{
if (RecvMsgBufferPtr == IntPtr.Zero)
{
RecvMsgBufferPtr = Marshal.AllocHGlobal(LinMsgSize * RecvMsgBufferCapacity);
if (EnableConsoleDebugLog) LoggerService?.Info("申请 LIN RecvMsgBufferPtr");
}
var msgPtRead = RecvMsgBufferPtr;
int linNum = LDFParser.LDF_GetRawMsg(LDFHandle, msgPtRead, RecvMsgBufferCapacity);
if (linNum > 0)
{
for (int i = 0; i < linNum; i++)
{
var msgPtr = (IntPtr)(msgPtRead + i * LinMsgSize);
var linMsg = (USB2LIN_EX.LIN_EX_MSG)Marshal.PtrToStructure(msgPtr, typeof(USB2LIN_EX.LIN_EX_MSG));
// 仅使用有效数据长度
int dataLen = linMsg.DataLen <= 0 ? 0 : Math.Min(linMsg.Data?.Length ?? 0, linMsg.DataLen);
string dataHex = dataLen > 0 ? BitConverter.ToString(linMsg.Data, 0, dataLen) : string.Empty;
if (EnableConsoleDebugLog)
{
Console.WriteLine($"LINMsg[{i}] PID=0x{linMsg.PID:X2} Type={linMsg.MsgType} CheckType={linMsg.CheckType} DataLen={linMsg.DataLen} Data={dataHex}");
}
// 推送到高速数据记录服务
HighSpeedDataService.AppendOrUpdateMsg(new Models.HighSpeed.CommMsg()
{
Category = "LIN",
MsgInfo = "0x" + linMsg.PID.ToString("X2"),
MsgData = dataHex,
Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")
});
}
}
else if (linNum < 0 && EnableConsoleDebugLog)
{
Console.WriteLine("Get LIN raw data error!");
}
}
IsReviceOk = true;
}
catch (Exception ex)
@@ -1155,6 +1206,16 @@ namespace CapMachine.Wpf.LinDrive
try { LDFParser.LDF_Release(LDFHandle); } catch { }
LDFHandle = 0;
}
// 释放接收缓冲区
lock (RecvBufferSync)
{
if (RecvMsgBufferPtr != IntPtr.Zero)
{
try { Marshal.FreeHGlobal(RecvMsgBufferPtr); }
catch { }
finally { RecvMsgBufferPtr = IntPtr.Zero; }
}
}
}
catch { }
USB_DEVICE.USB_CloseDevice(DevHandle);