TFLH/ViewModel/AginTestVM.cs
2026-10-20 09:42:02 +08:00

1097 lines
37 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Community;
using MahApps.Metro.Controls.Dialogs;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using static Community.ZLGCAN;
namespace ViewModel
{
partial class MainWindowVM
{
public static IntPtr devHandle = IntPtr.Zero; // 设备句柄
public static IntPtr[] linHandle = new IntPtr[2]; // lin 通道句柄
public static volatile bool isRunning = true; // 线程标志
public static uint isMerge = 0; // 合并接收标志
public static readonly object _consoleLock = new object(); // 控制台输出锁对象
#region 各种方法
/// <summary>
/// 连接
/// </summary>
public DelegateCommand OpenDeviceCommand { get; set; }
/// <summary>
/// 关闭
/// </summary>
public DelegateCommand CloseDeviceCommand { get; set; }
/// <summary>
/// 唤醒
/// </summary>
public DelegateCommand AwakenCommand { get; set; }
/// <summary>
/// 运行指令群组
/// </summary>
public DelegateCommand RunCommandGroupCommand { get; set; }
/// <summary>
/// 运行单个指令
/// </summary>
public DelegateCommand RunCommandModeCommand { get; set; }
/// <summary>
/// 新增群组
/// </summary>
public DelegateCommand AddCommandGroupCommand { get; set; }
/// <summary>
/// 新增指令
/// </summary>
public DelegateCommand AddCommandModeCommand { get; set; }
/// <summary>
/// 删除群组
/// </summary>
public DelegateCommand DeleteCommandGroupCommand { get; set; }
/// <summary>
/// 删除项目指令
/// </summary>
public DelegateCommand DeleteCommandModecCommand { get; set; }
#endregion
#region 选中的指令组
private CommandGroup selectCommandGroup;
/// <summary>
/// 选中的指令组
/// </summary>
public CommandGroup SelectCommandGroup
{
get { return selectCommandGroup; }
set
{
selectCommandGroup = value;
RaisePropertyChanged("SelectCommandGroup");
}
}
#endregion
#region 选中的指令
private CommandModel selectCommandModel;
/// <summary>
/// 选中的指令
/// </summary>
public CommandModel SelectCommandModel
{
get { return selectCommandModel; }
set
{
selectCommandModel = value;
RaisePropertyChanged("SelectCommandModel");
}
}
#endregion
// 线程传递参数
class ThreadParams
{
/// <summary>
/// 设备句柄
/// </summary>
public IntPtr devHandle { get; set; }
/// <summary>
/// 通道句柄
/// </summary>
public IntPtr chnHandle { get; set; }
/// <summary>
/// 通道号
/// </summary>
public int chnNum { get; set; }
}
/// <summary>
/// 通道1
/// </summary>
ThreadParams Lin0 { get; set; }
private string showStr;
/// <summary>
/// 显示的信息
/// </summary>
public string ShowStr
{
get { return showStr; }
set
{
showStr = value;
RaisePropertyChanged(nameof(ShowStr));
}
}
/// <summary>
/// 测试仪器初始化
/// </summary>
public void InitializeAginTestVM()
{
OpenDeviceCommand = new DelegateCommand() { ExecuteAction = new Action<object>(OpenDevice) };
CloseDeviceCommand = new DelegateCommand() { ExecuteAction = new Action<object>(CloseDevice) };
AwakenCommand = new DelegateCommand() { ExecuteAction = new Action<object>(Awaken) };
RunCommandGroupCommand = new DelegateCommand() { ExecuteAction = new Action<object>(RunCommandGroup) };
RunCommandModeCommand = new DelegateCommand() { ExecuteAction = new Action<object>(RunCommandMode) };
AddCommandGroupCommand = new DelegateCommand() { ExecuteAction = new Action<object>(AddCommandGroup) };
AddCommandModeCommand = new DelegateCommand() { ExecuteAction = new Action<object>(AddCommandMode) };
DeleteCommandGroupCommand = new DelegateCommand() { ExecuteAction = new Action<object>(DeleteCommandGroup) };
DeleteCommandModecCommand = new DelegateCommand() { ExecuteAction = new Action<object>(DeleteCommandModec) };
}
/// <summary>
/// 删除项目指令
/// </summary>
/// <param name="obj"></param>
/// <exception cref="NotImplementedException"></exception>
private void DeleteCommandModec(object obj)
{
CloseRes = MyMessageBox.Show("你确定要删除项目吗?", "提示", MessageDialogStyle.AffirmativeAndNegative);
if (CloseRes == MessageDialogResult.Affirmative)
{
foreach (var item in CurrentMachine.CommandGroupList)
{
if (item.CommandList.Contains(SelectCommandModel))
{
item.CommandList.Remove(SelectCommandModel);
break;
}
}
}
}
/// <summary>
/// 删除群组
/// </summary>
/// <param name="obj"></param>
/// <exception cref="NotImplementedException"></exception>
private void DeleteCommandGroup(object obj)
{
CloseRes = MyMessageBox.Show("你确定要删除工程吗?", "提示", MessageDialogStyle.AffirmativeAndNegative);
if (CloseRes == MessageDialogResult.Affirmative)
{
CurrentMachine.CommandGroupList.Remove(SelectCommandGroup);
}
}
/// <summary>
/// 新增群组
/// </summary>
/// <param name="obj"></param>
/// <exception cref="NotImplementedException"></exception>
private void AddCommandGroup(object obj)
{
if (SelectMachine != null)
{
SelectMachine.CommandGroupList.Add(new CommandGroup() { NameStr = "新来的", Enable = true });
}
}
/// <summary>
/// 新增指令
/// </summary>
/// <param name="obj"></param>
/// <exception cref="NotImplementedException"></exception>
private void AddCommandMode(object obj)
{
string str = obj.ToString();
if (str == "1")
{
if (SelectCommandGroup != null)
{
if(SelectCommandModel!=null)
{
// 获取目标索引
int targetIndex = SelectCommandGroup.CommandList.IndexOf(SelectCommandModel);
// 在目标下一位插入
SelectCommandGroup.CommandList.Insert(targetIndex + 1, new CommandModel() { NameStr = "新来的", Enable = true });
}
}
}
else
{
if (SelectCommandGroup != null)
{
SelectCommandGroup.CommandList.Add(new CommandModel() { NameStr = "新来的", Enable = true });
}
}
}
/// <summary>
/// 运行当个指令
/// </summary>
/// <param name="obj"></param>
/// <exception cref="NotImplementedException"></exception>
private void RunCommandMode(object obj)
{
if (SelectCommandModel != null)
{
RunCommand(SelectCommandModel);
}
}
/// <summary>
/// 运行指令群组
/// </summary>
/// <param name="obj"></param>
/// <exception cref="NotImplementedException"></exception>
private void RunCommandGroup(object obj)
{
Application.Current.Dispatcher.Invoke(() =>
{
if (SelectCommandGroup != null)
{
ShowStr = "";
ZCAN_WakeUpLIN(linHandle[0]);//唤醒
Thread.SpinWait(200);
RunGroup(SelectCommandGroup);
}
});
}
/// <summary>
/// 运行群组
/// </summary>
/// <param name="group"></param>
public void RunGroup(CommandGroup group)
{
foreach (var item in group.CommandList)
{
RunCommand(item);
Thread.SpinWait(item.TimeInterval);
}
}
/// <summary>
/// 运行独立指令
/// </summary>
/// <param name="model"></param>
public void RunCommand(CommandModel model)
{
switch (model.MyType)
{
case 1:
SetLINPublish_Test(linHandle[0], model);
LIN_Send_Test(linHandle[0], model);
break;
case 2:
LIN_Send_Test(linHandle[0], model, true);
break;
case 3:
SetLINPublish_Test(linHandle[0], model);
break;
case 5: //读取数据
break;
}
}
#region 1、唤醒
/// <summary>
/// 唤醒
/// </summary>
/// <param name="obj"></param>
private void Awaken(object obj)
{
uint ret;
// LIN1 发送唤醒帧
ret = ZLGCAN.ZCAN_WakeUpLIN(linHandle[0]);
if (ret == 1)
{
ShowStr += "唤醒成功\r";
}
else
{
ShowStr += "唤醒成功\n";
}
}
#endregion
#region 打开设备
/// <summary>
/// 连接测试设备成功
/// </summary>
bool OpenDeviceOK { get; set; }
/// <summary>
/// 打开设备
/// </summary>
/// <param name="obj"></param>
private void OpenDevice(object obj)
{
if (OpenOpenDevice(41, 0, 0))
{
ShowStr += "打开成功\r";
}
else
{
ShowStr += "打开失败\r";
}
}
/// <summary>
/// 打开ZLGCAN设备
/// </summary>
/// <param name="device_type"></param>
/// <param name="device_index"></param>
/// <param name="reserved"></param>
public bool OpenOpenDevice(uint device_type, uint device_index, uint reserved)
{
if (OpenDeviceOK)
{
return OpenDeviceOK;
}
// 打开设备
//devHandle = ZLGCAN.ZCAN_OpenDevice(41, 0, 0); // USBCANFD-200U 41
devHandle = ZLGCAN.ZCAN_OpenDevice(device_type, device_index, reserved); // USBCANFD-200U 41
if (devHandle == IntPtr.Zero)
{
Console.WriteLine("打开设备失败");
OpenDeviceOK = false;
}
else if (initializationDevice())
{
OpenDeviceOK = true;
}
else
{
OpenDeviceOK = false;
}
return OpenDeviceOK;
}
#endregion
#region 关闭设备
/// <summary>
/// 关闭设备
/// </summary>
/// <param name="obj"></param>
/// <exception cref="NotImplementedException"></exception>
private void CloseDevice(object obj)
{
uint ret;
ret = ZLGCAN.ZCAN_ResetLIN(linHandle[0]);
if (ret != 1)
{
ShowStr += "关闭通道是白\r";
}
// 关闭设备
ret = ZLGCAN.ZCAN_CloseDevice(devHandle);
if (ret != 1)
{
// Console.WriteLine("关闭设备失败");
ShowStr += "关闭设备失败\r";
}
else
{
ShowStr += "关闭设备成功\r";
}
}
#endregion
#region 初始化通道
/// <summary>
/// 初始化通道
/// </summary>
/// <returns></returns>
public bool initializationDevice()
{
// 初始化通道,LIN0作为主站
linHandle[0] = Init_chn_USBCANFD_lin(devHandle, 0, 1, 1);
//linHandle[1] = Init_chn_USBCANFD_lin(devHandle, 1, 1, 1);
//if (linHandle[0] == IntPtr.Zero || linHandle[1] == IntPtr.Zero)
//{
// ZLGCAN.ZCAN_CloseDevice(devHandle);
// return false;
//}
//else
//{
// return true;//初始换成功
//}
if (linHandle[0] != IntPtr.Zero)
{
Lin0 = new ThreadParams() { devHandle = devHandle, chnHandle = linHandle[0], chnNum = 0 };
//ThreadParams parameters = new ThreadParams
//{
// chnHandle = linHandle[i],
// chnNum = i
//};
Thread workerThread = new Thread(ReceiveThread); // 每通道独立线程接收
workerThread.IsBackground = true; // 设置为后台线程,不需要join
workerThread.Start(Lin0);
return true;
}
else
{
return false;
}
}
/// <summary>
/// 初始化 LIN 通道
/// </summary>
/// <param name="dev"></param>
/// <param name="chn_idx"></param>
/// <param name="linMode"></param>
/// <param name="resistance"></param>
/// <returns></returns>
public IntPtr Init_chn_USBCANFD_lin(IntPtr dev, int chn_idx, int linMode, int resistance = 0)
{
ZLGCAN.ZCAN_LIN_INIT_CONFIG lin_config = new ZLGCAN.ZCAN_LIN_INIT_CONFIG();
lin_config.linMode = (byte)linMode; // 0-从站 1-主站
lin_config.chkSumMode = 1; // 1-经典校验 2-增强校验 3-自动
lin_config.libBaud = 19200; // 4800
IntPtr pConfig = Marshal.AllocHGlobal(Marshal.SizeOf(lin_config));
Marshal.StructureToPtr(lin_config, pConfig, true);
IntPtr temp = IntPtr.Zero;
temp = ZLGCAN.ZCAN_InitLIN(dev, (uint)chn_idx, pConfig);
Marshal.FreeHGlobal(pConfig);
if (IntPtr.Zero == temp)
{
ShowStr += ("初始化LIN{0}通道失败", chn_idx);
return IntPtr.Zero;
}
// USBCANFD-200U V1.04,100U V1.03 400U V1.0版本,才支持设置lin终端电阻
string path = String.Format("{0}/lin_initenal_resistance", chn_idx);
string value = resistance.ToString();
uint ret = ZLGCAN.ZCAN_SetValue(devHandle, path, value);
if (ret != 1)
{
ShowStr += ("设置电阻失败");
}
if (ZLGCAN.ZCAN_StartLIN(temp) == 0)
{
ShowStr += ("启动LIN失败,请确认当前硬件/固件版本是否支持LIN通讯");
return IntPtr.Zero;
}
return temp;
}
#endregion
private CommandReceive receiveInfo;
/// <summary>
/// 接收到的信息
/// </summary>
public CommandReceive ReceiveInfo
{
get { return receiveInfo; }
set
{
receiveInfo = value;
RaisePropertyChanged("ReceiveInfo");
}
}
/// <summary>
/// 返回值解析
/// </summary>
private void ZCANLINDataToCommandReceive(ZCANLINData data)
{
//ReceiveInfo = new CommandReceive()
//{
// Dir = data.rxData.dir == 0 ? "Rx " : "Tx ",
// ID = string.Format("{0:X}", data.pid.rawVal & 0x3f),// (data.pid.rawVal & 0x3f),
// DataHex = BitConverter.ToString(data.rxData.data, 0, data.rxData.data.Length)
//};
CommandReceive CR = new CommandReceive()
{
Dir = data.rxData.dir == 0 ? "Rx " : "Tx ",
ID = string.Format("{0:X}", data.pid.rawVal & 0x3f),// (data.pid.rawVal & 0x3f),
DataHex = BitConverter.ToString(data.rxData.data, 0, data.rxData.data.Length),
};
ReceiveInfo = ReceiveInfo ?? new CommandReceive();
if (CR.ID == ReceiveInfo.ID)//如果ID相同 则肯定需要拼接
{
if (!string.IsNullOrEmpty(CR.DataHex))
{
ReceiveInfo.DataHex += "-" + CR.DataHex;
if (MyCommand != null)
{
MyCommand.ReturnValue += "-" + CR.DataHex;
}
}
}
else
{
ReceiveInfo = CR;
if (MyCommand != null && ReceiveInfo!=null)
{
MyCommand.ReturnValue = CR.DataHex;
MyCommand.DataLength = CR.Datalength; //GetLenght(ReceiveInfo.DataHex);
}
}
}
/// <summary>
/// 获取数据长度
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
public int GetLenght(string hex)
{
string[] strArr = hex.Split('-');
var r1 = Convert.ToInt32(strArr[2], 16);
var r2 = Convert.ToInt32(strArr[3], 16);
int res1 = r2 * 255 + r1;
// Hex转byte数组
byte[] dataBytes = strArr.Select(h => Convert.ToByte(h, 16)).ToArray();
// 1. 大端 32位无符号整数
// uint bigEndUint = BitConverter.ToUInt32(dataBytes.Reverse().ToArray(), 0);
// 2. 小端 32位无符号整数
uint res = BitConverter.ToUInt32(dataBytes, 0);
return res1;
}
/// <summary>
/// 接收线程
/// </summary>
/// <param name="obj"></param>
public void ReceiveThread(object obj)
{
ThreadParams parameters = (ThreadParams)obj;
var linMsgSize = Marshal.SizeOf(typeof(ZLGCAN.ZCAN_LIN_MSG));
var linDataSize = Marshal.SizeOf(typeof(ZLGCAN.ZCANLINData));
// 分配接收缓冲区
IntPtr receiveBuffer = Marshal.AllocHGlobal(linMsgSize * 100);
while (isRunning)
{
try
{
uint RecNum = ZLGCAN.ZCAN_GetLINReceiveNum(parameters.chnHandle); // 0-CAN 1-CANFD 2-合并
if (RecNum > 0)
{
uint ReceiveNum = ZLGCAN.ZCAN_ReceiveLIN(parameters.chnHandle, receiveBuffer, 100, 10);
if (ReceiveNum > 0)
{
for (int i = 0; i < ReceiveNum; i++)
{
var linMsg = (ZLGCAN.ZCAN_LIN_MSG)Marshal.PtrToStructure(receiveBuffer + i * linMsgSize, typeof(ZLGCAN.ZCAN_LIN_MSG));
lock (_consoleLock) // 加锁保证输出不混乱
{
if (linMsg.dataType == 0) // LIN 数据
{
var linData = ByteArrayToStruct<ZLGCAN.ZCANLINData>(linMsg.data);
// DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds((long)linData.rxData.timeStamp);
//DateTime time = dateTimeOffset.LocalDateTime;
ShowStr += string.Format("LIN{0} [{1}] ", linMsg.chnl, DateTime.Now.ToString("HH:mm:ss.fff"));
ShowStr += (linData.rxData.dir == 0 ? "Rx " : "Tx ");
ShowStr += string.Format("ID:{0:X} {1}\r", linData.pid.rawVal & 0x3f, ByteArrayToString(linData.rxData.data, linData.rxData.datalen));
ZCANLINDataToCommandReceive(linData);
}
else if (linMsg.dataType == 1) // LIN 错误数据
{
var linErrData = ByteArrayToStruct<ZLGCAN.ZCANLINErrData>(linMsg.data);
ShowStr += string.Format("LIN{0} [{1}] ERROR", linMsg.chnl, DateTime.Now.ToString("HH:mm:ss.fff"));
ShowStr += (linErrData.dir == 0 ? "Rx " : "Tx ");
ShowStr += string.Format("ID:{0:X} \r", linErrData.pid.rawVal & 0x3f);
}
else if (linMsg.dataType == 2) // LIN 事件
{
var linEventData = ByteArrayToStruct<ZLGCAN.ZCANLINEventData>(linMsg.data);
ShowStr += string.Format("LIN{0} [{1}] ", linMsg.chnl, DateTime.Now.ToString("HH:mm:ss.fff"));
if (linEventData.type == ZLGCAN.ZCAN_LIN_WAKE_UP)
{
ShowStr += ("Wake UP\r");
}
if (linEventData.type == ZLGCAN.ZCAN_LIN_ENTERED_SLEEP_MODE)
{
ShowStr += ("Entered sleep mode\r");
}
if (linEventData.type == ZLGCAN.ZCAN_LIN_EXITED_SLEEP_MODE)
{
ShowStr += ("exited sleep mode\r");
}
}
}
}
}
}
}
catch (Exception)
{
}
Thread.Sleep(10);
}
Marshal.FreeHGlobal(receiveBuffer);
}
/// <summary>
/// 接收线程(合并接收)
/// </summary>
/// <param name="obj"></param>
static void ReceiveThread_Merge(object obj)
{
ThreadParams parameters = (ThreadParams)obj;
var dataObjSize = Marshal.SizeOf(typeof(ZLGCAN.ZCANDataObj));
IntPtr receiveBuffer = Marshal.AllocHGlobal(dataObjSize * 100); // 分配接收缓冲区
while (isRunning)
{
uint RecNum = ZLGCAN.ZCAN_GetReceiveNum(devHandle, 2); // 合并接收
if (RecNum > 0)
{
uint ReceiveNum = ZLGCAN.ZCAN_ReceiveData(parameters.devHandle, receiveBuffer, 100, 10);
if (ReceiveNum > 0)
{
for (int i = 0; i < ReceiveNum; i++)
{
var dataObj = (ZLGCAN.ZCANDataObj)Marshal.PtrToStructure(receiveBuffer + i * Marshal.SizeOf(typeof(ZLGCAN.ZCANDataObj)), typeof(ZLGCAN.ZCANDataObj));
if (dataObj.dataType == 1) // CAN/CANFD
{
var canfdData = ByteArrayToStruct<ZLGCAN.ZCANCANFDData>(dataObj.data);
Console.Write("CAN:{0} [{1}] ", dataObj.chnl, canfdData.timeStamp);
// CAN/CANFD
bool isCanFd = (canfdData.flag & 1) != 0;
Console.Write(isCanFd ? "CANFD" : "CAN");
if (isCanFd && (canfdData.frame.flags & 1) == 1)
Console.Write("加速");
// 帧类型
Console.Write((canfdData.frame.can_id & (1 << 31)) != 0 ? "扩展帧 " : "标准帧 ");
// 方向
Console.Write((canfdData.flag & (1 << 9)) != 0 ? " TX " : " RX ");
// ID和数据
Console.Write("ID:{0:X} ", canfdData.frame.can_id & 0x1FFFFFFF);
for (int j = 0; j < canfdData.frame.len; j++)
{
Console.Write("{0:X2} ", canfdData.frame.data[j]);
}
Console.WriteLine("");
}
else if (dataObj.dataType == 4) // LIN
{
var linData = ByteArrayToStruct<ZLGCAN.ZCANLINData>(dataObj.data);
Console.Write("LIN:{0} [{1}] PID: {2:X} ", dataObj.chnl, linData.rxData.timeStamp, linData.pid.rawVal & 0x3f); //去掉校验位,获取真实ID
// 方向
Console.Write(linData.rxData.dir == 1 ? "TX Data: " : "RX Data: ");
// 数据
for (int j = 0; j < linData.rxData.datalen; j++)
Console.Write("{0:X2} ", linData.rxData.data[j]);
Console.WriteLine("");
}
else if (dataObj.dataType == 6) // LIN 错误
{
Console.Write("error");
}
}
}
}
Thread.Sleep(10);
}
Marshal.FreeHGlobal(receiveBuffer);
}
/// <summary>
/// 设置响应
/// </summary>
/// <param name="lin_Handle"></param>
private void SetLINPublish_Test(IntPtr lin_Handle, CommandModel cm)
{
//byte[] ydata = CommunicationManagementClass.HexToBytes("71-06-10-71-46-41-43-54");
//ZCAN_LIN_PUBLISH_CFG lin_Pub = new ZCAN_LIN_PUBLISH_CFG()
//{
// ID = Convert.ToByte("3C", 16),//0x3C,
// datelen = 8,
// data = ydata,
// chkSumMode = 1
//};
ZCAN_LIN_PUBLISH_CFG lin_Pub = GetLpub(cm);
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(lin_Pub));
Marshal.StructureToPtr(lin_Pub, ptr, true);
uint result = ZCAN_SetLINPublish(lin_Handle, ptr, 1); // 设置响应
if (result == 0)
{
Console.WriteLine("设置响应失败");
}
}
/// <summary>
/// 发送 LIN 仅头部报文
/// </summary>
/// <param name="lin_Handle"></param>
/// <param name="ID">对应的响应ID</param>
private void LIN_Send_Test(IntPtr lin_Handle, CommandModel model = null, bool bl = false)
{
//byte ID = 0x3C
byte ID = model != null ? Convert.ToByte(model.ID, 16) : (byte)0x3C;
ZCAN_LIN_MSG linMsg = new ZCAN_LIN_MSG()
{
chnl = 0,
dataType = 0,
data = new byte[46]
};
ZCANLINData linData = new ZCANLINData { pid = { rawVal = ID } };
byte[] linDataBytes = StructureToBytes(linData);
Array.Copy(linDataBytes, 0, linMsg.data, 0, linDataBytes.Length);
IntPtr msgPtr = StructureToPtr(linMsg);
if (bl)
{
model.SendCount = model.SendCount <= 0 ? 1 : model.SendCount;
for (int i = 0; i < model.SendCount; i++)
{
uint result = ZCAN_TransmitLIN(lin_Handle, msgPtr, 1); // 发送仅头部
if (result == 0)
{
Console.WriteLine("发送头部失败");
}
}
}
else
{
uint result = ZCAN_TransmitLIN(lin_Handle, msgPtr, 1); // 发送仅头部
}
Marshal.FreeHGlobal(msgPtr);
}
/// <summary>
/// 取消响应
/// </summary>
/// <param name="lin_Handle"></param>
static void SetLINSubscribe_Test(IntPtr lin_Handle)
{
ZLGCAN.ZCAN_LIN_SUBSCIBE_CFG lin_Sub = new ZLGCAN.ZCAN_LIN_SUBSCIBE_CFG()
{
ID = 0x10,
datelen = 0xFF, // 数据长度,范围为 1-8 当为 255(0xff)则表示设备自动识别报文长度
chkSumMode = 3 // 0- 默认(启动时配置) 1-经典 2-增强校验 3-自动
};
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(lin_Sub));
Marshal.StructureToPtr(lin_Sub, ptr, true);
uint result = ZLGCAN.ZCAN_SetLINSubscribe(lin_Handle, ptr, 1); // 取消响应
if (result == 0)
{
Console.WriteLine("取消响应失败");
}
}
/// <summary>
/// 辅助方法:结构体 -> 字节数组
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static byte[] StructToBytes<T>(T obj)
{
int size = Marshal.SizeOf(typeof(T));
byte[] bytes = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(obj, ptr, false);
Marshal.Copy(ptr, bytes, 0, size);
}
finally
{
Marshal.FreeHGlobal(ptr);
}
return bytes;
}
/// <summary>
/// 辅助方法:字节数组转字符串
/// </summary>
/// <param name="bytes"></param>
/// <param name="length"></param>
/// <returns></returns>
public string ByteArrayToString(byte[] bytes, int length)
{
//HEX
string str = BitConverter.ToString(bytes, 0, Math.Min(length, bytes.Length)).Replace("-", " ");
return str;
}
/// <summary>
/// 辅助方法:结构体转字节数组
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="structure"></param>
/// <returns></returns>
public static byte[] StructureToBytes<T>(T structure)
{
int size = Marshal.SizeOf(typeof(T));
byte[] bytes = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structure, ptr, false);
Marshal.Copy(ptr, bytes, 0, size);
return bytes;
}
finally
{
Marshal.FreeHGlobal(ptr);
}
}
/// <summary>
/// 辅助方法:字节数组转结构体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="bytes"></param>
/// <returns></returns>
public static T ByteArrayToStruct<T>(byte[] bytes) where T : struct
{
int size = Marshal.SizeOf(typeof(T));
IntPtr ptr = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(bytes, 0, ptr, Math.Min(size, bytes.Length));
return (T)Marshal.PtrToStructure(ptr, typeof(T));
}
finally
{
Marshal.FreeHGlobal(ptr);
}
}
/// <summary>
/// 辅助方法:结构体转指针
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="structure"></param>
/// <returns></returns>
public static IntPtr StructureToPtr<T>(T structure)
{
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(T)));
Marshal.StructureToPtr(structure, ptr, false);
return ptr;
}
/// <summary>
/// 指令对象转换
/// </summary>
/// <param name="sendModel"></param>
/// <returns></returns>
public ZCAN_LIN_PUBLISH_CFG GetLpub(CommandModel sendModel)
{
if (sendModel.ID != "3E" && sendModel.ID != "3F")
{
ZCAN_LIN_PUBLISH_CFG dd = new ZCAN_LIN_PUBLISH_CFG()
{
ID = Convert.ToByte(sendModel.ID, 16),//0x3C,
datelen = 8,
data = CommunicationManagementClass.HexToBytes(sendModel.DataHex),
chkSumMode = 1
};
return dd;
}
else
{
ZCAN_LIN_PUBLISH_CFG dd = new ZCAN_LIN_PUBLISH_CFG()
{
ID = Convert.ToByte(sendModel.ID, 16),//0x3C,
datelen = 8,
data = HexToBytesRCR(sendModel),//CommunicationManagementClass.HexToBytes(sendModel.DataHex),
chkSumMode = 1
};
return dd;
}
}
/// <summary>
/// 带RCR校验的 Hex转Byte[]
/// </summary>
/// <param name="dataHex"></param>
/// <returns></returns>
public byte[] HexToBytesRCR(CommandModel model)
{
string data = model.DataHex;
if (data.Contains("-"))
{
//data = Regex.Replace(data, @"(\w{2})", "$1-").Trim('-'); //字符串每隔2位加一个空格
data = data.Replace("-", " ");
}
List<string> strArr = data.Trim().Split(' ').ToList();
List<byte> b = new List<byte>();
//逐个字符变为16进制字节数据
foreach (var item in strArr)
{
if (!string.IsNullOrEmpty(item))
{
b.Add(Convert.ToByte(item.Trim(), 16));
}
}
byte a = GetCrcValue(b.ToArray(), 2, 5);
b[b.Count - 1] = a;
string sss = string.Format("{0:X2}" + " ", a);
strArr[strArr.Count - 1] = sss;
model.DataHex = string.Join("-", strArr);
//按照指定编码将字节数组变为字符串
return b.ToArray();
}
/// <summary>
/// 获取CRC // 从索引2开始算5个字节,返回 0xF1
/// </summary>
/// <param name="data"></param>
/// <param name="startIndex"></param>
/// <param name="len"></param>
/// <returns></returns>
public static byte GetCrcValue(byte[] data, int startIndex, int len)
{
byte crc = 0xFF;
for (int j = startIndex; j < startIndex + len; j++)
{
crc ^= data[j];
for (int i = 0; i < 8; i++)
{
if ((crc & 0x01) > 0)
{
crc >>= 1;
crc ^= 0xA1;
}
else
{
crc >>= 1;
}
}
}
return crc;
}
/// <summary>
/// 计算CRC-8值(多项式 0xA1,初始值 0xFF)
/// </summary>
/// <param name="arrBuff">要计算的数据字节数组</param>
/// <param name="len">参与计算的数据长度</param>
/// <returns>计算出的CRC值</returns>
public static byte GetCrcValue(byte[] arrBuff, int len)
{
byte crc = 0xFF;
for (int j = 0; j < len; j++)
{
crc ^= arrBuff[j];
for (int i = 0; i < 8; i++)
{
if ((crc & 0x01) > 0)
{
crc = (byte)((crc >> 1) ^ 0xA1);
}
else
{
crc = (byte)(crc >> 1);
}
}
}
return crc;
}
/// <summary>
/// hex转string
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
private string HexToString(string hex)
{
List<string> strArr = hex.Trim().Split('-').ToList();
strArr.RemoveRange(0, 4);
List<byte> b = new List<byte>();
//逐个字符变为16进制字节数据
foreach (var item in strArr)
{
b.Add(Convert.ToByte(item.Trim(), 16));
}
//按照指定编码将字节数组变为字符串
return System.Text.Encoding.ASCII.GetString(b.ToArray());
}
}
}