Exemplo n.º 1
0
 public static extern ECANStatus Receive(
     UInt32 DeviceType,
     UInt32 DeviceInd,
     UInt32 CANInd,
     out CAN_OBJ Receive,
     UInt32 length,
     UInt32 WaitTime);
        /// <summary>
        /// Get a frame from specified CAN ID and the frame from other ID will be ignored.
        /// </summary>
        /// <param name="canObj">return the completed frame</param>
        /// <param name="canID">the desired CAN ID</param>
        /// <param name="timeOut">The time out of receiving frames</param>
        /// <returns>read frame successfully or not</returns>
        public bool ReceiveSingleMessageByID(out CAN_OBJ canObj, uint canID, int timeOut)
        {
            canObj = new CAN_OBJ();

            try
            {
                DateTime dtStart = DateTime.Now;
                while ((DateTime.Now - dtStart).TotalMilliseconds < timeOut)
                {
                    if (false == BufferEmpty())
                    {
                        Thread.Sleep(5);                        //wait for 5ms
                        canObj = ReadFrame();
                        if (canObj.data != null && canObj.ID == canID)
                        {
                            return(true);
                        }
                    }
                }                 //check again if unread frame from bus
            }
            catch (Exception ex)
            {
                if (true == ex.Message.StartsWith("Failed at CAN receive: "))
                {
                    throw new Exception(ex.Message);
                }
                else
                {
                    throw new Exception(string.Format("Failed at receive message method with message: {0}", ex.Message));
                }
            }
            return(false);
        }
        public bool ReceiveSingleMessage(out CAN_OBJ canObj, int timeOut)
        {
            canObj = new CAN_OBJ();

            try
            {
                DateTime dtStart = DateTime.Now;
                while ((DateTime.Now - dtStart).TotalMilliseconds < timeOut)
                {
                    if (false == BufferEmpty())
                    {
                        {
                            canObj = ReadFrame();
                            if (canObj.DataLen > 0)
                            {
                                return(true);
                            }
                        }
                    }
                    Thread.Sleep(5);
                }                 //unread frame in instrument
            }
            catch (Exception ex)
            {
                if (true == ex.Message.StartsWith("Failed at CAN receive: "))
                {
                    throw new Exception(ex.Message);
                }
                else
                {
                    throw new Exception(string.Format("Failed at receive single message method with message: {0}", ex.Message));
                }
            }
            return(true);
        }
        /// <summary>
        /// Basicaly function to read a frame.
        /// </summary>
        /// <returns>return the completed frame from CAN bus </returns>
        private CAN_OBJ ReadFrame()
        {
            CAN_OBJ frame = new CAN_OBJ();

            if (false == BufferEmpty())
            {
                lock (this)
                {
                    //Console.WriteLine("[{0}] - [ReadFrame] - start");
                    uint uiLen = 1;
                    try
                    {
                        lock (this)
                        {
                            if (ECANDLL.Receive(Setting.DeviceType, Setting.DeviceID, Setting.Channel, out frame, uiLen, 1) != ECANStatus.STATUS_OK)
                            {
                                string strErrInfo = ReadError();
                                throw new Exception(string.Format("Failed at CAN receive: {0}", strErrInfo));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (true == ex.Message.StartsWith("Failed at can receive:"))
                        {
                            throw new Exception(ex.Message);
                        }
                        throw new Exception(string.Format("Failure happeded at receive method: {0}", ex.Message));
                    }
                }
            }

            return(frame);
        }
Exemplo n.º 5
0
        public ulong GetBitsFromFrame(CAN_OBJ canOBJ, uint startBit, uint length)
        {
            byte[] byteData = new byte[canOBJ.DataLen];
            //get all data from frame
            canOBJ.data.CopyTo(byteData, 0);

            return(GetBitsFromFrame(byteData, startBit, length));
        }
Exemplo n.º 6
0
        public bool SendMessage(CAN_OBJ canObj)
        {
            byte[] byteData = new byte[canObj.DataLen];
            canObj.data.CopyTo(byteData, 0);

            Console.WriteLine();
            return(SendFrame(canObj, byteData));
        }
Exemplo n.º 7
0
        //Send data to BUS
        /// <summary>
        /// Send command (data) with specified ID
        /// </summary>
        /// <param name="ID">ID string in hex format without space</param>
        /// <param name="command">Hex string of command/data, space between bytes</param>
        /// <returns>sent successfully or not</returns>
        public bool SendMessage(string ID, string command)
        {
            int iLen = 0;

            string[] strBytes = null;
            byte[]   data     = null;
            CAN_OBJ  canObj   = new CAN_OBJ();

            //convert hex string to byte[]
            if (command.IndexOf(@" ") > 0)
            {
                iLen     = (command.Length + 1) / 3;             //space between bytes. e.g. "FE 00"
                strBytes = command.Split(' ');
                data     = new byte[iLen];
            }
            else
            {
                iLen     = command.Length / 2;            //no space in hex string. e.g."FE00"
                strBytes = new string[iLen];
                for (int i = 0, index = 0; i + 1 < command.Length; i += 2, index++)
                {
                    strBytes[index] = command.Substring(i, 2);
                }
                data = new byte[iLen];
            }
            for (int index = 0; index < iLen; index++)
            {
                data[index] = Convert.ToByte(Int32.Parse(strBytes[index], System.Globalization.NumberStyles.HexNumber));                //convert the HEX number string to a character and then to ASIC
            }
            UInt32 uiID = Convert.ToUInt32(ID, 16);

            if (uiID > 0x7FF)
            {
                canObj.ExternFlag = 0x1;
            }
            else
            {
                canObj.ExternFlag = 0x0;
            }
            canObj.ID         = uiID;
            canObj.RemoteFlag = 0;
            canObj.Reserved   = null;
            canObj.SendType   = 0;
            canObj.TimeFlag   = 0x0;
            canObj.TimeStamp  = 0;
            canObj.data       = new byte[data.Length];
            data.CopyTo(canObj.data, 0);
            canObj.DataLen = (byte)data.Length;

            return(SendFrame(canObj, data));
        }
Exemplo n.º 8
0
        //Send 8-byte to CAN BUS
        private bool SendFrame(CAN_OBJ canOBJ, byte[] message)
        {
            CAN_OBJ[] objMessage = new CAN_OBJ[2];
            UInt16    uLen       = 0;
            int       iSizeOfObj = 0;

            try
            {
                byte[] byteData = new byte[8];
                for (int i = 0; i < byteData.Length; i++)
                {
                    if (i < message.Length)
                    {
                        byteData[i] = message[i];
                    }
                    else
                    {
                        byteData[i] = 0x0;
                    }
                }
                objMessage[0] = canOBJ;
                //objMessage[0].data = message;
                objMessage[0].data = byteData;
                objMessage[1]      = objMessage[0];

                uLen       = 1;
                iSizeOfObj = System.Runtime.InteropServices.Marshal.SizeOf(objMessage[0]);
                lock (this)
                {
                    string strData = BitConverter.ToString(canOBJ.data).Replace("-", string.Empty);
                    //Console.WriteLine("SendFrame: {0:X} : {1:X}", canOBJ.ID, strData);
                    if (ECANDLL.Transmit(Setting.DeviceType, Setting.DeviceID, Setting.Channel, objMessage, (ushort)uLen) != ECANStatus.STATUS_OK)
                    {
                        string strErrInfo = ReadError();
                        throw new Exception(string.Format("Failed at CAN transmit: {0}", strErrInfo));
                    }
                }
            }
            catch (Exception ex)
            {
                if (true == ex.Message.StartsWith("Failed at CAN transmit:"))
                {
                    throw new Exception(ex.Message);
                }
                throw new Exception(string.Format("Failure happeded at send method: {0}", message));
            }

            return(true);
        }
        /// <summary>
        /// Get data from specified CAN ID and the frames from other ID will be ignored.
        /// </summary>
        /// <param name="DataList">return the completed frames</param>
        /// <param name="canID">the desired CAN ID</param>
        /// <param name="duration">read data within specified duration, unit in ms</param>
        /// <param name="timeOut">The time out of receiving frames</param>
        /// <param name="clearBufferBeforeRead">whether clear buffer of CAN receiver and received global variable</param>
        /// <returns>read frames successfully or not</returns>
        public bool ReceiveMessagesByID(out List <CAN_OBJ> DataList, uint canID, int timeOut, bool clearBufferBeforeRead)
        {
            DataList = new List <CAN_OBJ>();
            CAN_OBJ objFrame = new CAN_OBJ();

            try
            {
                ClearBuffer(clearBufferBeforeRead);
                DateTime dtStart = DateTime.Now;
                while (true)
                {
                    if (false == BufferEmpty()) //unread frame in instrument
                    {
                        objFrame = ReadFrame();
                        if (objFrame.DataLen > 0 && objFrame.ID == canID)
                        {
                            DataList.Add(objFrame);
                        }
                    }
                    else if ((DateTime.Now - dtStart).TotalMilliseconds > timeOut)
                    {
                        break;
                    }
                    else
                    {
                        Thread.Sleep(Setting.MaxInterval);
                        if (true == BufferEmpty()) //unread frame in instrument
                        {
                            break;                 //time exceeds the max interval, don't wait.
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (true == ex.Message.StartsWith("Failed at CAN receive: "))
                {
                    throw new Exception(ex.Message);
                }
                else
                {
                    throw new Exception(string.Format("Failed at receive message method with message: {0}", ex.Message));
                }
            }
            return(true);
        }
Exemplo n.º 10
0
        public void ThreadFunc_Receive(object obj)
        {
            string str = obj as string;

            Console.WriteLine("[{0}] - [ThreadFunc_Receive] - Start", DateTime.Now.ToString("HH:mm:ss.ffff"));

            if (listReceivedFrame == null)
            {
                Console.WriteLine("[{0}] - [ThreadFunc_Receive] - init listReceivedFrame", DateTime.Now.ToString("HH:mm:ss.ffff"));
                listReceivedFrame = new List <CAN_OBJ>();
            }
            int iThreadFunc_ReceiveCount = 0;

            while (EnableReceiveThread)
            {
                try
                {
                    lock (listReceivedFrame)
                    {
                        if (false == BufferEmpty())
                        {
                            CAN_OBJ canObj = ReadFrame();
                            if (canObj.DataLen > 0)
                            {
                                listReceivedFrame.Add(canObj);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[Err][ThreadFunc_Receive]:{0}", ex.Message);
                }
                iThreadFunc_ReceiveCount++;
            }
        }
 public static string FrameToString(CAN_OBJ canObj)
 {
     return(string.Format("{0:X},{1:X}", canObj.ID, BitConverter.ToString(canObj.data).Replace("-", string.Empty)));
 }
Exemplo n.º 12
0
        public bool SendMessages(List <byte[]> DataList,
                                 uint ID         = 1,
                                 uint TimeStamp  = 0,
                                 byte TimeFlag   = 0x0,
                                 byte SendType   = 0x0,
                                 byte RemoteFlag = 0x0,                       //not remote frame
                                 byte ExternFlag = 0x0)                       //standard frame
        {
            byte[]  byteData    = new byte[8];
            CAN_OBJ canOBJ      = new CAN_OBJ();
            bool    bSendStatus = false;

            try
            {
                canOBJ.ExternFlag = ExternFlag;
                canOBJ.ID         = ID;
                canOBJ.RemoteFlag = RemoteFlag;
                canOBJ.Reserved   = null;
                canOBJ.SendType   = SendType;
                canOBJ.TimeFlag   = TimeFlag;
                canOBJ.TimeStamp  = TimeStamp;

                foreach (byte[] byteCommand in DataList)
                {
                    uint uLength = (uint)byteCommand.Length;

                    if (uLength > 8)
                    {
                        throw new Exception("The command length is large than 8.");
                    }
                    else
                    {
                        //do nothing
                    }
                    for (int i = 0; i < 8; i++)
                    {
                        if (i < uLength)
                        {
                            byteData[i] = byteCommand[i];
                        }
                        else
                        {
                            byteData[i] = 0x0;
                        }
                    }
                    canOBJ.DataLen = (byte)uLength;
                    bSendStatus    = SendFrame(canOBJ, byteData);
                    if (bSendStatus == false)
                    {
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                if (true == ex.Message.StartsWith("Failed at CAN transmit with data:"))
                {
                    throw new Exception(string.Format("{0}", ex.Message));
                }
                else
                {
                    throw new Exception(string.Format("Failed at SendMessage with message: {0}", ex.Message));
                }
            }
            return(true);
        }