/// <summary> /// 扫描节点 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void scanNode(FormProgress sender, DoWorkEventArgs e) { for (int i = ScanStartAddr; i <= ScanEndAddr; i++) { int ret; UInt32[] appVersion = new UInt32[1], appType = new UInt32[1]; ret = USB2CAN.CAN_BL_NodeCheck(DeviceIndex, CANIndex, (UInt16)i, appVersion, appType, 10); if (ret == USB2CAN.CAN_SUCCESS) { this.listViewNodeList.BeginUpdate(); //数据更新,UI暂时挂起,直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度 ListViewItem lvi = new ListViewItem(); lvi.Text = i.ToString(); if (appType[0] == USB2CAN.CAN_BL_BOOT) { lvi.SubItems.Add("ROOT"); } else { lvi.SubItems.Add("APP"); } lvi.SubItems.Add(String.Format("v{0}.{1}", (((appVersion[0] >> 24) & 0xFF) * 10) + (appVersion[0] >> 16) & 0xFF, (((appVersion[0] >> 8) & 0xFF) * 10) + appVersion[0] & 0xFF)); this.listViewNodeList.Items.Add(lvi); this.listViewNodeList.EndUpdate(); //结束数据处理,UI界面一次性绘制。 } sender.SetProgress(i - ScanStartAddr + 1, "正在检测节点:" + i.ToString()); if (sender.CancellationPending) { e.Cancel = true; return; } } }
public static void SendMsgThread() { while (CANSendMsgFlag) { USB2CAN.CAN_MSG[] CanMsg = new USB2CAN.CAN_MSG[10]; for (int i = 0; i < 10; i++) { CanMsg[i] = new USB2CAN.CAN_MSG(); CanMsg[i].ExternFlag = 0; CanMsg[i].RemoteFlag = 0; CanMsg[i].ID = (UInt32)i; CanMsg[i].DataLen = 8; CanMsg[i].Data = new Byte[CanMsg[i].DataLen]; for (int j = 0; j < CanMsg[i].DataLen; j++) { CanMsg[i].Data[j] = (Byte)j; } } int SendedNum = USB2CAN.CAN_SendMsg(DevHandle, CANSendIndex, CanMsg, (UInt32)CanMsg.Length); if (SendedNum >= 0) { SendMsgNum += SendedNum; Console.WriteLine("Success send frames:{0}", SendMsgNum); } else { Console.WriteLine("Send CAN data failed!"); break; } Thread.Sleep(10); } }
private void buttonSetNewBaudRate_Click(object sender, EventArgs e) { UInt16 NodeAddr; if (configDevice()) { //判断当前所选择的节点 if (this.listViewNodeList.Items.Count <= 0) { //当前节点列表中没有节点 MessageBox.Show(this, "节点列表中无节点,请先扫描节点!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else { if (this.checkBoxAllNode.Checked) { NodeAddr = 0; } else { if (this.listViewNodeList.SelectedIndices[0] < 0) { //没有选择任何节点 MessageBox.Show(this, "请先选择节点!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else { NodeAddr = UInt16.Parse(this.listViewNodeList.Items[this.listViewNodeList.SelectedIndices[0]].SubItems[0].Text); } } } USB2CAN.CAN_INIT_CONFIG CAN_InitConfig = new USB2CAN.CAN_INIT_CONFIG(); int BaudRate = int.Parse(this.comboBoxNewBaudRate.Text.Substring(0, this.comboBoxNewBaudRate.Text.Length - 4)); if (DevType == DevTypeUSB2CANB) { CAN_InitConfig.CAN_BRP = (UInt32)CANBaudRateTab42M[GetBaudRateIndex(BaudRate)].PreScale; CAN_InitConfig.CAN_SJW = CANBaudRateTab42M[GetBaudRateIndex(BaudRate)].SJW; CAN_InitConfig.CAN_BS1 = CANBaudRateTab42M[GetBaudRateIndex(BaudRate)].BS1; CAN_InitConfig.CAN_BS2 = CANBaudRateTab42M[GetBaudRateIndex(BaudRate)].BS2; } else { CAN_InitConfig.CAN_BRP = (UInt32)CANBaudRateTab[GetBaudRateIndex(BaudRate)].PreScale; CAN_InitConfig.CAN_SJW = CANBaudRateTab[GetBaudRateIndex(BaudRate)].SJW; CAN_InitConfig.CAN_BS1 = CANBaudRateTab[GetBaudRateIndex(BaudRate)].BS1; CAN_InitConfig.CAN_BS2 = CANBaudRateTab[GetBaudRateIndex(BaudRate)].BS2; } int ret = USB2CAN.CAN_BL_SetNewBaudRate(DevHandles[DeviceIndex], CANIndex, NodeAddr, ref CAN_InitConfig, (UInt32)BaudRate, 100); if (ret != USB2CAN.CAN_SUCCESS) { MessageBox.Show(this, "设置新波特率失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { this.comboBoxBaudRate.SelectedIndex = this.comboBoxNewBaudRate.SelectedIndex; } } }
public static void ReadMsgThread() { while (CANReadMsgFlag) { USB2CAN.CAN_MSG[] CanMsgBuffer = new USB2CAN.CAN_MSG[1024]; //申请数据缓冲区 IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(USB2CAN.CAN_MSG)) * CanMsgBuffer.Length); int CanNum = USB2CAN.CAN_GetMsgWithSize(DevHandle, CANReadIndex, pt, CanMsgBuffer.Length); if (CanNum > 0) { for (int i = 0; i < CanNum; i++) { CanMsgBuffer[i] = (USB2CAN.CAN_MSG)Marshal.PtrToStructure((IntPtr)((UInt32)pt + i * Marshal.SizeOf(typeof(USB2CAN.CAN_MSG))), typeof(USB2CAN.CAN_MSG)); Console.WriteLine("CanMsg[{0}].ID = {1}", i, CanMsgBuffer[i].ID); Console.WriteLine("CanMsg[{0}].TimeStamp = {1}", i, CanMsgBuffer[i].TimeStamp); Console.Write("CanMsg[{0}].Data = ", i); for (int j = 0; j < CanMsgBuffer[i].DataLen; j++) { Console.Write("{0:X2} ", CanMsgBuffer[i].Data[j]); } Console.WriteLine("\n"); } } else if (CanNum < 0) { Console.WriteLine("Get CAN data error!"); break; } //释放数据缓冲区,必须释放,否则程序运行一段时间后会报内存不足 Marshal.FreeHGlobal(pt); Thread.Sleep(10); } }
private bool InitCAN() { //初始化配置CAN canConfig = new USB2CAN.CAN_INIT_CONFIG(); #if CAN_MODE_LOOPBACK canConfig.CAN_Mode = 1; //环回模式 #else canConfig.CAN_Mode = 0 | (1 << 7); //正常模式 #endif canConfig.CAN_ABOM = 0; //禁止自动离线 canConfig.CAN_NART = 1; //禁止报文重传 canConfig.CAN_RFLM = 0; //FIFO满之后覆盖旧报文 canConfig.CAN_TXFP = 1; //发送请求决定发送顺序 //配置波特率,波特率 = 100M/(BRP*(SJW+BS1+BS2)) canConfig.CAN_BRP = 4; canConfig.CAN_BS1 = 16; canConfig.CAN_BS2 = 4; canConfig.CAN_SJW = 1; var ret = USB2CAN.CAN_Init(DeviceHandle, canIndex, ref canConfig); if (ret != USB2CAN.CAN_SUCCESS) { LogLine("Config CAN failed!"); return(false); } else { LogLine("Config CAN Success!"); return(true); } }
public int GetMsg(ref USB2CAN.CAN_MSG[] msgs) { //申请存储数据缓冲区 IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(USB2CAN.CAN_MSG)) * msgs.Length); int canNum = USB2CAN.CAN_GetMsgWithSize(DeviceHandle, canIndex, pt, msgs.Length); if (canNum > 0) { var structSize = Marshal.SizeOf(typeof(USB2CAN.CAN_MSG)); for (int i = 0; i < canNum; i++) { //从缓冲区中获取数据 msgs[i] = (USB2CAN.CAN_MSG)Marshal.PtrToStructure((IntPtr)((uint)pt + i * structSize), typeof(USB2CAN.CAN_MSG)); LogLine("CanMsg[{0}].ID = {1}", i, msgs[i].ID); LogLine("CanMsg[{0}].TimeStamp = {1}", i, msgs[i].TimeStamp); Log("CanMsg[{0}].Data = ", i); for (int j = 0; j < msgs[i].DataLen; j++) { Log("{0:X2} ", msgs[i].Data[j]); } LogLine("\n"); } } else if (canNum < 0) { LogLine("Get CAN data error!"); } return(canNum); }
/// <summary> /// 初始化配置USB2XXX CAN适配器 /// </summary> /// <returns></returns> private bool configDevice() { int ret, DevNum; bool state; DeviceIndex = this.comboBoxDeviceIndex.SelectedIndex; CANIndex = this.comboBoxCANIndex.SelectedIndex; //扫描查找设备 DevNum = usb_device.USB_ScanDevice(null); if (DevNum <= 0) { MessageBox.Show(this, "无设备连接!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } //打开设备 state = usb_device.USB_OpenDevice(DeviceIndex); if (!state) { MessageBox.Show(this, "打开设备失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } USB2CAN.CBL_CMD_LIST CMD_List = new USB2CAN.CBL_CMD_LIST(); String[] cmdStr = { "Erase", "WriteInfo", "Write", "Check", "SetBaudRate", "Excute", "CmdSuccess", "CmdFaild" }; byte[] cmdData = new byte[cmdStr.Length]; for (int i = 0; i < this.listViewCmdList.Items.Count; i++) { ListViewItem item = listViewCmdList.Items[i]; if (item.SubItems[0].Text == cmdStr[i]) { cmdData[i] = byte.Parse(item.SubItems[1].Text); } } CMD_List.Erase = cmdData[0]; CMD_List.WriteInfo = cmdData[1]; CMD_List.Write = cmdData[2]; CMD_List.Check = cmdData[3]; CMD_List.SetBaudRate = cmdData[4]; CMD_List.Excute = cmdData[5]; CMD_List.CmdSuccess = cmdData[6]; CMD_List.CmdFaild = cmdData[7]; USB2CAN.CAN_INIT_CONFIG CAN_InitConfig = new USB2CAN.CAN_INIT_CONFIG(); int BaudRate = int.Parse(this.comboBoxBaudRate.Text.Substring(0, this.comboBoxBaudRate.Text.Length - 4)); CAN_InitConfig.CAN_BRP = (UInt32)CANBaudRateTab[GetBaudRateIndex(BaudRate)].PreScale; CAN_InitConfig.CAN_SJW = CANBaudRateTab[GetBaudRateIndex(BaudRate)].SJW; CAN_InitConfig.CAN_BS1 = CANBaudRateTab[GetBaudRateIndex(BaudRate)].BS1; CAN_InitConfig.CAN_BS2 = CANBaudRateTab[GetBaudRateIndex(BaudRate)].BS2; ret = USB2CAN.CAN_BL_Init(DeviceIndex, CANIndex, ref CAN_InitConfig, ref CMD_List); if (ret != USB2CAN.CAN_SUCCESS) { MessageBox.Show(this, "初始化设备失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } return(true); }
public bool StopGetMsg() { var ret = USB2CAN.CAN_StopGetMsg(DeviceHandle, canIndex); if (ret != USB2CAN.CAN_SUCCESS) { LogLine("Stop Get Msg failed!"); } else { LogLine("Stop Get Msg Success!"); } return(USB2CAN.CAN_SUCCESS == ret); }
public int SendMsg(USB2CAN.CAN_MSG[] canMsg, uint num) { int sendedNum = USB2CAN.CAN_SendMsg(DeviceHandle, canIndex, canMsg, num); if (sendedNum >= 0) { lastSentTime = DateTime.Now; LogLine("Success send frames:{0}", sendedNum); } else { LogLine("Send CAN data failed!"); } return(sendedNum); }
public USB2CAN.CAN_STATUS GetStatus() { USB2CAN.CAN_STATUS CANStatus = new USB2CAN.CAN_STATUS(); var ret = USB2CAN.CAN_GetStatus(DeviceHandle, canIndex, ref CANStatus); if (ret == USB2CAN.CAN_SUCCESS) { LogLine("TSR = {0:X8}", CANStatus.TSR); LogLine("ESR = {0:X8}", CANStatus.ESR); } else { LogLine("Get CAN status error!\n"); CANStatus = default(USB2CAN.CAN_STATUS); } return(CANStatus); }
public bool StartGetMsg() { if (GetMsgStarted) { return(true); } GetMsgStarted = true; //启动CAN接收数据 var ret = USB2CAN.CAN_StartGetMsg(DeviceHandle, canIndex); if (ret != USB2CAN.CAN_SUCCESS) { LogLine("Start Get Msg failed!"); return(false); } else { LogLine("Start Get Msg Success!"); return(true); } }
private bool InitFilter() { //配置过滤器,接收所有数据 canFilter = new USB2CAN.CAN_FILTER_CONFIG(); canFilter.Enable = 1; canFilter.ExtFrame = 0; canFilter.FilterIndex = 0; canFilter.FilterMode = 0; canFilter.MASK_IDE = 0; canFilter.MASK_RTR = 0; canFilter.MASK_Std_Ext = 0; var ret = USB2CAN.CAN_Filter_Init(DeviceHandle, canIndex, ref canFilter); if (ret != USB2CAN.CAN_SUCCESS) { LogLine("Config CAN Filter failed!"); return(false); } else { LogLine("Config CAN Filter Success!"); return(true); } }
void upgrateFirmware(FormProgress sender, DoWorkEventArgs e) { int FirmwareFileSize; UInt16 NodeAddr; int ret; //如果文件不存在,就提示错误 if (File.Exists(this.textBoxFilePath.Text)) { BinaryReader br; FirmwareFileSize = (int)new FileInfo(this.textBoxFilePath.Text).Length; try { //将固件文件读取到数据缓冲区中 br = new BinaryReader(new FileStream(this.textBoxFilePath.Text, FileMode.Open)); //判断当前所选择的节点 if (this.listViewNodeList.Items.Count <= 0) { //当前节点列表中没有节点 MessageBox.Show(this, "节点列表中无节点,请先扫描节点!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); br.Close(); return; } else { if (this.checkBoxAllNode.Checked) { NodeAddr = 0; } else { if (this.listViewNodeList.SelectedIndices[0] < 0) { //没有选择任何节点 MessageBox.Show(this, "请先选择节点!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); br.Close(); return; } else { NodeAddr = UInt16.Parse(this.listViewNodeList.Items[this.listViewNodeList.SelectedIndices[0]].SubItems[0].Text); } } } //MessageBox.Show(this, "NodeAddr = " + NodeAddr, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); //发送跳转到Bootloader的命令 sender.SetProgress(0, "跳转到Bootloader..."); ret = USB2CAN.CAN_BL_Excute(DeviceIndex, CANIndex, NodeAddr, USB2CAN.CAN_BL_BOOT); if (ret != USB2CAN.CAN_SUCCESS) { MessageBox.Show(this, "执行固件跳转命令失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); br.Close(); return; } //延时 System.Threading.Thread.Sleep(500); //检测当前节点是否为Bootloader if (!this.checkBoxAllNode.Checked) { UInt32[] appVersion = new UInt32[1], appType = new UInt32[1]; ret = USB2CAN.CAN_BL_NodeCheck(DeviceIndex, CANIndex, NodeAddr, appVersion, appType, 10); if (ret != USB2CAN.CAN_SUCCESS) { MessageBox.Show(this, "节点检测失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); br.Close(); return; } else { if (appType[0] != USB2CAN.CAN_BL_BOOT) { MessageBox.Show(this, "当前节点固件类型不是Bootloader,请重新点击升级固件!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); br.Close(); return; } } } //发送擦出固件命令 sender.SetProgress(0, "擦出固件..."); ret = USB2CAN.CAN_BL_Erase(DeviceIndex, CANIndex, NodeAddr, (UInt32)FirmwareFileSize, 10000); if (ret != USB2CAN.CAN_SUCCESS) { MessageBox.Show(this, "擦出固件失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); br.Close(); return; } if (this.checkBoxAllNode.Checked) { System.Threading.Thread.Sleep(1000); } //循环发送数据 UInt32 AddrOffset = 0; UInt32 PackSize = 512; byte[] DataBuffer = new byte[PackSize]; for (AddrOffset = 0; AddrOffset < FirmwareFileSize; AddrOffset += PackSize) { UInt32 read_data_num = (UInt32)br.Read(DataBuffer, 0, (int)PackSize); ret = USB2CAN.CAN_BL_Write(DeviceIndex, CANIndex, NodeAddr, AddrOffset, DataBuffer, read_data_num, 1000); if (ret != USB2CAN.CAN_SUCCESS) { MessageBox.Show(this, "写数据失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); br.Close(); return; } if (this.checkBoxAllNode.Checked) { System.Threading.Thread.Sleep(20); } sender.SetProgress((int)(AddrOffset + read_data_num), "正在发送固件数据..."); } //执行固件 ret = USB2CAN.CAN_BL_Excute(DeviceIndex, CANIndex, NodeAddr, USB2CAN.CAN_BL_APP); if (ret != USB2CAN.CAN_SUCCESS) { MessageBox.Show(this, "执行固件跳转命令失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); br.Close(); return; } System.Threading.Thread.Sleep(100); //获取固件信息 if (!this.checkBoxAllNode.Checked) { UInt32[] appVersion = new UInt32[1], appType = new UInt32[1]; ret = USB2CAN.CAN_BL_NodeCheck(DeviceIndex, CANIndex, NodeAddr, appVersion, appType, 10); if (ret == USB2CAN.CAN_SUCCESS) { string AppTypeStr; if (appType[0] == USB2CAN.CAN_BL_BOOT) { AppTypeStr = "BOOT"; } else { AppTypeStr = "APP"; } this.listViewNodeList.Items[this.listViewNodeList.SelectedIndices[0]].SubItems[1].Text = AppTypeStr; string AppVersionStr; AppVersionStr = String.Format("v{0}.{1}", (((appVersion[0] >> 24) & 0xFF) * 10) + (appVersion[0] >> 16) & 0xFF, (((appVersion[0] >> 8) & 0xFF) * 10) + appVersion[0] & 0xFF); this.listViewNodeList.Items[this.listViewNodeList.SelectedIndices[0]].SubItems[2].Text = AppVersionStr; } } br.Close(); } catch (IOException ep) { MessageBox.Show(this, ep.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } else { MessageBox.Show(this, "无法打开固件文件,是否选择了固件文件?", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
/// <summary> /// 初始化配置USB2XXX CAN适配器 /// </summary> /// <returns></returns> private bool configDevice() { int ret, DevNum; bool state; DeviceIndex = this.comboBoxDeviceIndex.SelectedIndex; CANIndex = this.comboBoxCANIndex.SelectedIndex; //扫描查找设备 DevNum = usb_device.USB_ScanDevice(DevHandles); if (DevNum <= 0) { MessageBox.Show(this, "无设备连接!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } //打开设备 state = usb_device.USB_OpenDevice(DevHandles[DeviceIndex]); if (!state) { MessageBox.Show(this, "打开设备失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } //获取设备类型 usb_device.DEVICE_INFO DevInfo = new usb_device.DEVICE_INFO(); StringBuilder FuncStr = new StringBuilder(256); state = usb_device.DEV_GetDeviceInfo(DevHandles[DeviceIndex], ref DevInfo, FuncStr); if (!state) { MessageBox.Show(this, "获取设备信息失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } DevType = ((UInt64)DevInfo.SerialNumber[0] << 32) | (DevInfo.SerialNumber[1]); USB2CAN.CBL_CMD_LIST CMD_List = new USB2CAN.CBL_CMD_LIST(); String[] cmdStr = { "Erase", "WriteInfo", "Write", "Check", "SetBaudRate", "Execute", "CmdSuccess", "CmdFaild" }; byte[] cmdData = new byte[cmdStr.Length]; for (int i = 0; i < this.listViewCmdList.Items.Count; i++) { ListViewItem item = listViewCmdList.Items[i]; if (item.SubItems[0].Text == cmdStr[i]) { cmdData[i] = byte.Parse(item.SubItems[1].Text); } } CMD_List.Erase = cmdData[0]; CMD_List.WriteInfo = cmdData[1]; CMD_List.Write = cmdData[2]; CMD_List.Check = cmdData[3]; CMD_List.SetBaudRate = cmdData[4]; CMD_List.Execute = cmdData[5]; CMD_List.CmdSuccess = cmdData[6]; CMD_List.CmdFaild = cmdData[7]; USB2CAN.CAN_INIT_CONFIG CAN_InitConfig = new USB2CAN.CAN_INIT_CONFIG(); int BaudRate = int.Parse(this.comboBoxBaudRate.Text.Substring(0, this.comboBoxBaudRate.Text.Length - 4)); if (DevType == DevTypeUSB2CANB) { CAN_InitConfig.CAN_BRP = (UInt32)CANBaudRateTab42M[GetBaudRateIndex(BaudRate)].PreScale; CAN_InitConfig.CAN_SJW = CANBaudRateTab42M[GetBaudRateIndex(BaudRate)].SJW; CAN_InitConfig.CAN_BS1 = CANBaudRateTab42M[GetBaudRateIndex(BaudRate)].BS1; CAN_InitConfig.CAN_BS2 = CANBaudRateTab42M[GetBaudRateIndex(BaudRate)].BS2; } else { CAN_InitConfig.CAN_BRP = (UInt32)CANBaudRateTab[GetBaudRateIndex(BaudRate)].PreScale; CAN_InitConfig.CAN_SJW = CANBaudRateTab[GetBaudRateIndex(BaudRate)].SJW; CAN_InitConfig.CAN_BS1 = CANBaudRateTab[GetBaudRateIndex(BaudRate)].BS1; CAN_InitConfig.CAN_BS2 = CANBaudRateTab[GetBaudRateIndex(BaudRate)].BS2; } ret = USB2CAN.CAN_BL_Init(DevHandles[DeviceIndex], CANIndex, ref CAN_InitConfig, ref CMD_List); if (ret != USB2CAN.CAN_SUCCESS) { MessageBox.Show(this, "初始化设备失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } return(true); }
static void Main(string[] args) { usb_device.DEVICE_INFO DevInfo = new usb_device.DEVICE_INFO(); Int32[] DevHandles = new Int32[20]; Int32 DevHandle = 0; Byte CANIndex = 0; bool state; Int32 DevNum, ret; //扫描查找设备 DevNum = usb_device.USB_ScanDevice(DevHandles); if (DevNum <= 0) { Console.WriteLine("No device connected!"); return; } else { Console.WriteLine("Have {0} device connected!", DevNum); } DevHandle = DevHandles[0]; //打开设备 state = usb_device.USB_OpenDevice(DevHandle); if (!state) { Console.WriteLine("Open device error!"); return; } else { Console.WriteLine("Open device success!"); } //获取固件信息 StringBuilder FuncStr = new StringBuilder(256); state = usb_device.DEV_GetDeviceInfo(DevHandle, ref DevInfo, FuncStr); if (!state) { Console.WriteLine("Get device infomation error!"); return; } else { Console.WriteLine("Firmware Info:"); Console.WriteLine(" Name:" + Encoding.Default.GetString(DevInfo.FirmwareName)); Console.WriteLine(" Build Date:" + Encoding.Default.GetString(DevInfo.BuildDate)); Console.WriteLine(" Firmware Version:v{0}.{1}.{2}", (DevInfo.FirmwareVersion >> 24) & 0xFF, (DevInfo.FirmwareVersion >> 16) & 0xFF, DevInfo.FirmwareVersion & 0xFFFF); Console.WriteLine(" Hardware Version:v{0}.{1}.{2}", (DevInfo.HardwareVersion >> 24) & 0xFF, (DevInfo.HardwareVersion >> 16) & 0xFF, DevInfo.HardwareVersion & 0xFFFF); Console.WriteLine(" Functions:" + DevInfo.Functions.ToString("X8")); Console.WriteLine(" Functions String:" + FuncStr); } //初始化配置CAN USB2CAN.CAN_INIT_CONFIG CANConfig = new USB2CAN.CAN_INIT_CONFIG(); #if CAN_MODE_LOOPBACK CANConfig.CAN_Mode = 1; //环回模式 #else CANConfig.CAN_Mode = 0; //正常模式 #endif CANConfig.CAN_ABOM = 0; //禁止自动离线 CANConfig.CAN_NART = 1; //禁止报文重传 CANConfig.CAN_RFLM = 0; //FIFO满之后覆盖旧报文 CANConfig.CAN_TXFP = 1; //发送请求决定发送顺序 //配置波特率,波特率 = 100M/(BRP*(SJW+BS1+BS2)) CANConfig.CAN_BRP = 2; CANConfig.CAN_BS1 = 15; CANConfig.CAN_BS2 = 5; CANConfig.CAN_SJW = 1; ret = USB2CAN.CAN_Init(DevHandle, CANIndex, ref CANConfig); if (ret != USB2CAN.CAN_SUCCESS) { Console.WriteLine("Config CAN failed!"); return; } else { Console.WriteLine("Config CAN Success!"); } //配置过滤器,接收所有数据 USB2CAN.CAN_FILTER_CONFIG CANFilter = new USB2CAN.CAN_FILTER_CONFIG(); CANFilter.Enable = 1; CANFilter.ExtFrame = 0; CANFilter.FilterIndex = 0; CANFilter.FilterMode = 0; CANFilter.MASK_IDE = 0; CANFilter.MASK_RTR = 0; CANFilter.MASK_Std_Ext = 0; ret = USB2CAN.CAN_Filter_Init(DevHandle, CANIndex, ref CANFilter); if (ret != USB2CAN.CAN_SUCCESS) { Console.WriteLine("Config CAN Filter failed!"); return; } else { Console.WriteLine("Config CAN Filter Success!"); } //启动CAN接收数据 ret = USB2CAN.CAN_StartGetMsg(DevHandle, CANIndex); if (ret != USB2CAN.CAN_SUCCESS) { Console.WriteLine("Start CAN failed!"); return; } else { Console.WriteLine("Start CAN Success!"); } #if CAN_SEND_MSG//发送CAN帧 USB2CAN.CAN_MSG[] CanMsg = new USB2CAN.CAN_MSG[5]; for (int i = 0; i < 5; i++) { CanMsg[i] = new USB2CAN.CAN_MSG(); CanMsg[i].ExternFlag = 0; CanMsg[i].RemoteFlag = 0; CanMsg[i].ID = (UInt32)i; CanMsg[i].DataLen = 8; CanMsg[i].Data = new Byte[CanMsg[i].DataLen]; for (int j = 0; j < CanMsg[i].DataLen; j++) { CanMsg[i].Data[j] = (Byte)j; } } int SendedNum = USB2CAN.CAN_SendMsg(DevHandle, CANIndex, CanMsg, (UInt32)CanMsg.Length); if (SendedNum >= 0) { Console.WriteLine("Success send frames:{0}", SendedNum); } else { Console.WriteLine("Send CAN data failed!"); } #endif #if CAN_GET_STATUS USB2CAN.CAN_STATUS CANStatus = new USB2CAN.CAN_STATUS(); ret = USB2CAN.CAN_GetStatus(DevHandle, CANIndex, ref CANStatus); if (ret == USB2CAN.CAN_SUCCESS) { Console.WriteLine("TSR = {0:X8}", CANStatus.TSR); Console.WriteLine("ESR = {0:X8}", CANStatus.ESR); } else { Console.WriteLine("Get CAN status error!\n"); } #endif //延时 System.Threading.Thread.Sleep(500); #if CAN_GET_MSG for (int t = 0; t < 10; t++) { USB2CAN.CAN_MSG[] CanMsgBuffer = new USB2CAN.CAN_MSG[1024]; //申请存储数据缓冲区 IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(USB2CAN.CAN_MSG)) * CanMsgBuffer.Length); int CanNum = USB2CAN.CAN_GetMsgWithSize(DevHandle, CANIndex, pt, CanMsgBuffer.Length); if (CanNum > 0) { for (int i = 0; i < CanNum; i++) { //从缓冲区中获取数据 CanMsgBuffer[i] = (USB2CAN.CAN_MSG)Marshal.PtrToStructure((IntPtr)((UInt32)pt + i * Marshal.SizeOf(typeof(USB2CAN.CAN_MSG))), typeof(USB2CAN.CAN_MSG)); Console.WriteLine("CanMsg[{0}].ID = {1}", i, CanMsgBuffer[i].ID); Console.WriteLine("CanMsg[{0}].TimeStamp = {1}", i, CanMsgBuffer[i].TimeStamp); Console.Write("CanMsg[{0}].Data = ", i); for (int j = 0; j < CanMsgBuffer[i].DataLen; j++) { Console.Write("{0:X2} ", CanMsgBuffer[i].Data[j]); } Console.WriteLine("\n"); } } else if (CanNum < 0) { Console.WriteLine("Get CAN data error!"); } //延时 System.Threading.Thread.Sleep(100); //释放申请的数据缓冲区 Marshal.FreeHGlobal(pt); } //停止CAN USB2CAN.CAN_StopGetMsg(DevHandle, CANIndex); #endif }
static void Main(string[] args) { usb_device.DEVICE_INFO DevInfo = new usb_device.DEVICE_INFO(); Int32[] DevHandles = new Int32[20]; bool state; Int32 DevNum, ret; Thread CANSendMsgThread = new Thread(new ThreadStart(SendMsgThread)); Thread CANReadMsgThread = new Thread(new ThreadStart(ReadMsgThread)); //扫描查找设备 DevNum = usb_device.USB_ScanDevice(DevHandles); if (DevNum <= 0) { Console.WriteLine("No device connected!"); return; } else { Console.WriteLine("Have {0} device connected!", DevNum); } DevHandle = DevHandles[0]; //打开设备 state = usb_device.USB_OpenDevice(DevHandle); if (!state) { Console.WriteLine("Open device error!"); return; } else { Console.WriteLine("Open device success!"); } //获取固件信息 StringBuilder FuncStr = new StringBuilder(256); state = usb_device.DEV_GetDeviceInfo(DevHandle, ref DevInfo, FuncStr); if (!state) { Console.WriteLine("Get device infomation error!"); return; } else { Console.WriteLine("Firmware Info:"); Console.WriteLine(" Name:" + Encoding.Default.GetString(DevInfo.FirmwareName)); Console.WriteLine(" Build Date:" + Encoding.Default.GetString(DevInfo.BuildDate)); Console.WriteLine(" Firmware Version:v{0}.{1}.{2}", (DevInfo.FirmwareVersion >> 24) & 0xFF, (DevInfo.FirmwareVersion >> 16) & 0xFF, DevInfo.FirmwareVersion & 0xFFFF); Console.WriteLine(" Hardware Version:v{0}.{1}.{2}", (DevInfo.HardwareVersion >> 24) & 0xFF, (DevInfo.HardwareVersion >> 16) & 0xFF, DevInfo.HardwareVersion & 0xFFFF); Console.WriteLine(" Functions:" + DevInfo.Functions.ToString("X8")); Console.WriteLine(" Functions String:" + FuncStr); } //初始化配置CAN USB2CAN.CAN_INIT_CONFIG CANConfig = new USB2CAN.CAN_INIT_CONFIG(); CANConfig.CAN_Mode = 0x80; //正常模式 CANConfig.CAN_ABOM = 0; //禁止自动离线 CANConfig.CAN_NART = 1; //禁止报文重传 CANConfig.CAN_RFLM = 0; //FIFO满之后覆盖旧报文 CANConfig.CAN_TXFP = 1; //发送请求决定发送顺序 //配置波特率,波特率 = 42M/(BRP*(SJW+BS1+BS2)) CANConfig.CAN_BRP = 2; CANConfig.CAN_BS1 = 15; CANConfig.CAN_BS2 = 5; CANConfig.CAN_SJW = 1; ret = USB2CAN.CAN_Init(DevHandle, CANSendIndex, ref CANConfig); if (ret != USB2CAN.CAN_SUCCESS) { Console.WriteLine("Config Send CAN failed!"); return; } else { Console.WriteLine("Config Send CAN Success!"); } ret = USB2CAN.CAN_Init(DevHandle, CANReadIndex, ref CANConfig); if (ret != USB2CAN.CAN_SUCCESS) { Console.WriteLine("Config Read CAN failed!"); return; } else { Console.WriteLine("Config Read CAN Success!"); } //配置过滤器,接收所有数据 USB2CAN.CAN_FILTER_CONFIG CANFilter = new USB2CAN.CAN_FILTER_CONFIG(); CANFilter.Enable = 1; CANFilter.ExtFrame = 0; CANFilter.FilterIndex = 0; CANFilter.FilterMode = 0; CANFilter.MASK_IDE = 0; CANFilter.MASK_RTR = 0; CANFilter.MASK_Std_Ext = 0; ret = USB2CAN.CAN_Filter_Init(DevHandle, CANReadIndex, ref CANFilter); if (ret != USB2CAN.CAN_SUCCESS) { Console.WriteLine("Config CAN Filter failed!"); return; } else { Console.WriteLine("Config CAN Filter Success!"); } //启动CAN接收数据 ret = USB2CAN.CAN_StartGetMsg(DevHandle, CANReadIndex); if (ret != USB2CAN.CAN_SUCCESS) { Console.WriteLine("Start CAN failed!"); return; } else { Console.WriteLine("Start CAN Success!"); } //启动接收数据线程 CANReadMsgFlag = true; CANReadMsgThread.Start(); //启动发送数据线程 CANSendMsgFlag = true; CANSendMsgThread.Start(); //按下回车后结束发送接收线程 Console.ReadLine(); //结束线程 CANSendMsgFlag = false; CANReadMsgFlag = false; CANSendMsgThread.Join(); CANReadMsgThread.Join(); //停止CAN USB2CAN.CAN_StopGetMsg(DevHandle, CANReadIndex); }