unsafe public void recordLog(VCI_CAN_OBJ obj) { logStr += "帧ID:0x" + System.Convert.ToString((int)obj.ID, 16); logStr += " 帧格式:"; if (obj.RemoteFlag == 0) logStr += "数据帧 "; else logStr += "远程帧 "; if (obj.ExternFlag == 0) logStr += "标准帧 "; else logStr += "扩展帧 "; if (obj.RemoteFlag == 0) { logStr += "数据: "; byte len = (byte)(obj.DataLen % 9); for (byte j = 0; j < len; j++) { logStr += " " + Convert.ToString(obj.Data[j], 16); } } logStr += Environment.NewLine; }
/// <summary> /// 接收CAN总线上的数据 /// </summary> private void DeviceReceive() { VCI_ERR_INFO pErrInfo = new VCI_ERR_INFO(); while (true) { SpinWait.SpinUntil(() => false, 1);//80 //返回接收缓冲区中尚未被读取的帧数 UInt32 num = VCI_GetReceiveNum(devType, devIndex, devChannel); if (num == 0) { continue; } //分配一次最多接收VCI_GetReceiveNum函数返回值的帧数的数据存储内存空间 IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(VCI_CAN_OBJ)) * (int)num); //返回实际读到的帧数,如返回的为0xFFFFFFFF,则读取数据失败,有错误发生。 UInt32 len = VCI_Receive(devType, devIndex, devChannel, pt, num, -1); if (len == 0xFFFFFFFF) { VCI_ReadErrInfo(devType, devIndex, devChannel, ref pErrInfo); //释放分配的内存空间 Marshal.FreeHGlobal(pt); continue; } //获取CAN总线上的数据并触发事件 for (int i = 0; i < len; i++) { VCI_CAN_OBJ receData = (VCI_CAN_OBJ)Marshal.PtrToStructure((IntPtr)((UInt32)pt + i * Marshal.SizeOf(typeof(VCI_CAN_OBJ))), typeof(VCI_CAN_OBJ)); string _data = String.Empty; byte[] temp = receData.Data; for (int j = 0; j < receData.DataLen; j++) { _data += String.Format("{0:X2}", temp[j]) + " "; } //将接收的数据添加到table中 lock (DataBase) { DataRow _dr = DataBase.NewRow(); _dr["dttype"] = 1; _dr["id"] = "0x" + string.Format("{0:X}", receData.ID); _dr["direction"] = (string)Application.Current.Resources["teReceive"]; _dr["type"] = receData.ExternFlag == 0 ? (string)Application.Current.Resources["teStandardFrame"] : (string)Application.Current.Resources["teExtendedFrame"]; _dr["time"] = DateTime.Now.ToString("MM/dd HH:mm:ss:ffff");//((double)receData.TimeStamp / 10000).ToString().PadRight(9, '0'); _dr["data"] = _data.Trim(); _dr["signal"] = 0; DataBase.Rows.Add(_dr); if (DataBase.Rows.Count > 1000) { for (int n = 0; n < DataBase.Rows.Count - 1000; n++) { DataBase.Rows.RemoveAt(0); } } } } Marshal.FreeHGlobal(pt); } }
public Int32 StandardWrite(Byte[] write_buffer, byte len, int state) { VCI_CAN_OBJ[] vco = new VCI_CAN_OBJ[1]; uint dwRel; vco[0].ID = Consts.MASTER_ID; //switch (state) //{ // case 0x01: // vco[0].ID = Consts.TX_CAN_ID_1; // break; // case 0x02: // vco[0].ID = Consts.TX_CAN_ID_2; // break; // case 0x03: // vco[0].ID = Consts.TX_CAN_ID_3; // break; // case 0x04: // vco[0].ID = Consts.TX_CAN_ID_4; // break; // case 0x05: // vco[0].ID = Consts.TX_CAN_ID_5; // break; //} vco[0].RemoteFlag = 0; vco[0].ExternFlag = 1; vco[0].DataLen = len; vco[0].SendType = 1; //只发一次 unsafe { fixed(VCI_CAN_OBJ *m_recobj1 = &vco[0]) { for (int j = 0; j < 8; j++) { m_recobj1->Data[j] = write_buffer[j]; } } } try { dwRel = VCI_Transmit(m_devtype, m_devind, m_canind, ref vco[0], 1); if (dwRel == 1) { return(1); } else if (dwRel == 0xffffffff) { VCI_ResetCAN(m_devtype, m_devind, m_canind); VCI_ClearBuffer(m_devtype, m_devind, m_canind); //VCI_CloseDevice(m_devtype, m_devind); //VCI_OpenDevice(m_devtype, m_devind, m_canind); return(0); } else { return(0); } } catch (Exception e) { //e.Message; return(-1); } }
/// <summary> /// 接收CAN总线上的数据 /// </summary> private void ReceiveDataFromCAN() { try { if (ZLGInfo.DevType == (uint)ZLGType.VCI_USBCANFD_100U) { ZLGCAN_API.ZCAN_Receive_Data[] can_data = new ZLGCAN_API.ZCAN_Receive_Data[100]; //ZLGCAN_API.ZCAN_Receive_Data[] can_data = new ZLGCAN_API.ZCAN_Receive_Data[500]; uint len; while (true) { lock (locker) { len = ZLGCAN_API.ZCAN_GetReceiveNum(channel_handle, TYPE_CAN); int nRecvIndex = 0; if (len > 0) { int size = Marshal.SizeOf(typeof(ZLGCAN_API.ZCAN_Receive_Data)); IntPtr ptr = Marshal.AllocHGlobal((int)len * size); len = ZLGCAN_API.ZCAN_Receive(channel_handle, ptr, len, 50); byte[] byRecvData = new byte[len * 8]; string canIDStr = string.Empty; for (int i = 0; i < len; ++i) { can_data[i] = (ZLGCAN_API.ZCAN_Receive_Data)Marshal.PtrToStructure( (IntPtr)((UInt32)ptr + i * size), typeof(ZLGCAN_API.ZCAN_Receive_Data)); Buffer.BlockCopy(can_data[i].frame.data, 0, byRecvData, nRecvIndex, 8); nRecvIndex += 8; canIDStr += can_data[i].frame.can_id.ToString("X"); canIDStr += ","; } Marshal.FreeHGlobal(ptr); if (RaiseZLGRecvDataEvent != null) { OnRaiseZLGRecvDataEvent(this, new CANEvent() { eventType = CANEventType.ReceEvent, DataLen = byRecvData[1], listData = new List <byte>(byRecvData), ID = canIDStr.TrimEnd(',') });; //Marshal.FreeHGlobal(ptr); } } } Thread.Sleep(100); } } else if (ZLGInfo.DevType == (uint)ZLGType.PCAN) { PCANInterface.PCANInstance.ReadMessages(); } else { VCI_ERR_INFO pErrInfo = new VCI_ERR_INFO(); while (true) { //为了不占用CPU SpinWait.SpinUntil(() => false, 150); //返回接收缓冲区中尚未被读取的帧数 UInt32 num = VCI_GetReceiveNum(ZLGInfo.DevType, zlgInfo.DevIndex, zlgInfo.DevChannel); if (num == 0) { continue; } zlgInfo.IsSendFrame = false; //分配一次最多接收VCI_GetReceiveNum函数返回值的帧数的数据存储内存空间 IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(VCI_CAN_OBJ)) * (int)num); //返回实际读到的帧数,如返回的为0xFFFFFFFF,则读取数据失败,有错误发生。 UInt32 len = VCI_Receive(ZLGInfo.DevType, zlgInfo.DevIndex, zlgInfo.DevChannel, pt, num, -1); if (len == 0xFFFFFFFF) { VCI_ReadErrInfo(ZLGInfo.DevType, zlgInfo.DevIndex, zlgInfo.DevChannel, ref pErrInfo); //释放分配的内存空间 Marshal.FreeHGlobal(pt); continue; } else { } int nRecvIndex = 0; byte[] byRecvData = new byte[len * 8]; string canIDStr = String.Empty; //获取CAN总线上的数据并触发事件 for (int i = 0; i < len; i++) { VCI_CAN_OBJ recvData = (VCI_CAN_OBJ)Marshal.PtrToStructure((IntPtr)((UInt32)pt + i * Marshal.SizeOf(typeof(VCI_CAN_OBJ))), typeof(VCI_CAN_OBJ)); Buffer.BlockCopy(recvData.Data, 0, byRecvData, nRecvIndex, 8); nRecvIndex += 8; canIDStr += recvData.ID.ToString("X"); canIDStr += ","; } if (RaiseZLGRecvDataEvent != null) { OnRaiseZLGRecvDataEvent(this, new CANEvent() { eventType = CANEventType.ReceEvent, DataLen = byRecvData[2], listData = new List <byte>(byRecvData), ID = canIDStr.TrimEnd(',') }); } VCI_ClearBuffer(ZLGInfo.DevType, zlgInfo.DevIndex, zlgInfo.DevChannel); Marshal.FreeHGlobal(pt); } } } catch (Exception ex) { string str = ex.Message; } }
static extern uint VCI_Transmit(uint DeviceType, uint DeviceInd, uint CANInd, ref VCI_CAN_OBJ pSend, uint Len);
/// <summary> /// 发送数据 /// </summary> /// <param name="buffer"></param> void IDataCommunication.SendData(byte[] buffer) { VCI_CAN_OBJ frameinfo = new VCI_CAN_OBJ(); frameinfo.Data = new byte[buffer.Length - 4]; for (int i = 4; i < buffer.Length; i++) { frameinfo.Data[i - 4] = buffer[i]; } frameinfo.DataLen = BitConverter.GetBytes(buffer.Length - 4)[0]; frameinfo.RemoteFlag = 0; frameinfo.ExternFlag = 0; frameinfo.SendType = 0; frameinfo.ID = Convert.ToUInt32((buffer[3] << 8) + buffer[2]); frameinfo.Reserved = new byte[3]; if (VCI_Transmit(DEVICETYPE, DeviceInd, CNDInd, ref frameinfo, 1) != STATUS_OK) { WriteLog("写入失败!"); if (VCI_Transmit(DEVICETYPE, DeviceInd, CNDInd, ref frameinfo, 1) != STATUS_OK)//如果出错,再写一次 { WriteLog("二次写入失败!"); } } }
unsafe public static String CanReceive() { UInt32 res = VCI_GetReceiveNum(4, 0, 0); if (res == 0) { return(""); } UInt32 con_maxlen = 2500; IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(VCI_CAN_OBJ)) * (Int32)con_maxlen); res = VCI_Receive(4, 0, 0, pt, con_maxlen, 0); String str = ""; for (UInt32 i = 0; i < res; i++) { VCI_CAN_OBJ obj = (VCI_CAN_OBJ)Marshal.PtrToStructure((IntPtr)((UInt32)pt + i * Marshal.SizeOf(typeof(VCI_CAN_OBJ))), typeof(VCI_CAN_OBJ)); str = "接收到数据: "; str += " 帧ID:0x" + System.Convert.ToString((Int32)obj.ID, 16); str += " 帧格式:"; if (obj.RemoteFlag == 0) { str += "数据帧 "; } else { str += "远程帧 "; } if (obj.ExternFlag == 0) { str += "标准帧 "; } else { str += "扩展帧 "; } ////////////////////////////////////////// if (obj.RemoteFlag == 0) { str += "数据: "; byte len = (byte)(obj.DataLen % 9); byte j = 0; if (j++ < len) { str += " " + System.Convert.ToString(obj.Data[0], 16); } if (j++ < len) { str += " " + System.Convert.ToString(obj.Data[1], 16); } if (j++ < len) { str += " " + System.Convert.ToString(obj.Data[2], 16); } if (j++ < len) { str += " " + System.Convert.ToString(obj.Data[3], 16); } if (j++ < len) { str += " " + System.Convert.ToString(obj.Data[4], 16); } if (j++ < len) { str += " " + System.Convert.ToString(obj.Data[5], 16); } if (j++ < len) { str += " " + System.Convert.ToString(obj.Data[6], 16); } if (j++ < len) { str += " " + System.Convert.ToString(obj.Data[7], 16); } } } Marshal.FreeHGlobal(pt); return(str); }
static extern UInt32 VCI_Receive(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, ref VCI_CAN_OBJ pReceive, UInt32 Len, Int32 WaitTime);
unsafe private void ReceiveDataHandle(UInt32 canId) { String str = ""; UInt32 res = new UInt32(); res = DllAdapte.VCI_GetReceiveNum(mDevType, mDevInd, canId); if (res == 0) { return; } //res = DllAdapte.VCI_Receive(mDevType, mDevInd, mCanInd, ref mRecObj[0],50, 100); UInt32 con_maxlen = 50; IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(VCI_CAN_OBJ)) * (Int32)con_maxlen); res = DllAdapte.VCI_Receive(mDevType, mDevInd, canId, pt, con_maxlen, 100); for (UInt32 i = 0; i < res; i++) { VCI_CAN_OBJ obj = (VCI_CAN_OBJ)Marshal.PtrToStructure((IntPtr)((UInt32)pt + i * Marshal.SizeOf(typeof(VCI_CAN_OBJ))), typeof(VCI_CAN_OBJ)); //str = "接收到数据: "; str += " 帧ID:0x" + System.Convert.ToString((Int32)obj.ID, 16); str += " 帧格式:"; if (obj.RemoteFlag == 0) { str += "数据帧 "; } else { str += "远程帧 "; } if (obj.ExternFlag == 0) { str += "标准帧 "; } else { str += "扩展帧 "; } if (obj.RemoteFlag == 0) { str += "数据: "; byte len = (byte)(obj.DataLen % 9); for (byte j = 0; j < len; j++) { if (j == 0) { str += obj.Data[j].ToString("X2"); } else { str += " " + obj.Data[j].ToString("X2"); //System.Convert.ToString(obj.Data[j], 16); } } } if (mPauseFlag == 0) { RevListBox.Items.Add(str); RevListBox.SelectedIndex = RevListBox.Items.Count - 1; } str = string.Empty; } Marshal.FreeHGlobal(pt); }
static extern uint VCI_Receive(uint DeviceType, uint DeviceInd, uint CANInd, ref VCI_CAN_OBJ pReceive, uint Len, int WaitTime);
unsafe public void torque_input(int index, bool b) { if (m_bOpen == 0) { return; } VCI_CAN_OBJ sendobj = new VCI_CAN_OBJ(); sendobj.RemoteFlag = 0; sendobj.ID = Motor[index].ID; sendobj.ExternFlag = Motor[index].FrameFormat; string v = ""; if (b == enable) { switch (index) { case 0: v = textBox_tq_LF.Text; break; case 1: v = textBox_tq_LM.Text; break; case 2: v = textBox_tq_LR.Text; break; case 3: v = textBox_tq_RF.Text; break; case 4: v = textBox_tq_RM.Text; break; case 5: v = textBox_tq_RR.Text; break; } } else { v = "0"; } //*******************************************// v = v.Replace(" ", ""); if ((v.Length % 2) != 0) { v = '0' + v; } sendobj.DataLen = (byte)(v.Length / 2); for (int i = 0; i < sendobj.DataLen; i++) { sendobj.Data[i] = Convert.ToByte(v.Substring(i * 2, 2), 16); } //************************************************// if (VCI_Transmit(m_devtype, m_devind, m_canind, ref sendobj, 1) == 0) { MessageBox.Show("发送失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
unsafe protected string ReceiveData(UInt32 FilterID, int timeout, uint deviceType, uint deviceIndex, uint cANIndex) { string dataStrList = "读取失败!"; List <string> dataStringList = new List <string>(); var cancelTokenSource = new CancellationTokenSource(timeout); if (IsOpen) //是否打开CAN { List <uint> Data_Frame = new List <uint>(); while (!cancelTokenSource.IsCancellationRequested)//设置读取超时 { //uint num = VCI_GetReceiveNum(deviceType, deviceIndex, cANIndex); uint con_maxlen = 100; int size = Marshal.SizeOf(typeof(VCI_CAN_OBJ)); //获取结构体占用空间大小 IntPtr pt = Marshal.AllocHGlobal(size * (Int32)con_maxlen); //声明一个同样大小的空间的指针或句柄 UInt32 result = VCI_Receive(deviceType, deviceIndex, cANIndex, pt, con_maxlen, 100); //返回最大100幁数据 for (UInt32 i = 0; i < result; i++) { VCI_CAN_OBJ obj = (VCI_CAN_OBJ)Marshal.PtrToStructure((IntPtr)((uint)pt + i * size), typeof(VCI_CAN_OBJ)); //将结构体放到这个空间中 if (obj.ID == FilterID) //判断是否为过滤的ID { if (obj.RemoteFlag == 0) //判断是否为远程幁 { //Data_Frame.Add(obj.ID); byte len = (byte)(obj.DataLen % 9); byte j = 0; if (j++ < len) { for (int d = 0; d < len; d++) { Data_Frame.Add(obj.Data[d]); } Data_Frame.RemoveRange(0, 2); } } dataStrList = ConvertFrom.ArrayToHexString(Data_Frame.ToArray()); } } #region old //dataStr = "帧ID: "; //dataStr = Convert.ToString(obj.ID, 16); // if (obj.ID == FilterID) // { // if (obj.RemoteFlag == 0) // { // //dataStr += " 数据: "; // byte len = (byte)(obj.DataLen % 9); // byte j = 0; // if (j++ < len) // { // for (int d = 0; d < len; d++) // { // dataStr += " " + string.Format("{0:X2}", obj.Data[d]);//01 00 00 00 00 00 00 08 // } // } // dataStringList.Add(dataStr.ToUpper()); // } // } // //Console.WriteLine(dataStr.ToUpper()); //} //if (dataStringList.Count > 0) //{ // foreach (var item in dataStringList) // { // dataStrList += item + "\r\n"; // } // return dataStrList; //}//判断是否有 指定的数据 //else //{ // dataStringList = null; // dataStrList = ""; // //ReceiveData(FilterID, timeout); // return $"CAN1 读取帧ID: {Convert.ToString(FilterID, 16).ToUpper()} 失败!"; //} #endregion } return(dataStrList); } return(dataStrList); //return $"CAN1 读取帧ID: {Convert.ToString(FilterID, 16).ToUpper()} 失败!"; }
/// <summary> /// 发送单帧信息 /// </summary> /// <param name="ID"></param> /// <param name="canIndex"></param> /// <param name="data"></param> /// <param name="dataLength"></param> public void SingleTransmit(VCI_CAN_OBJ obj) { try { if (ZLGInfo.DevType == (uint)ZLGType.VCI_USBCANFD_100U) { ZLGCAN_API.ZCAN_Transmit_Data can_data = new ZLGCAN_API.ZCAN_Transmit_Data(); obj.ExternFlag = 1; can_data.frame.can_id = MakeCanId(obj.ID, obj.ExternFlag, 0, 0); can_data.frame.data = new byte[8]; Buffer.BlockCopy(obj.Data, 0, can_data.frame.data, 0, obj.DataLen); can_data.frame.can_dlc = (byte)obj.Data.Length; can_data.transmit_type = obj.SendType; IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(can_data)); Marshal.StructureToPtr(can_data, ptr, true); BoqiangH5Repository.CSVFileHelper.WriteLogs("log", "发送", CSVFileHelper.ToHexStrFromByte(can_data.frame.data, false), false); uint res = ZLGCAN_API.ZCAN_Transmit(channel_handle, ptr, 1); Marshal.FreeHGlobal(ptr); if (res == 0) { _dispatcher.BeginInvoke(new Action(delegate() { })); AbortThread(); return; } else { OnRaiseZLGCommunicateEvent(this, new CANEvent() { eventType = CANEventType.SendEvent, //ID = can_data.frame.can_id, DataLen = can_data.frame.data[2], listData = new List <byte>(can_data.frame.data) }); } } else if (ZLGInfo.DevType == (uint)ZLGType.PCAN) { bool isRemote = false; if (obj.RemoteFlag == 0x00) { isRemote = false; } else { isRemote = true; } BoqiangH5Repository.CSVFileHelper.WriteLogs("log", "发送", CSVFileHelper.ToHexStrFromByte(obj.Data, false), false); PCANInterface.PCANInstance.PCAN_WriteData(obj.ID, obj.DataLen, isRemote, obj.Data); } else { //在非托管内存中分配一个VCI_CAN_OBJ结构体大小的内存空间 IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(VCI_CAN_OBJ)) * 1); VCI_CAN_OBJ pSend = (VCI_CAN_OBJ)Marshal.PtrToStructure((IntPtr)((UInt32)pt), typeof(VCI_CAN_OBJ)); //IsSendFrame = true; pSend.ID = obj.ID; pSend.SendType = obj.SendType; pSend.RemoteFlag = obj.RemoteFlag; pSend.ExternFlag = obj.ExternFlag; pSend.DataLen = obj.DataLen; string strSendDdata = String.Empty; byte[] temp = obj.Data; for (int j = 0; j < pSend.DataLen; j++) { strSendDdata += String.Format("{0:X2}", temp[j]) + " "; } for (int i = 0; i < obj.DataLen; i++) { pSend.Data[i] = obj.Data[i]; } if (pSend.Data[0] == 0x30 && pSend.Data[1] == 0xff && pSend.Data[3] == 0x00) { } BoqiangH5Repository.CSVFileHelper.WriteLogs("log", "发送", CSVFileHelper.ToHexStrFromByte(pSend.Data, false), false); //返回实际发送成功的帧数 UInt32 res = VCI_Transmit(ZLGInfo.DevType, zlgInfo.DevIndex, zlgInfo.DevChannel, ref pSend, 1); if (res == 0) { _dispatcher.BeginInvoke(new Action(delegate() { })); AbortThread(); return; } else { OnRaiseZLGCommunicateEvent(this, new CANEvent() { eventType = CANEventType.SendEvent, //ID = pSend.ID, DataLen = pSend.DataLen, listData = new List <byte>(pSend.Data) }); } Marshal.FreeHGlobal(pt); } } catch (Exception ex) { } }
/// <summary> /// 发送单帧信息 /// </summary> /// <param name="ID"></param> /// <param name="canIndex"></param> /// <param name="data"></param> /// <param name="dataLength"></param> public void SingleTransmit() { if (sendData.ToString() == "" || sendID.ToString() == "") { return; } string[] _data = sendData.Trim().Split(' '); //在非托管内存中分配一个VCI_CAN_OBJ结构体大小的内存空间——————此方法似乎不行!!! //IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(VCI_CAN_OBJ)) * 1); //VCI_CAN_OBJ pSend = (VCI_CAN_OBJ)Marshal.PtrToStructure((IntPtr)((UInt32)pt), typeof(VCI_CAN_OBJ)); VCI_CAN_OBJ pSend = new VCI_CAN_OBJ(); //初始化Data为8个字节 pSend.Data = new byte[8]; pSend.DataLen = System.Convert.ToByte(_data.Length); for (int i = 0; i < _data.Length; i++) { pSend.Data[i] = System.Convert.ToByte(_data[i], 16); } pSend.ExternFlag = 1; pSend.RemoteFlag = 0; pSend.SendType = 0; pSend.TimeFlag = 0; pSend.TimeStamp = 0x00; pSend.ID = Convert.ToUInt32(sendID, 16); //返回实际发送成功的帧数 UInt32 res = VCI_Transmit(devType, devIndex, devChannel, ref pSend, 1); if (res == 0) { _dispatcher.BeginInvoke(new Action(delegate() { DXMessageBox.Show((string)Application.Current.Resources["tePromptText3"], (string)Application.Current.Resources["tePrompt"], MessageBoxButton.OK, MessageBoxImage.Warning); })); AbortThread(); return; } //将接收的数据添加到table中 lock (DataBase) { DataRow _dr = DataBase.NewRow(); _dr["dttype"] = 0; _dr["id"] = "0x" + sendID; _dr["direction"] = (string)Application.Current.Resources["coSend"]; _dr["type"] = pSend.ExternFlag == 0 ? (string)Application.Current.Resources["teStandardFrame"] : (string)Application.Current.Resources["teExtendedFrame"]; _dr["time"] = DateTime.Now.ToString("MM/dd HH:mm:ss:ffff"); _dr["data"] = sendData; _dr["signal"] = 0; DataBase.Rows.Add(_dr); if (DataBase.Rows.Count > 1000) { for (int i = 0; i < DataBase.Rows.Count - 1000; i++) { DataBase.Rows.RemoveAt(0); } } } //Marshal.FreeHGlobal(pt); }
unsafe private void ReceiveUpData() { String idStr = ""; string dataStr = string.Empty; UInt32 res = new UInt32(); UInt32 canId = 0; res = DllAdapte.VCI_GetReceiveNum(mDevType, mDevInd, canId); if (res == 0) { return; } //res = DllAdapte.VCI_Receive(mDevType, mDevInd, mCanInd, ref mRecObj[0],50, 100); UInt32 con_maxlen = 50; IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(VCI_CAN_OBJ)) * (Int32)con_maxlen); res = DllAdapte.VCI_Receive(mDevType, mDevInd, canId, pt, con_maxlen, 100); for (UInt32 i = 0; i < res; i++) { VCI_CAN_OBJ obj = (VCI_CAN_OBJ)Marshal.PtrToStructure((IntPtr)((UInt32)pt + i * Marshal.SizeOf(typeof(VCI_CAN_OBJ))), typeof(VCI_CAN_OBJ)); idStr = System.Convert.ToString((Int32)obj.ID, 16); if (idStr.Contains("1441abaa")) // && mPauseFlag == 0 { if (obj.Data[1] == (byte)0xcc) { mUpCmd = UpgradeCmd.CmdUpgrade; sendListBox.Items.Add("同主机Ping成功!"); } else { mUpCmd = UpgradeCmd.CmdPing; } } if (idStr.Contains("1442abaa")) // && mPauseFlag == 0 { if (obj.Data[1] == (byte)0xcc) { mFrameSendFlag = 0; mUpgradeFlag = 0; mUpCmd = UpgradeCmd.CmdNone; //timerSend.Enabled = false; //重启后要先关闭发送定时器 sendListBox.Items.Add("主机重启成功!"); } } if (idStr.Contains("1443abaa")) // && mPauseFlag == 0 { if (obj.Data[1] == (byte)0xcc) { mUpCmd = UpgradeCmd.CmdSendData; sendListBox.Items.Add("发送升级地址成功!"); } else if (obj.Data[1] == (byte)0x33) { mUpgradeFlag = 0; mUpCmd = UpgradeCmd.CmdNone; sendListBox.Items.Add("升级下载地址不符合FLASH空间大小!"); } else { mUpCmd = UpgradeCmd.CmdUpgrade; } } if (idStr.Contains("1444abaa")) // && mPauseFlag == 0 { if (obj.Data[1] == (byte)0x33) { mRevFrameNum = 0; mUpgradeFlag = 0; progressBar.Visible = false; mUpCmd = UpgradeCmd.CmdRun; sendListBox.Items.Add("升级成功!"); mBinReader.Close(); mBinStream.Close(); } else if (obj.Data[1] == (byte)0xcc) { mUpCmd = UpgradeCmd.CmdSendData; } else { if (mSendDone == 1) { progressBar.Visible = false; mSendDone = 0; //标志复位 mUpgradeFlag = 0; //mUpCmd = UpgradeCmd.CmdRun; sendListBox.Items.Add("数据发送完成但未收到主机应答信号!"); } else { mUpgradeFlag = 0; mUpCmd = UpgradeCmd.CmdNone; sendListBox.Items.Add("提示:主机在本帧中有丢失数据!"); } } } if (obj.RemoteFlag == 0) { byte len = (byte)(obj.DataLen % 9); for (byte j = 0; j < len; j++) { if (j == 0) { dataStr += obj.Data[j].ToString("X2"); } else { dataStr += " " + obj.Data[j].ToString("X2"); //System.Convert.ToString(obj.Data[j], 16); } } } if (mPauseFlag == 0) { if (mFrameSendFlag == 1) { mRevFrameNum++; } RevListBox.Items.Add("报文ID: 0x" + idStr + " 接收数据: " + dataStr + " 接收帧数: " + mRevFrameNum.ToString("X4")); RevListBox.SelectedIndex = RevListBox.Items.Count - 1; } dataStr = string.Empty; } Marshal.FreeHGlobal(pt); }
/// <summary> /// 发送数据 /// </summary> /// <param name="id">发送ID</param> /// <param name="data">发送数据</param> public unsafe void SendData(string id, string data) { Debug.WriteLine("id:" + id + "data:" + data); if (!connected) { return; } var SendID = "0x00000" + id.ToUpper(); var sendobj = new VCI_CAN_OBJ { SendType = 0, RemoteFlag = 0, ExternFlag = 0, ID = Convert.ToUInt32(SendID, 16) }; if (data.Length != 23) { var length = (23 - data.Length) / 3; for (int j = 0; j < length; j++) { data += " FF"; } } var len = (data.Length + 1) / 3; sendobj.DataLen = Convert.ToByte(len); var strdata = data; //Debug.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + " 7E2:" + strdata); var i = -1; if (i++ < len - 1) { sendobj.Data[0] = Convert.ToByte("0x" + strdata.Substring(i * 3, 2), 16); } if (i++ < len - 1) { sendobj.Data[1] = Convert.ToByte("0x" + strdata.Substring(i * 3, 2), 16); } if (i++ < len - 1) { sendobj.Data[2] = Convert.ToByte("0x" + strdata.Substring(i * 3, 2), 16); } if (i++ < len - 1) { sendobj.Data[3] = Convert.ToByte("0x" + strdata.Substring(i * 3, 2), 16); } if (i++ < len - 1) { sendobj.Data[4] = Convert.ToByte("0x" + strdata.Substring(i * 3, 2), 16); } if (i++ < len - 1) { sendobj.Data[5] = Convert.ToByte("0x" + strdata.Substring(i * 3, 2), 16); } if (i++ < len - 1) { sendobj.Data[6] = Convert.ToByte("0x" + strdata.Substring(i * 3, 2), 16); } if (i++ < len - 1) { sendobj.Data[7] = Convert.ToByte("0x" + strdata.Substring(i * 3, 2), 16); } var nTimeOut = 3000; //Debug.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + " CAN开始发送数据"); VCI_SetReference(m_devtype, m_devind, m_canind, 4, (byte *)&nTimeOut); // Debug.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff ") + id + ": " + strdata); //Debug.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + " CAN结束发送数据"); if (VCI_Transmit(m_devtype, m_devind, m_canind, ref sendobj, 1) == 0) { if (connected) { if (!messageBoxNotice) { messageBoxNotice = true; if (MessageBox.Show("TCU指令发送失败,请检查TCU是否正常连接", "Confirmation", MessageBoxButton.OK) == MessageBoxResult.Yes) { messageBoxNotice = false; } } //MessageBox.Show("TCU指令发送失败,请检查TCU是否正常连接"); } } }
public uint Receive(uint can_index, ref VCI_CAN_OBJ obj_ref, uint obj_length = VCI_MAX_OBJECT_LENGTH, int rec_wait_time = VCI_RECEIVE_WAIT_TIME) { return(VCI_Receive(m_devtype, m_devind, can_index, ref obj_ref, obj_length, rec_wait_time)); }
static extern UInt32 VCI_Transmit(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, ref VCI_CAN_OBJ pSend, UInt32 Len);
public uint Transmit(uint can_index, ref VCI_CAN_OBJ obj_ref, uint obj_length) { return(VCI_Transmit((uint)m_devtype, m_devind, can_index, ref obj_ref, obj_length)); }
public static extern uint VCI_Transmit(uint DeviceType, uint DeviceInd, uint CANInd, ref VCI_CAN_OBJ pSend, uint Len);
unsafe private void timer_rec_Tick(object sender, EventArgs e) { UInt32 res = new UInt32(); res = VCI_GetReceiveNum(m_devtype, m_devind, m_canind); if (res == 0) { return; } //res = VCI_Receive(m_devtype, m_devind, m_canind, ref m_recobj[0],50, 100); ///////////////////////////////////// UInt32 con_maxlen = 50; IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(VCI_CAN_OBJ)) * (Int32)con_maxlen); res = VCI_Receive(m_devtype, m_devind, m_canind, pt, con_maxlen, 100); //////////////////////////////////////////////////////// String str = ""; for (UInt32 i = 0; i < res; i++) { VCI_CAN_OBJ obj = (VCI_CAN_OBJ)Marshal.PtrToStructure((IntPtr)((UInt32)pt + i * Marshal.SizeOf(typeof(VCI_CAN_OBJ))), typeof(VCI_CAN_OBJ)); str = "接收到数据: "; str += " 帧ID:0x" + System.Convert.ToString((Int32)obj.ID, 16); str += " 帧格式:"; if (obj.RemoteFlag == 0) { str += "数据帧 "; } else { str += "远程帧 "; } if (obj.ExternFlag == 0) { str += "标准帧 "; } else { str += "扩展帧 "; } ////////////////////////////////////////// if (obj.RemoteFlag == 0) { str += "数据: "; byte len = (byte)(obj.DataLen % 9); byte j = 0; if (j++ < len) { str += " " + System.Convert.ToString(obj.Data[0], 16); } if (j++ < len) { str += " " + System.Convert.ToString(obj.Data[1], 16); } if (j++ < len) { str += " " + System.Convert.ToString(obj.Data[2], 16); } if (j++ < len) { str += " " + System.Convert.ToString(obj.Data[3], 16); } if (j++ < len) { str += " " + System.Convert.ToString(obj.Data[4], 16); } if (j++ < len) { str += " " + System.Convert.ToString(obj.Data[5], 16); } if (j++ < len) { str += " " + System.Convert.ToString(obj.Data[6], 16); } if (j++ < len) { str += " " + System.Convert.ToString(obj.Data[7], 16); } } listBox_Info.Items.Add(str); listBox_Info.SelectedIndex = listBox_Info.Items.Count - 1; } Marshal.FreeHGlobal(pt); }
/// <summary> /// 接收数据 /// </summary> private void Recieve() { uint len = 0; VCI_ERR_INFO errinfo = new VCI_ERR_INFO(); VCI_CAN_OBJ[] frameinfos = new VCI_CAN_OBJ[1]; while (isOpen) { try { do { len = VCI_Receive(DEVICETYPE, DeviceInd, CNDInd, ref frameinfos[0], 1, 0); if (len <= 0) { VCI_ReadErrInfo(DEVICETYPE, DeviceInd, CNDInd, ref errinfo); } else { foreach (var frameinfo in frameinfos) { if (frameinfo.DataLen > 0 && frameinfo.Data != null) { if (frameinfo.Data.Length < frameinfo.DataLen) { WriteLog("数据格式不正确!"); } buffer.Add(0xFA);//加数据包头 //buffer.Add(0xe1); //buffer.Add(0x08); //buffer.Add(0); //buffer.Add(0); for (int i = 1; i < frameinfo.DataLen + 1; i++) { buffer.Add(frameinfo.Data[i - 1]); } DataRecievedArgs args = new DataRecievedArgs(); args.Buffer = buffer; //System.Diagnostics.Debug.WriteLine(frameinfo.Data[7]); //args.Buffer1 = new byte[frameinfo.DataLen]; ////args.Buffer[0] = 0xe1; ////args.Buffer[1] = 0x08; ////args.Buffer[2] = 0; ////args.Buffer[3] = 0; //for (int i = 0; i < frameinfo.DataLen; i++) //{ // args.Buffer1[i] = frameinfo.Data[i]; //} if (DataReceived != null) DataReceived(args); } } } } while (len <= 0); } catch { } //System.Diagnostics.Debug.WriteLine("end:" + DateTime.Now.Millisecond); //VCI_ClearBuffer(VCI_USBCAN1, DeviceInd, CNDInd); Thread.Sleep(1); } }
public UInt32 Receive(ref VCI_CAN_OBJ pReceive) { return(VCI_Receive(m_devtype, m_devind, m_canind, ref pReceive, 1000, 100)); }
/// <summary> /// 发送数据 /// </summary> /// <param name="buffer"></param> void IDataCommunication.SendData(byte[] buffer) { lock (this) { VCI_CAN_OBJ frameinfo = new VCI_CAN_OBJ(); frameinfo.Data = new byte[buffer.Length - 4]; for (int i = 4; i < buffer.Length; i++) { frameinfo.Data[i - 4] = buffer[i]; } frameinfo.DataLen = BitConverter.GetBytes(buffer.Length - 4)[0]; frameinfo.RemoteFlag = 0; frameinfo.ExternFlag = 0; frameinfo.SendType = 0; frameinfo.ID = Convert.ToUInt32((buffer[3] << 8) + buffer[2]); frameinfo.Reserved = new byte[3]; if (VCI_Transmit(VCI_USBCAN1, DeviceInd, CNDInd, ref frameinfo, 1) != STATUS_OK) { WriteLog("写入失败!"); if (VCI_Transmit(VCI_USBCAN1, DeviceInd, CNDInd, ref frameinfo, 1) != STATUS_OK)//如果出错,再写一次 { WriteLog("二次写入失败!"); } } Thread.Sleep(10); } //LogManager.Debug(buffer[0].ToString("X2") + " " + buffer[1].ToString("X2") + " " + buffer[2].ToString("X2") + " " + buffer[3].ToString("X2") + " " + buffer[4].ToString("X2") + " " // + buffer[5].ToString("X2") + " " + buffer[6].ToString("X2") + " " + buffer[7].ToString("X2") + " " // + buffer[8].ToString("X2") + " " + buffer[9].ToString("X2") + " " + buffer[10].ToString("X2") + " " + buffer[11].ToString("X2")); }