public override string Read(SerialPort serialPort) { int tempdatalenth = serialPort.BytesToRead; byte[] tempbytes = new byte[tempdatalenth]; serialPort.Read(tempbytes, 0, tempdatalenth); return(ConvertFrom.ArrayToHexString(tempbytes)); }
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()} 失败!"; }