Exemplo n.º 1
0
        public override void handleMessage(CANMessage a_message)
        {
            if (_queue == null)
            {
                _queue = new CANMessage[32];
                _receiveMessageIndex = 0;
                _readMessageIndex = 0;
            }

            // add the message to a queue for later processing ...
            // the queue is a ringbuffer for CANMessage objects.
            // X objects are supported
            // we need a receive and a read pointer for this to work properly
            messageReceived = false;
            //_queue[_receiveMessageIndex] = a_message;
            _queue[_receiveMessageIndex] = new CANMessage();
            _queue[_receiveMessageIndex].setData(a_message.getData());
            _queue[_receiveMessageIndex].setID(a_message.getID());
            _queue[_receiveMessageIndex].setLength(a_message.getLength());

            _receiveMessageIndex++;
            if(_receiveMessageIndex > _queue.Length - 1) _receiveMessageIndex = 0; // make it circular

            DetermineSize();
        }
Exemplo n.º 2
0
 public override void handleMessage(CANMessage a_message)
 {
     lock (m_canMessage)
     {
         if (a_message.getID() == m_waitMsgID)
         {
             m_canMessage.setData(a_message.getData());
             m_canMessage.setFlags(a_message.getFlags());
             m_canMessage.setID(a_message.getID());
             m_canMessage.setLength(a_message.getLength());
             m_canMessage.setTimeStamp(a_message.getTimeStamp());
             messageReceived = true;
             m_resetEvent.Set();
         }
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// readMessages is the "run" method of this class. It reads all incomming messages
        /// and publishes them to registered ICANListeners.
        /// </summary>
        public void readMessages()
        {
            int readResult = 0;

            Lawicel.CANUSB.CANMsg r_canMsg   = new Lawicel.CANUSB.CANMsg();
            CANMessage            canMessage = new CANMessage();

            Console.WriteLine("readMessages started");
            while (true)
            {
                lock (m_synchObject)
                {
                    if (m_endThread)
                    {
                        Console.WriteLine("readMessages ended");
                        return;
                    }
                }
                readResult = Lawicel.CANUSB.canusb_Read(m_deviceHandle, out r_canMsg);
                if (readResult == Lawicel.CANUSB.ERROR_CANUSB_OK)
                {
                    if (acceptMessageId(r_canMsg.id))
                    {
                        canMessage.setID(r_canMsg.id);
                        canMessage.setLength(r_canMsg.len);
                        canMessage.setTimeStamp(r_canMsg.timestamp);
                        canMessage.setFlags(r_canMsg.flags);
                        canMessage.setData(r_canMsg.data);
                        lock (m_listeners)
                        {
                            AddToCanTrace(string.Format("RX: {0} {1}", canMessage.getID().ToString("X3"), canMessage.getData().ToString("X16")));
                            foreach (ICANListener listener in m_listeners)
                            {
                                listener.handleMessage(canMessage);
                            }
                        }
                    }
                }
                else if (readResult == Lawicel.CANUSB.ERROR_CANUSB_NO_MESSAGE)
                {
                    Thread.Sleep(1);
                }
            }
        }
Exemplo n.º 4
0
        override public void handleMessage(CANMessage a_message)
        {
            if (_queue == null)
            {
                _queue = new CANMessage[16];
                _receiveMessageIndex = 0;
                _readMessageIndex    = 0;
            }

            // add the message to a queue for later processing ...
            // the queue is a ringbuffer for CANMessage objects.
            // X objects are supported
            // we need a receive and a read pointer for this to work properly
            messageReceived = false;
            //_queue[_receiveMessageIndex] = a_message;
            _queue[_receiveMessageIndex] = new CANMessage();
            _queue[_receiveMessageIndex].setData(a_message.getData());
            _queue[_receiveMessageIndex].setID(a_message.getID());
            _queue[_receiveMessageIndex].setLength(a_message.getLength());

            _receiveMessageIndex++;
            if (_receiveMessageIndex > _queue.Length - 1)
            {
                _receiveMessageIndex = 0;                                          // make it circular
            }
            //DetermineSize();


            /*
             * lock (m_canMessage)
             * {
             *  if (a_message.getID() == m_waitMsgID)
             *  {
             *      m_canMessage = a_message;
             *      messageReceived = true;
             *  }
             * }
             * if (messageReceived)
             * {
             *  m_resetEvent.Set();
             * }*/
        }
Exemplo n.º 5
0
        /// <summary>
        /// sendMessage send a CANMessage.
        /// </summary>
        /// <param name="a_message">A CANMessage.</param>
        /// <returns>true on success, othewise false.</returns>
        override public bool sendMessage(CANMessage a_message)
        {
            lock (lockObj)
            {
                while (interfaceBusy)
                {
                    if (lastSentTimestamp < Environment.TickCount - timeoutWithoutReadyChar)
                    {
                        //Console.WriteLine("released");
                        break;
                    }
                }

                lastSentTimestamp = Environment.TickCount;
                interfaceBusy     = true;
                //Console.WriteLine("set");

                Lawicel.CANUSB.CANMsg msg = new Lawicel.CANUSB.CANMsg();
                msg.id    = a_message.getID();
                msg.len   = a_message.getLength();
                msg.flags = a_message.getFlags();
                msg.data  = a_message.getData();

                if (m_serialPort.IsOpen)
                {
                    //m_serialPort.Write("\r");
                    string txstring = "t";
                    txstring += msg.id.ToString("X3");
                    txstring += "8"; // always 8 bytes to transmit
                    for (int t = 0; t < 8; t++)
                    {
                        byte b = (byte)(((msg.data >> t * 8) & 0x0000000000000000FF));
                        txstring += b.ToString("X2");
                    }
                    txstring += "\r";
                    AddToCanTrace(string.Format("TX: {0} {1} {2}", a_message.getID().ToString("X3"), a_message.getData().ToString("X16"), txstring));
                    m_serialPort.Write(txstring);
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 6
0
        //---------------------------------------------------------------------------------------------

        /**
         *  Sends a 11 bit CAN data frame.
         *
         *  @param      msg         CAN message
         *
         *  @return                 success (true/false)
         */
        protected override bool sendMessageDevice(CANMessage msg)
        {
            try
            {
                caCombiAdapter.caCANFrame frame;
                frame.id          = msg.getID();
                frame.length      = msg.getLength();
                frame.data        = msg.getData();
                frame.is_extended = 0;
                frame.is_remote   = 0;

                combi.CAN_SendMessage(ref frame);
                return(true);
            }
            catch (Exception e)
            {
                logger.Debug("tx failed with Exception.Message: " + e.Message);
                return(false);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// sendMessage send a CANMessage.
        /// </summary>
        /// <param name="a_message">A CANMessage.</param>
        /// <returns>true on success, othewise false.</returns>
        override protected bool sendMessageDevice(CANMessage a_message)
        {
            Lawicel.CANUSB.CANMsg msg = new Lawicel.CANUSB.CANMsg();
            msg.id    = a_message.getID();
            msg.len   = a_message.getLength();
            msg.flags = a_message.getFlags();
            msg.data  = a_message.getData();
            int writeResult;

            writeResult = Lawicel.CANUSB.canusb_Write(m_deviceHandle, ref msg);
            if (writeResult == Lawicel.CANUSB.ERROR_CANUSB_OK)
            {
                return(true);
            }
            else
            {
                logger.Debug("tx failed writeResult: " + writeResult);
                return(false);
            }
        }
Exemplo n.º 8
0
        //---------------------------------------------------------------------------------------------

        /**
         *  Waits for arrival of a specific CAN message or any message if ID = 0.
         *
         *  @param      a_canID     message ID
         *  @param      timeout     timeout, ms
         *  @param      canMsg      message
         *
         *  @return                 message ID
         */
        public override uint waitForMessage(uint a_canID, uint timeout,
                                            out CANMessage canMsg)
        {
            canMsg = new CANMessage();
            Debug.Assert(canMsg != null);
            canMsg.setID(0);

            caCombiAdapter.caCANFrame frame = new caCombiAdapter.caCANFrame();
            if (combi.CAN_GetMessage(ref frame, timeout) &&
                (frame.id == a_canID || a_canID == 0))
            {
                // message received
                canMsg.setID(frame.id);
                canMsg.setLength(frame.length);
                canMsg.setData(frame.data);

                return(frame.id);
            }

            // timed out
            return(0);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Send a message that starts a session. This is used to test if there is
        /// a connection.
        /// </summary>
        /// <returns></returns>
        private bool sendSessionRequest()
        {
            CANMessage msg1 = new CANMessage(0x220, 0, 8);

            EASYSYNC.CANMsg msg = new EASYSYNC.CANMsg();
            msg1.setData(0x000040021100813f);

            if (!sendMessage(msg1))
            {
                return(false);
            }
            if (waitForMessage(0x238, 1000, out msg) == 0x238)
            {
                //Ok, there seems to be a ECU somewhere out there.
                //Now, sleep for 10 seconds to get a session timeout. This is needed for
                //applications on higher level. Otherwise there will be no reply when the
                //higher level application tries to start a session.
                Thread.Sleep(10000);
                return(true);
            }
            return(false);
        }
Exemplo n.º 10
0
        public override uint waitForMessage(uint a_canID, uint timeout, out CANMessage canMsg)
        {
            canMsg = new CANMessage();
            return(0);

            //CANMessage canMessage = new CANMessage();
            //string rxMessage = string.Empty;

            //canMsg = new CANMessage();
            //int nrOfWait = 0;

            //while (nrOfWait < timeout)
            //{
            //    rxMessage = m_serialPort.ReadLine();
            //    rxMessage = rxMessage.Replace("\r", ""); // remove prompt characters... we don't need that stuff
            //    rxMessage = rxMessage.Replace("\n", ""); // remove prompt characters... we don't need that stuff
            //    if (rxMessage.StartsWith("w") == false)
            //    {
            //        Thread.Sleep(1);
            //        nrOfWait++;
            //        continue;
            //    }
            //    uint id = Convert.ToUInt32(rxMessage.Substring(1, 3), 16);
            //    if (id != a_canID && a_canID != 0)
            //    {
            //        Thread.Sleep(1);
            //        nrOfWait++;
            //        continue;
            //    }

            //    canMessage.setID(id);
            //    canMessage.setLength(8);
            //    canMessage.setData(0x0000000000000000);
            //    for (uint i = 0; i < 8; i++)
            //        canMessage.setCanData(Convert.ToByte(rxMessage.Substring(5 + (2 * (int)i), 2), 16), i);
            //    return (uint)id;
            //}
            //return 0;
        }
Exemplo n.º 11
0
        public override void handleMessage(CANMessage a_message)
        {
            if (_queue == null)
            {
                _queue = new CANMessage[16];
                _receiveMessageIndex = 0;
                _readMessageIndex = 0;
            }

            // add the message to a queue for later processing ...
            // the queue is a ringbuffer for CANMessage objects.
            // X objects are supported
            // we need a receive and a read pointer for this to work properly
            messageReceived = false;
            //_queue[_receiveMessageIndex] = a_message;
            _queue[_receiveMessageIndex] = new CANMessage();
            _queue[_receiveMessageIndex].setData(a_message.getData());
            _queue[_receiveMessageIndex].setID(a_message.getID());
            _queue[_receiveMessageIndex].setLength(a_message.getLength());

            _receiveMessageIndex++;
            if(_receiveMessageIndex > _queue.Length - 1) _receiveMessageIndex = 0; // make it circular

            //DetermineSize();

            /*
            lock (m_canMessage)
            {
                if (a_message.getID() == m_waitMsgID)
                {
                    m_canMessage = a_message;
                    messageReceived = true;
                }
            }
            if (messageReceived)
            {
                m_resetEvent.Set();
            }*/
        }
Exemplo n.º 12
0
        /// <summary>
        /// readMessages is the "run" method of this class. It reads all incomming messages
        /// and publishes them to registered ICANListeners.
        /// </summary>
        public void readMessages()
        {
            int readResult = 0;

            Lawicel.CANUSB.CANMsg r_canMsg   = new Lawicel.CANUSB.CANMsg();
            CANMessage            canMessage = new CANMessage();

            logger.Debug("readMessages started");
            while (true)
            {
                lock (m_synchObject)
                {
                    if (m_endThread)
                    {
                        logger.Debug("readMessages thread ended");
                        return;
                    }
                }
                readResult = Lawicel.CANUSB.canusb_Read(m_deviceHandle, out r_canMsg);
                if (readResult == Lawicel.CANUSB.ERROR_CANUSB_OK)
                {
                    if (acceptMessageId(r_canMsg.id))
                    {
                        canMessage.setID(r_canMsg.id);
                        canMessage.setLength(r_canMsg.len);
                        canMessage.setTimeStamp(r_canMsg.timestamp);
                        canMessage.setFlags(r_canMsg.flags);
                        canMessage.setData(r_canMsg.data);

                        receivedMessage(canMessage);
                    }
                }
                else if (readResult == Lawicel.CANUSB.ERROR_CANUSB_NO_MESSAGE)
                {
                    Thread.Sleep(1);
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// readMessages is the "run" method of this class. It reads all incomming messages
        /// and publishes them to registered ICANListeners.
        /// </summary>
        public void readMessages()
        {
            int readResult = 0;

            EASYSYNC.CANMsg r_canMsg   = new EASYSYNC.CANMsg();
            CANMessage      canMessage = new CANMessage();

            while (true)
            {
                lock (m_synchObject)
                {
                    if (m_endThread)
                    {
                        return;
                    }
                }
                readResult = EASYSYNC.canusb_Read(m_deviceHandle, out r_canMsg);
                if (readResult == EASYSYNC.ERROR_CANUSB_OK)
                {
                    canMessage.setID(r_canMsg.id);
                    canMessage.setLength(r_canMsg.len);
                    canMessage.setTimeStamp(r_canMsg.timestamp);
                    canMessage.setFlags(r_canMsg.flags);
                    canMessage.setData(r_canMsg.data);
                    lock (m_listeners)
                    {
                        foreach (ICANListener listener in m_listeners)
                        {
                            listener.handleMessage(canMessage);
                        }
                    }
                }
                else if (readResult == EASYSYNC.ERROR_CANUSB_NO_MESSAGE)
                {
                    Thread.Sleep(1);
                }
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// waitForMessage waits for a specific CAN message give by a CAN id.
        /// </summary>
        /// <param name="a_canID">The CAN id to listen for</param>
        /// <param name="timeout">Listen timeout</param>
        /// <param name="r_canMsg">The CAN message with a_canID that we where listening for.</param>
        /// <returns>The CAN id for the message we where listening for, otherwise 0.</returns>
        public override uint waitForMessage(uint a_canID, uint timeout, out CANMessage canMsg)
        {
            Lawicel.CANUSB.CANMsg r_canMsg;
            canMsg = new CANMessage();
            int readResult = 0;
            int nrOfWait   = 0;

            while (nrOfWait < timeout)
            {
                r_canMsg   = new Lawicel.CANUSB.CANMsg();
                readResult = Lawicel.CANUSB.canusb_Read(m_deviceHandle, out r_canMsg);
                if (readResult == Lawicel.CANUSB.ERROR_CANUSB_OK)
                {
                    Thread.Sleep(1);
                    logger.Trace("rx: 0x" + r_canMsg.id.ToString("X3") + r_canMsg.data.ToString("X16"));
                    if (r_canMsg.id == 0x00)
                    {
                        nrOfWait++;
                    }
                    else if (r_canMsg.id != a_canID)
                    {
                        continue;
                    }
                    canMsg.setData(r_canMsg.data);
                    canMsg.setID(r_canMsg.id);
                    canMsg.setLength(r_canMsg.len);
                    return((uint)r_canMsg.id);
                }
                else if (readResult == Lawicel.CANUSB.ERROR_CANUSB_NO_MESSAGE)
                {
                    Thread.Sleep(1);
                    nrOfWait++;
                }
            }
            r_canMsg = new Lawicel.CANUSB.CANMsg();
            return(0);
        }
Exemplo n.º 15
0
        public CANMessage waitMessage(int a_timeout)
        {
            sw.Reset();
            sw.Start();
            CANMessage retMsg = new CANMessage();
            while (sw.ElapsedMilliseconds < a_timeout)
            {
                // search queue for the desired message
                if (_receiveMessageIndex < _readMessageIndex)
                {
                    // first upto (_queue.Length - 1)
                    for (int idx = _readMessageIndex; idx < _queue.Length; idx++)
                    {
                        if (_queue[idx].getID() == this.m_waitMsgID)
                        {
                            retMsg = _queue[idx];
                            _readMessageIndex = idx + 1;
                            if (_readMessageIndex > _queue.Length - 1) _readMessageIndex = 0; // make it circular

                            sw.Stop();
                            return retMsg;
                        }
                    }
                    for (int idx = 0; idx < _receiveMessageIndex; idx++)
                    {
                        if (_queue[idx].getID() == this.m_waitMsgID)
                        {
                            retMsg = _queue[idx];
                            _readMessageIndex = idx + 1;
                            if (_readMessageIndex > _queue.Length - 1) _readMessageIndex = 0; // make it circular
                            sw.Stop();
                            return retMsg;
                        }
                    }
                }
                else
                {
                    for (int idx = _readMessageIndex; idx < _receiveMessageIndex; idx++)
                    {
                        if (_queue[idx].getID() == this.m_waitMsgID)
                        {
                            retMsg = _queue[idx];
                            _readMessageIndex = idx + 1;
                            if (_readMessageIndex > _queue.Length - 1) _readMessageIndex = 0; // make it circular
                            sw.Stop();
                            return retMsg;
                        }
                    }
                }
                Thread.Sleep(1);
            }
            sw.Stop();
            return retMsg;

            /*
            CANMessage retMsg;

            m_resetEvent.WaitOne(a_timeout, true);
            lock (m_canMessage)
            {
                retMsg = m_canMessage;
            }
            messageReceived = false;
            return retMsg;*/
        }
Exemplo n.º 16
0
 /// <summary>
 /// readMessages is the "run" method of this class. It reads all incomming messages
 /// and publishes them to registered ICANListeners.
 /// </summary>
 public void readMessages()
 {
     int readResult = 0;
     Lawicel.CANUSB.CANMsg r_canMsg = new Lawicel.CANUSB.CANMsg();
     CANMessage canMessage = new CANMessage();
     Console.WriteLine("readMessages started");
     while (true)
     {
         lock (m_synchObject)
         {
             if (m_endThread)
             {
                 Console.WriteLine("readMessages ended");
                 return;
             }
         }
         readResult = Lawicel.CANUSB.canusb_Read(m_deviceHandle, out r_canMsg);
         if (readResult == Lawicel.CANUSB.ERROR_CANUSB_OK)
         {
             if (acceptMessageId(r_canMsg.id))
             {
                 canMessage.setID(r_canMsg.id);
                 canMessage.setLength(r_canMsg.len);
                 canMessage.setTimeStamp(r_canMsg.timestamp);
                 canMessage.setFlags(r_canMsg.flags);
                 canMessage.setData(r_canMsg.data);
                 lock (m_listeners)
                 {
                     AddToCanTrace(string.Format("RX: {0} {1}", canMessage.getID().ToString("X3"), canMessage.getData().ToString("X16")));
                     foreach (ICANListener listener in m_listeners)
                     {
                         listener.handleMessage(canMessage);
                     }
                 }
             }
         }
         else if (readResult == Lawicel.CANUSB.ERROR_CANUSB_NO_MESSAGE)
         {
             Thread.Sleep(1);
         }
     }
 }
Exemplo n.º 17
0
 /// <summary>
 /// waitForMessage waits for a specific CAN message give by a CAN id.
 /// </summary>
 /// <param name="a_canID">The CAN id to listen for</param>
 /// <param name="timeout">Listen timeout</param>
 /// <param name="r_canMsg">The CAN message with a_canID that we where listening for.</param>
 /// <returns>The CAN id for the message we where listening for, otherwise 0.</returns>
 public override uint waitForMessage(uint a_canID, uint timeout, out CANMessage canMsg)
 {
     Lawicel.CANUSB.CANMsg r_canMsg;
     canMsg = new CANMessage();
     int readResult = 0;
     int nrOfWait = 0;
     while (nrOfWait < timeout)
     {
         r_canMsg = new Lawicel.CANUSB.CANMsg();
         readResult = Lawicel.CANUSB.canusb_Read(m_deviceHandle, out r_canMsg);
         if (readResult == Lawicel.CANUSB.ERROR_CANUSB_OK)
         {
             Thread.Sleep(1);
             AddToCanTrace("rx: 0x" + r_canMsg.id.ToString("X4") + r_canMsg.data.ToString("X16"));
             if (r_canMsg.id == 0x00)
             {
                 nrOfWait++;
             }
             else if (r_canMsg.id != a_canID)
                 continue;
             canMsg.setData(r_canMsg.data);
             canMsg.setID(r_canMsg.id);
             canMsg.setLength(r_canMsg.len);
             return (uint)r_canMsg.id;
         }
         else if (readResult == Lawicel.CANUSB.ERROR_CANUSB_NO_MESSAGE)
         {
             Thread.Sleep(1);
             nrOfWait++;
         }
     }
     r_canMsg = new Lawicel.CANUSB.CANMsg();
     return 0;
 }
Exemplo n.º 18
0
        //---------------------------------------------------------------------------------------------
        /**
        Waits for arrival of a specific CAN message or any message if ID = 0.

        @param      a_canID     message ID
        @param      timeout     timeout, ms
        @param      canMsg      message

        @return                 message ID
        */
        public override uint waitForMessage(uint a_canID, uint timeout,
        out CANMessage canMsg)
        {
            canMsg = new CANMessage();
            Debug.Assert(canMsg != null);
            canMsg.setID(0);

            caCombiAdapter.caCANFrame frame = new caCombiAdapter.caCANFrame();
            if (this.combi.CAN_GetMessage(ref frame, timeout) &&
            (frame.id == a_canID || a_canID == 0))
            {
            // message received
            canMsg.setID(frame.id);
            canMsg.setLength(frame.length);
            canMsg.setData(frame.data);

            return frame.id;
            }

            // timed out
            return 0;
        }
Exemplo n.º 19
0
        // int thrdcnt = 0;
        /// <summary>
        /// readMessages is the "run" method of this class. It reads all incomming messages
        /// and publishes them to registered ICANListeners.
        /// </summary>
        public void readMessages()
        {
            while (true)
            {
                lock (m_synchObject)
                {
                    if (m_endThread)
                    {
                        m_endThread = false;
                        return;
                    }
                }
                if (m_serialPort.IsOpen)
                {
                    // read the status?


                    string line = string.Empty;

                    try
                    {
                        line = m_serialPort.ReadLine();
                        if (line.Length > 0)
                        {
                            if (line.Length == 25)
                            {
                                Lawicel.CANUSB.CANMsg r_canMsg = new Lawicel.CANUSB.CANMsg();
                                canMessage = new CANMessage();
                                // three bytes identifier
                                r_canMsg.id  = (uint)Convert.ToInt32(line.Substring(1, 3), 16);
                                r_canMsg.len = (byte)Convert.ToInt32(line.Substring(4, 1), 16);
                                ulong data = 0;
                                // add all the bytes
                                data         |= (ulong)(byte)Convert.ToInt32(line.Substring(5, 2), 16);
                                data         |= (ulong)(byte)Convert.ToInt32(line.Substring(7, 2), 16) << 1 * 8;
                                data         |= (ulong)(byte)Convert.ToInt32(line.Substring(9, 2), 16) << 2 * 8;
                                data         |= (ulong)(byte)Convert.ToInt32(line.Substring(11, 2), 16) << 3 * 8;
                                data         |= (ulong)(byte)Convert.ToInt32(line.Substring(13, 2), 16) << 4 * 8;
                                data         |= (ulong)(byte)Convert.ToInt32(line.Substring(15, 2), 16) << 5 * 8;
                                data         |= (ulong)(byte)Convert.ToInt32(line.Substring(17, 2), 16) << 6 * 8;
                                data         |= (ulong)(byte)Convert.ToInt32(line.Substring(19, 2), 16) << 7 * 8;
                                r_canMsg.data = data;
                                canMessage.setID(r_canMsg.id);
                                canMessage.setLength(r_canMsg.len);
                                canMessage.setFlags(r_canMsg.flags);
                                canMessage.setData(r_canMsg.data);

                                lock (m_listeners)
                                {
                                    AddToCanTrace(string.Format("RX: {0} {1} {2}", canMessage.getID().ToString("X3"), line.Substring(5, 16), line));
                                    foreach (ICANListener listener in m_listeners)
                                    {
                                        listener.handleMessage(canMessage);
                                    }
                                }
                            }
                            else if (line.Contains("z"))
                            {
                                interfaceBusy = false;
                                //Console.WriteLine("clear");
                            }
                            else if (line.Length == 2 && Convert.ToInt32(line.Substring(1, 2), 16) != 0x07)
                            {
                                //Console.WriteLine("Send error");
                            }
                            else
                            {
                                //Console.WriteLine("Unknown message: " + line);
                            }
                        }
                    }
                    catch (Exception E)
                    {
                        Console.WriteLine("Failed to read frames from CANbus: " + E.Message);
                    }
                }
                //Thread.Sleep(2);
                Thread.Sleep(delayTimespan); // give others some air
            }
        }
Exemplo n.º 20
0
        //-------------------------------------------------------------------------

        /**
         *  Sends a 11 bit CAN data frame.
         *
         *  @param      message     CAN message
         *
         *  @return                 success (true/false)
         */
        public override bool sendMessage(CANMessage message)
        {
            return(MctAdapter_SendMessage(message.getID(), message.getLength(),
                                          message.getData()));
        }
Exemplo n.º 21
0
 public InformationFrameEventArgs(CANMessage message)
 {
     this._message = message;
 }
Exemplo n.º 22
0
        /// <summary>
        /// waitForMessage waits for a specific CAN message give by a CAN id.
        /// </summary>
        /// <param name="a_canID">The CAN id to listen for</param>
        /// <param name="timeout">Listen timeout</param>
        /// <param name="r_canMsg">The CAN message with a_canID that we where listening for.</param>
        /// <returns>The CAN id for the message we where listening for, otherwise 0.</returns>
        public override uint waitForMessage(uint a_canID, uint timeout, out CANMessage canMessage)
        {
            canMessage = new CANMessage();
            Debug.Assert(canMessage != null);

            int wait_cnt = 0;
            uint id;
            byte length;
            ulong data;
            while (wait_cnt < timeout)
            {
            if (MctAdapter_ReceiveMessage(out id, out length, out data))
            {
                // message received
                canMessage.setID(id);
                canMessage.setLength(length);
                canMessage.setData(data);

                if (canMessage.getID() != a_canID)
                    continue;
                return (uint)canMessage.getID();
            }

            // wait a bit
            Thread.Sleep(1);
            ++wait_cnt;
            }

            // nothing was received
            return 0;
        }
Exemplo n.º 23
0
        //-------------------------------------------------------------------------
        /**
        Handles incoming messages.
        */
        private void read_messages()
        {
            uint id;
            byte length;
            ulong data;

            CANMessage msg = new CANMessage();
            Debug.Assert(msg != null);

            // main loop
            while (true)
            {
            // check for thread termination request
            Debug.Assert(this.term_mutex != null);
            lock (this.term_mutex)
            {
                if (this.term_requested)
                {
                    return;
                }
            }

            // receive messages
            while (MctAdapter_ReceiveMessage(out id, out length, out data))
            {
                if (acceptMessageId(id))
                {
                    // convert message
                    msg.setID(id);
                    msg.setLength(length);
                    msg.setData(data);

                    // pass message to listeners
                    lock (this.m_listeners)
                    {
                        AddToCanTrace("RX: " + id.ToString("X4") + " " + data.ToString("X16"));
                        foreach (ICANListener listener in this.m_listeners)
                        {
                            listener.handleMessage(msg);
                        }
                    }
                }
            }

            // give up CPU for a moment
            Thread.Sleep(1);
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Send a message that starts a session. This is used to test if there is 
        /// a connection.
        /// </summary>
        /// <returns></returns>
        private bool sendSessionRequest()
        {
            CANMessage msg1 = new CANMessage(0x220, 0, 8);
            EASYSYNC.CANMsg msg = new EASYSYNC.CANMsg();
            msg1.setData(0x000040021100813f);

            if (!sendMessage(msg1))
                return false;
            if (waitForMessage(0x238, 1000, out msg) == 0x238)
            {
                //Ok, there seems to be a ECU somewhere out there.
                //Now, sleep for 10 seconds to get a session timeout. This is needed for
                //applications on higher level. Otherwise there will be no reply when the
                //higher level application tries to start a session.
                Thread.Sleep(10000);
                return true;
            }
            return false;
        }
Exemplo n.º 25
0
        //-------------------------------------------------------------------------
        /**
        Sends a 11 bit CAN data frame.

        @param      message     CAN message

        @return                 success (true/false)
        */
        public override bool sendMessage(CANMessage message)
        {
            return MctAdapter_SendMessage(message.getID(), message.getLength(),
            message.getData());
        }
Exemplo n.º 26
0
        public void readMessages()
        {
            CANMessage    canMessage  = new CANMessage();
            StringBuilder receiveText = new StringBuilder();

            logger.Debug("readMessages started");
            while (true)
            {
                receiveDataSemaphore.WaitOne();

                lock (m_synchObject)
                {
                    if (m_endThread)
                    {
                        logger.Debug("readMessages ended");
                        return;
                    }
                }

                if (m_serialPort != null)
                {
                    if (m_serialPort.IsOpen && m_serialPort.BytesToRead > 0)
                    {
                        string rawString = string.Empty;
                        try
                        {
                            rawString = m_serialPort.ReadExisting();
                        }
                        catch (Exception e)
                        {
                            logger.Debug("CANELM372Device ReadExisting()" + e.Message);
                        }
                        //AddToSerialTrace("RAW RX: " + rawString.Replace("\r",m_cr_sequence));
                        string rxString  = rawString.Replace("\n", "").Replace(">", "");// remove prompt characters... we don't need that stuff
                        bool   isStopped = false;

                        if (rxString.Length > 0)
                        {
                            rxString = rxString.Replace("\r", m_cr_sequence); //replace , because stringbuilder cannot handle \r
                            receiveText.Append(rxString);
                            //AddToSerialTrace("RECEIVE TEXT: " + receiveText.ToString());
                            //System.Diagnostics.Debug.WriteLine("SERMSG: " + receiveText);
                            var lines = ExtractLines(ref receiveText);
                            foreach (var rxMessage in lines)
                            {
                                if (rxMessage.StartsWith("STOPPED"))
                                {
                                    isStopped = true;
                                }
                                else if (rxMessage.StartsWith("NO DATA"))
                                {
                                }                                             //skip it
                                else if (rxMessage.StartsWith("CAN ERROR"))
                                {
                                    //handle error?
                                }
                                else if (rxMessage.StartsWith("ELM"))
                                {
                                    isStopped = false;
                                }                                                            //skip it, this is a trick to stop ELM from listening to more messages and send ready char
                                else if (rxMessage.StartsWith("?"))
                                {
                                    isStopped = false;
                                }
                                else if (rxMessage.StartsWith("NO DATA"))
                                {
                                    logger.Debug("NO DATA");
                                }
                                else if (rxMessage.Length == 19) // is it a valid line
                                {
                                    try
                                    {
                                        rxMessage.Replace(" ", "");//remove all whitespaces
                                        uint id = Convert.ToUInt32(rxMessage.Substring(0, 3), 16);
                                        if (acceptMessageId(id))
                                        {
                                            canMessage.setID(id);
                                            canMessage.setLength(8); // TODO: alter to match data
                                            //canMessage.setData(0x0000000000000000); // reset message content
                                            canMessage.setData(ExtractDataFromString(rxMessage));

                                            receivedMessage(canMessage);
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        logger.Debug(e, rxMessage);
                                    }
                                }
                                // Catch weird message-lengths from Z22SE
                                else if (rxMessage.StartsWith("7E8") && rxMessage.Length > 6)
                                {
                                    try
                                    {
                                        rxMessage.Replace(" ", "");//remove all whitespaces
                                        uint id = Convert.ToUInt32(rxMessage.Substring(0, 3), 16);

                                        byte len = (byte)(rxMessage.Length - 3);
                                        len = (byte)(((len & 1) == 1 ? len + 1 : len) / 2);

                                        if (acceptMessageId(id) && len <= 8)
                                        {
                                            canMessage.setID(id);
                                            canMessage.setLength(len);
                                            canMessage.setData(ExtractDataFromString2(len, rxMessage));
                                            receivedMessage(canMessage);
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        logger.Debug(e, rxMessage);
                                    }
                                }
                                //disable whitespace logging
                                if (rxMessage.Length > 0)
                                {
                                    logger.Debug("SERRX: " + rxMessage + " Len:" + rxMessage.Length);
                                }
                            }
                        }
                        if (rawString.Contains(">") && !isStopped)
                        {
                            logger.Debug("SERIAL READY");
                            sendDataSempahore.WaitOne(0);
                            sendDataSempahore.Release();
                            interfaceBusy = false;
                        }
                    }
                }
            }
        }
Exemplo n.º 27
0
 public override uint waitForMessage(uint a_canID, uint timeout, out CANMessage canMsg)
 {
     canMsg = new CANMessage();
     return(0);
 }
Exemplo n.º 28
0
        public CANMessage waitMessage(int a_timeout)
        {
            sw.Reset();
            sw.Start();
            CANMessage retMsg = new CANMessage();
            while (sw.ElapsedMilliseconds < a_timeout)
            {
                // search queue for the desired message
                if (_receiveMessageIndex < _readMessageIndex)
                {
                    // first upto (_queue.Length - 1)
                    for (int idx = _readMessageIndex; idx < _queue.Length; idx++)
                    {
                        if (_queue[idx].getID() == this.m_waitMsgID || _queue[idx].getID() == this.m_additionalWaitMsgID)
                        {
                            retMsg = _queue[idx];
                            _readMessageIndex = idx + 1;
                            if (_readMessageIndex > _queue.Length - 1) _readMessageIndex = 0; // make it circular

                            sw.Stop();
                            return retMsg;
                        }
                    }
                    for (int idx = 0; idx < _receiveMessageIndex; idx++)
                    {
                        if (_queue[idx].getID() == this.m_waitMsgID || _queue[idx].getID() == this.m_additionalWaitMsgID)
                        {
                            retMsg = _queue[idx];
                            _readMessageIndex = idx + 1;
                            if (_readMessageIndex > _queue.Length - 1) _readMessageIndex = 0; // make it circular
                            sw.Stop();
                            return retMsg;
                        }
                    }
                }
                else
                {
                    for (int idx = _readMessageIndex; idx < _receiveMessageIndex; idx++)
                    {
                        if (_queue[idx].getID() == this.m_waitMsgID || _queue[idx].getID() == this.m_additionalWaitMsgID)
                        {
                            retMsg = _queue[idx];
                            _readMessageIndex = idx + 1;
                            if (_readMessageIndex > _queue.Length - 1) _readMessageIndex = 0; // make it circular
                            sw.Stop();
                            return retMsg;
                        }
                    }
                }
                Thread.Sleep(1);
            }
            sw.Stop();
            return retMsg;
        }
Exemplo n.º 29
0
        public CANMessage waitMessage(int a_timeout)
        {
            sw.Reset();
            sw.Start();
            CANMessage retMsg = new CANMessage();

            while (sw.ElapsedMilliseconds < a_timeout)
            {
                // search queue for the desired message
                if (_receiveMessageIndex < _readMessageIndex)
                {
                    // first upto (_queue.Length - 1)
                    for (int idx = _readMessageIndex; idx < _queue.Length; idx++)
                    {
                        if (_queue[idx].getID() == this.m_waitMsgID || _queue[idx].getID() == this.m_additionalWaitMsgID)
                        {
                            retMsg            = _queue[idx];
                            _readMessageIndex = idx + 1;
                            if (_readMessageIndex > _queue.Length - 1)
                            {
                                _readMessageIndex = 0;                                        // make it circular
                            }
                            sw.Stop();
                            return(retMsg);
                        }
                    }
                    for (int idx = 0; idx < _receiveMessageIndex; idx++)
                    {
                        if (_queue[idx].getID() == this.m_waitMsgID || _queue[idx].getID() == this.m_additionalWaitMsgID)
                        {
                            retMsg            = _queue[idx];
                            _readMessageIndex = idx + 1;
                            if (_readMessageIndex > _queue.Length - 1)
                            {
                                _readMessageIndex = 0;                                        // make it circular
                            }
                            sw.Stop();
                            return(retMsg);
                        }
                    }
                }
                else
                {
                    for (int idx = _readMessageIndex; idx < _receiveMessageIndex; idx++)
                    {
                        if (_queue[idx].getID() == this.m_waitMsgID || _queue[idx].getID() == this.m_additionalWaitMsgID)
                        {
                            retMsg            = _queue[idx];
                            _readMessageIndex = idx + 1;
                            if (_readMessageIndex > _queue.Length - 1)
                            {
                                _readMessageIndex = 0;                                        // make it circular
                            }
                            sw.Stop();
                            return(retMsg);
                        }
                    }
                }
                Thread.Sleep(1);
            }
            sw.Stop();
            return(retMsg);
        }
Exemplo n.º 30
0
        /// <summary>
        /// waitAnyMessage waits for any message to be received.
        /// </summary>
        /// <param name="timeout">Listen timeout</param>
        /// <param name="r_canMsg">The CAN message that was first received</param>
        /// <returns>The CAN id for the message received, otherwise 0.</returns>
        private uint waitAnyMessage(uint timeout, out CANMessage canMessage)
        {
            canMessage = new CANMessage();
            Debug.Assert(canMessage != null);

            int wait_cnt = 0;
            uint id;
            byte length;
            ulong data;
            while (wait_cnt < timeout)
            {
            if (MctAdapter_ReceiveMessage(out id, out length, out data))
            {
                // message received
                canMessage.setID(id);
                canMessage.setLength(length);
                canMessage.setData(data);

                return id;
            }

            // wait a bit
            Thread.Sleep(1);
            ++wait_cnt;
            }

            // nothing was received
            return 0;
        }
Exemplo n.º 31
0
        public CANMessage waitMessage(int a_timeout)
        {
            sw.Reset();
            sw.Start();
            CANMessage retMsg = new CANMessage();

            while (sw.ElapsedMilliseconds < a_timeout)
            {
                // search queue for the desired message
                if (_receiveMessageIndex < _readMessageIndex)
                {
                    // first upto (_queue.Length - 1)
                    for (int idx = _readMessageIndex; idx < _queue.Length; idx++)
                    {
                        if (_queue[idx].getID() == this.m_waitMsgID)
                        {
                            retMsg            = _queue[idx];
                            _readMessageIndex = idx + 1;
                            if (_readMessageIndex > _queue.Length - 1)
                            {
                                _readMessageIndex = 0;                                        // make it circular
                            }
                            sw.Stop();
                            return(retMsg);
                        }
                    }
                    for (int idx = 0; idx < _receiveMessageIndex; idx++)
                    {
                        if (_queue[idx].getID() == this.m_waitMsgID)
                        {
                            retMsg            = _queue[idx];
                            _readMessageIndex = idx + 1;
                            if (_readMessageIndex > _queue.Length - 1)
                            {
                                _readMessageIndex = 0;                                        // make it circular
                            }
                            sw.Stop();
                            return(retMsg);
                        }
                    }
                }
                else
                {
                    for (int idx = _readMessageIndex; idx < _receiveMessageIndex; idx++)
                    {
                        if (_queue[idx].getID() == this.m_waitMsgID)
                        {
                            retMsg            = _queue[idx];
                            _readMessageIndex = idx + 1;
                            if (_readMessageIndex > _queue.Length - 1)
                            {
                                _readMessageIndex = 0;                                        // make it circular
                            }
                            sw.Stop();
                            return(retMsg);
                        }
                    }
                }
                Thread.Sleep(1);
            }
            sw.Stop();
            return(retMsg);

            /*
             * CANMessage retMsg;
             *
             * m_resetEvent.WaitOne(a_timeout, true);
             * lock (m_canMessage)
             * {
             *  retMsg = m_canMessage;
             * }
             * messageReceived = false;
             * return retMsg;*/
        }
Exemplo n.º 32
0
 /// <summary>
 /// waitForMessage waits for a specific CAN message give by a CAN id.
 /// </summary>
 /// <param name="a_canID">The CAN id to listen for</param>
 /// <param name="timeout">Listen timeout</param>
 /// <param name="r_canMsg">The CAN message with a_canID that we where listening for.</param>
 /// <returns>The CAN id for the message we where listening for, otherwise 0.</returns>
 public override uint waitForMessage(uint a_canID, uint timeout, out CANMessage canMsg)
 {
     EASYSYNC.CANMsg r_canMsg;
     canMsg = new CANMessage();
     int readResult = 0;
     int nrOfWait = 0;
     while (nrOfWait < timeout)
     {
         r_canMsg = new EASYSYNC.CANMsg();
         readResult = EASYSYNC.canusb_Read(m_deviceHandle, out r_canMsg);
         if (readResult == EASYSYNC.ERROR_CANUSB_OK)
         {
             if (r_canMsg.id == 0x00)
             {
                 nrOfWait++;
             }
             else if (r_canMsg.id != a_canID)
                 continue;
             canMsg.setData(r_canMsg.data);
             canMsg.setID(r_canMsg.id);
             canMsg.setLength(r_canMsg.len);
             return (uint)r_canMsg.id;
         }
         else if (readResult == EASYSYNC.ERROR_CANUSB_NO_MESSAGE)
         {
             Thread.Sleep(1);
             nrOfWait++;
         }
     }
     r_canMsg = new EASYSYNC.CANMsg();
     return 0;
 }
Exemplo n.º 33
0
 abstract public uint waitForMessage(uint a_canID, uint timeout, out CANMessage canMsg);
Exemplo n.º 34
0
        public void readMessages()
        {
            CANMessage canMessage = new CANMessage();

            Console.WriteLine("readMessages started");
            while (true)
            {
                lock (m_synchObject)
                {
                    if (m_endThread)
                    {
                        Console.WriteLine("readMessages ended");
                        return;
                    }
                }
                if (rawString != null)
                {
                    logger.Trace(String.Format("Raw Data: {0}", rawString));
                    //AddToSerialTrace("RAW RX: " + rawString.Replace("\r",m_cr_sequence));
                    string rxString = rawString.Replace("\r", m_cr_sequence); //replace , because stringbuilder cannot handle \r
                    bool isStopped = false;

                    if (rxString.Length > 0)
                    {
                        //AddToSerialTrace("RECEIVE TEXT: " + rxString);
                        //System.Diagnostics.Debug.WriteLine("SERMSG: " + rxString);
                        var lines = ExtractLines(rxString);
                        foreach (var rxMessage in lines)
                        {
                            if (rxMessage.StartsWith("STOPPED")) { isStopped = true; }
                            else if (rxMessage.StartsWith("NO (MORE?) DATA")) { } //skip it
                            else if (rxMessage.StartsWith("CAN ERROR")) { } //handle error?
                            else if (rxMessage.StartsWith("ELM")) { isStopped = false; } //skip it, this is a trick to stop ELM from listening to more messages and send ready char
                            else if (rxMessage.StartsWith("?")) { isStopped = false; }
                            else if (rxMessage.Length == 19) // is it a valid line
                            {
                                try
                                {
                                    rxMessage.Replace(" ", "");//remove all whitespaces
                                    uint id = Convert.ToUInt32(rxMessage.Substring(0, 3), 16);
                                    if (acceptMessageId(id))
                                    {
                                        canMessage.setID(id);
                                        canMessage.setLength(8); // TODO: alter to match data
                                        //canMessage.setData(0x0000000000000000); // reset message content
                                        canMessage.setData(ExtractDataFromString(rxMessage));

                                        receivedMessage(canMessage);
                                    }
                                }
                                catch (Exception)
                                {
                                    //Console.WriteLine("MSG: " + rxMessage);
                                }
                            }
                            //disable whitespace logging
                            if (rxMessage.Length > 0)
                            {
                                logger.Debug("TELNET: " + rxMessage);
                            }
                        }
                    }
                    if (!isStopped)
                    {
                        logger.Debug("TELNET READY");
                        interfaceBusy = false;
                    }
                    rawString = null;
                }
            }
        }
Exemplo n.º 35
0
        //---------------------------------------------------------------------------------------------
        /**
        Sends a 11 bit CAN data frame.

        @param      msg         CAN message

        @return                 success (true/false)
        */
        public override bool sendMessage(CANMessage msg)
        {
            this.AddToCanTrace("Sending message: " + msg.getID().ToString("X4") + " " + msg.getData().ToString("X16") + " " + msg.getLength().ToString("X2"));

            try
            {
            Combi.caCombiAdapter.caCANFrame frame;
            frame.id = msg.getID();
            frame.length = msg.getLength();
            frame.data = msg.getData();
            frame.is_extended = 0;
            frame.is_remote = 0;

            this.combi.CAN_SendMessage(ref frame);

            this.AddToCanTrace("Message sent successfully");
            return true;
            }

            catch (Exception e)
            {
            this.AddToCanTrace("Message failed to send: " + e.Message);
            return false;
            }
        }
Exemplo n.º 36
0
        protected override bool sendMessageDevice(CANMessage a_message)
        {
            lock (lockObj)
            {
                interfaceBusy = true;
                if (a_message.getID() != _ECUAddress)
                {
                    _ECUAddress = a_message.getID();

                    string command = String.Format("ATSH{0:X3}\r", a_message.getID());
                    SendControlMessage(command, false);
                }

                lastSentCanMessage = a_message.Clone();
                string sendString = GetELMRequest(a_message);

                //add expected responses, but this has to be one char only :(
                if (a_message.elmExpectedResponses != -1 && a_message.elmExpectedResponses < 16)
                    sendString += " " + a_message.elmExpectedResponses.ToString("X1");

                sendString += "\r";

                lastSentTimestamp = Environment.TickCount;
                rawString = WriteToTelnetAndWait(sendString);

                return true; // remove after implementation
            }
        }
Exemplo n.º 37
0
        //---------------------------------------------------------------------------------------------
        /**
        Tries to connect to CAN bus using the specified bitrate.

        @param      bitrate             bitrate
        @param      check_traffic       check for CAN traffic

        @return                         succ / fail
        */
        private bool try_bitrate(uint bitrate, bool check_traffic)
        {
            try
            {
            // try connecting
            this.combi.CAN_SetBitrate(bitrate);
            this.combi.CAN_Open(true);

            if (check_traffic)
            {
                // look for bus activity
                CANMessage msg = new CANMessage();
                Debug.Assert(msg != null);

                if (this.waitForMessage(0, 1000, out msg) < 1)
                {
                    throw new Exception("No traffic at given bitrate");
                }
            }

            return true;
            }

            catch
            {
            // failed
            this.combi.CAN_Open(false);
            return false;
            }
        }
Exemplo n.º 38
0
 /// <summary>
 /// readMessages is the "run" method of this class. It reads all incomming messages
 /// and publishes them to registered ICANListeners.
 /// </summary>
 public void readMessages()
 {
     int readResult = 0;
     EASYSYNC.CANMsg r_canMsg = new EASYSYNC.CANMsg();
     CANMessage canMessage = new CANMessage();
     while (true)
     {
         lock (m_synchObject)
         {
             if (m_endThread)
                 return;
         }
         readResult = EASYSYNC.canusb_Read(m_deviceHandle, out r_canMsg);
         if (readResult == EASYSYNC.ERROR_CANUSB_OK)
         {
             canMessage.setID(r_canMsg.id);
             canMessage.setLength(r_canMsg.len);
             canMessage.setTimeStamp(r_canMsg.timestamp);
             canMessage.setFlags(r_canMsg.flags);
             canMessage.setData(r_canMsg.data);
             lock (m_listeners)
             {
                 foreach (ICANListener listener in m_listeners)
                 {
                     listener.handleMessage(canMessage);
                 }
             }
         }
         else if (readResult == EASYSYNC.ERROR_CANUSB_NO_MESSAGE)
         {
             Thread.Sleep(1);
         }
     }
 }
Exemplo n.º 39
0
 public InformationFrameEventArgs(CANMessage message)
 {
     this._message = message;
 }
Exemplo n.º 40
0
        /// <summary>
        /// sendMessage send a CANMessage.
        /// </summary>
        /// <param name="a_message">A CANMessage.</param>
        /// <returns>true on success, othewise false.</returns>
        public override bool sendMessage(CANMessage a_message)
        {
            lock (lockObj)
            {
                while (interfaceBusy)
                {
                    if (lastSentTimestamp < Environment.TickCount - timeoutWithoutReadyChar)
                    {
                        //Console.WriteLine("released");
                        break;
                    }
                }

                lastSentTimestamp = Environment.TickCount;
                interfaceBusy = true;
                //Console.WriteLine("set");

                Lawicel.CANUSB.CANMsg msg = new Lawicel.CANUSB.CANMsg();
                msg.id = a_message.getID();
                msg.len = a_message.getLength();
                msg.flags = a_message.getFlags();
                msg.data = a_message.getData();

                if (m_serialPort.IsOpen)
                {
                    //m_serialPort.Write("\r");
                    string txstring = "t";
                    txstring += msg.id.ToString("X3");
                    txstring += "8"; // always 8 bytes to transmit
                    for (int t = 0; t < 8; t++)
                    {
                        byte b = (byte)(((msg.data >> t * 8) & 0x0000000000000000FF));
                        txstring += b.ToString("X2");
                    }
                    txstring += "\r";
                    AddToCanTrace(string.Format("TX: {0} {1} {2}", a_message.getID().ToString("X3"), a_message.getData().ToString("X16"), txstring));
                    m_serialPort.Write(txstring);
                    return true;
                }
            }
            return false;
        }
Exemplo n.º 41
0
 /// <summary>
 /// sendMessage send a CANMessage.
 /// </summary>
 /// <param name="a_message">A CANMessage.</param>
 /// <returns>true on success, othewise false.</returns>
 public override bool sendMessage(CANMessage a_message)
 {
     Lawicel.CANUSB.CANMsg msg = new Lawicel.CANUSB.CANMsg();
     msg.id = a_message.getID();
     msg.len = a_message.getLength();
     msg.flags = a_message.getFlags();
     msg.data = a_message.getData();
     int writeResult;
     AddToCanTrace("TX: " + msg.id.ToString("X4") + " " + msg.data.ToString("X16"));
     writeResult = Lawicel.CANUSB.canusb_Write(m_deviceHandle, ref msg);
     if (writeResult == Lawicel.CANUSB.ERROR_CANUSB_OK)
     {
         AddToCanTrace("Message sent successfully");
         return true;
     }
     else
     {
         switch (writeResult)
         {
             case Lawicel.CANUSB.ERROR_CANUSB_COMMAND_SUBSYSTEM:
                 AddToCanTrace("Message failed to send: ERROR_CANUSB_COMMAND_SUBSYSTEM");
                 break;
             case Lawicel.CANUSB.ERROR_CANUSB_INVALID_PARAM:
                 AddToCanTrace("Message failed to send: ERROR_CANUSB_INVALID_PARAM");
                 break;
             case Lawicel.CANUSB.ERROR_CANUSB_NO_MESSAGE:
                 AddToCanTrace("Message failed to send: ERROR_CANUSB_NO_MESSAGE");
                 break;
             case Lawicel.CANUSB.ERROR_CANUSB_NOT_OPEN:
                 AddToCanTrace("Message failed to send: ERROR_CANUSB_NOT_OPEN");
                 break;
             case Lawicel.CANUSB.ERROR_CANUSB_OPEN_SUBSYSTEM:
                 AddToCanTrace("Message failed to send: ERROR_CANUSB_OPEN_SUBSYSTEM");
                 break;
             case Lawicel.CANUSB.ERROR_CANUSB_TX_FIFO_FULL:
                 AddToCanTrace("Message failed to send: ERROR_CANUSB_TX_FIFO_FULL");
                 break;
             default:
                 AddToCanTrace("Message failed to send: " + writeResult.ToString());
                 break;
         }
         return false;
     }
 }
Exemplo n.º 42
0
        /// <summary>
        /// waitAnyMessage waits for any message to be received.
        /// </summary>
        /// <param name="timeout">Listen timeout</param>
        /// <param name="r_canMsg">The CAN message that was first received</param>
        /// <returns>The CAN id for the message received, otherwise 0.</returns>
        private uint waitAnyMessage(uint timeout, out Lawicel.CANUSB.CANMsg r_canMsg)
        {
            CANMessage canMessage = new CANMessage();

            string line = string.Empty;

            int readResult = 0;
            int nrOfWait = 0;
            while (nrOfWait < timeout)
            {
                m_serialPort.Write("\r");
                m_serialPort.Write("P\r");
                bool endofFrames = false;
                while (!endofFrames)
                {
                    Console.WriteLine("reading line");
                    line = m_serialPort.ReadLine();
                    Console.WriteLine("line: " + line + " len: " + line.Length.ToString());
                    if (line[0] == '\x07' || line[0] == '\r' || line[0] == 'A')
                    {
                        endofFrames = true;
                    }
                    else
                    {

                        if (line.Length == 14)
                        {
                            // three bytes identifier
                            r_canMsg = new Lawicel.CANUSB.CANMsg();
                            r_canMsg.id = (uint)Convert.ToInt32(line.Substring(1, 3), 16);
                            r_canMsg.len = (byte)Convert.ToInt32(line.Substring(4, 1), 16);
                            ulong data = 0;
                            // add all the bytes
                            data |= (ulong)(byte)Convert.ToInt32(line.Substring(5, 2), 16) << 7 * 8;
                            data |= (ulong)(byte)Convert.ToInt32(line.Substring(7, 2), 16) << 6 * 8;
                            data |= (ulong)(byte)Convert.ToInt32(line.Substring(9, 2), 16) << 5 * 8;
                            data |= (ulong)(byte)Convert.ToInt32(line.Substring(11, 2), 16) << 4 * 8;
                            data |= (ulong)(byte)Convert.ToInt32(line.Substring(13, 2), 16) << 3 * 8;
                            data |= (ulong)(byte)Convert.ToInt32(line.Substring(15, 2), 16) << 2 * 8;
                            data |= (ulong)(byte)Convert.ToInt32(line.Substring(17, 2), 16) << 1 * 8;
                            data |= (ulong)(byte)Convert.ToInt32(line.Substring(19, 2), 16);
                            r_canMsg.data = data;
                            canMessage.setID(r_canMsg.id);
                            canMessage.setLength(r_canMsg.len);
                            canMessage.setFlags(0);
                            canMessage.setData(r_canMsg.data);

                            return (uint)r_canMsg.id;

                        }
                    }

                }
                //Thread.Sleep(0);
                nrOfWait++;
            }
            r_canMsg = new Lawicel.CANUSB.CANMsg();
            return 0;
        }
Exemplo n.º 43
0
        /// <summary>
        /// Send a message that starts a session. This is used to test if there is 
        /// a connection.
        /// </summary>
        /// <returns></returns>
        private bool sendSessionRequest()
        {
            Console.WriteLine("Sending session request");
            // 0x220 is for T7
            // 0x7E0 is for T8
            CANMessage msg1 = new CANMessage(0x220, 0, 8);
            Lawicel.CANUSB.CANMsg msg = new Lawicel.CANUSB.CANMsg();
            msg1.setData(0x000040021100813f);

            if (!sendMessage(msg1))
            {
                Console.WriteLine("Unable to send session request");
                return false;
            }
            if (waitForMessage(0x238, 1000, out msg) == 0x238)
            {
                //Ok, there seems to be a ECU somewhere out there.
                //Now, sleep for 10 seconds to get a session timeout. This is needed for
                //applications on higher level. Otherwise there will be no reply when the
                //higher level application tries to start a session.
                Thread.Sleep(10000);
                Console.WriteLine("sendSessionRequest: TRUE");

                return true;
            }
            Console.WriteLine("sendSessionRequest: FALSE");
            return false;
        }
Exemplo n.º 44
0
        /// <summary>
        /// readMessages is the "run" method of this class. It reads all incomming messages
        /// and publishes them to registered ICANListeners.
        /// </summary>
        public void readMessages()
        {
            int readResult = 0;
            Lawicel.CANUSB.CANMsg r_canMsg = new Lawicel.CANUSB.CANMsg();
            CANMessage canMessage = new CANMessage();
            logger.Debug("readMessages started");
            while (true)
            {
                lock (m_synchObject)
                {
                    if (m_endThread)
                    {
                        logger.Debug("readMessages thread ended");
                        return;
                    }
                }
                readResult = Lawicel.CANUSB.canusb_Read(m_deviceHandle, out r_canMsg);
                if (readResult == Lawicel.CANUSB.ERROR_CANUSB_OK)
                {
                    if (acceptMessageId(r_canMsg.id))
                    {
                        canMessage.setID(r_canMsg.id);
                        canMessage.setLength(r_canMsg.len);
                        canMessage.setTimeStamp(r_canMsg.timestamp);
                        canMessage.setFlags(r_canMsg.flags);
                        canMessage.setData(r_canMsg.data);

                        receivedMessage(canMessage);
                    }
                }
                else if (readResult == Lawicel.CANUSB.ERROR_CANUSB_NO_MESSAGE)
                {
                    Thread.Sleep(1);
                }
            }
        }
Exemplo n.º 45
0
 /// <summary>
 /// This method is called by ICANDevices where derived objects of this class
 /// are registered. The method is called for each received CANMessage.
 /// What this method does is application dependent.
 /// </summary>
 /// <param name="a_canMessage">The CANMessage to be handled by this method.</param>
 public abstract void handleMessage(CANMessage a_canMessage);
Exemplo n.º 46
0
 /// <summary>
 /// sendMessage send a CANMessage.
 /// </summary>
 /// <param name="a_message">A CANMessage.</param>
 /// <returns>true on success, othewise false.</returns>
 protected override bool sendMessageDevice(CANMessage a_message)
 {
     Lawicel.CANUSB.CANMsg msg = new Lawicel.CANUSB.CANMsg();
     msg.id = a_message.getID();
     msg.len = a_message.getLength();
     msg.flags = a_message.getFlags();
     msg.data = a_message.getData();
     int writeResult;
     writeResult = Lawicel.CANUSB.canusb_Write(m_deviceHandle, ref msg);
     if (writeResult == Lawicel.CANUSB.ERROR_CANUSB_OK)
     {
         return true;
     }
     else
     {
         logger.Debug("tx failed writeResult: " + writeResult);
         return false;
     }
 }
Exemplo n.º 47
0
        public void readMessages()
        {
            CANMessage canMessage = new CANMessage();

            Console.WriteLine("readMessages started");
            while (true)
            {
                lock (m_synchObject)
                {
                    if (m_endThread)
                    {
                        Console.WriteLine("readMessages ended");
                        return;
                    }
                }
                if (rawString != null)
                {
                    logger.Trace(String.Format("Raw Data: {0}", rawString));
                    //AddToSerialTrace("RAW RX: " + rawString.Replace("\r",m_cr_sequence));
                    string rxString  = rawString.Replace("\r", m_cr_sequence); //replace , because stringbuilder cannot handle \r
                    bool   isStopped = false;

                    if (rxString.Length > 0)
                    {
                        //AddToSerialTrace("RECEIVE TEXT: " + rxString);
                        //System.Diagnostics.Debug.WriteLine("SERMSG: " + rxString);
                        var lines = ExtractLines(rxString);
                        foreach (var rxMessage in lines)
                        {
                            if (rxMessage.StartsWith("STOPPED"))
                            {
                                isStopped = true;
                            }
                            else if (rxMessage.StartsWith("NO (MORE?) DATA"))
                            {
                            }                                                     //skip it
                            else if (rxMessage.StartsWith("CAN ERROR"))
                            {
                            }                                               //handle error?
                            else if (rxMessage.StartsWith("ELM"))
                            {
                                isStopped = false;
                            }                                                            //skip it, this is a trick to stop ELM from listening to more messages and send ready char
                            else if (rxMessage.StartsWith("?"))
                            {
                                isStopped = false;
                            }
                            else if (rxMessage.Length == 19) // is it a valid line
                            {
                                try
                                {
                                    rxMessage.Replace(" ", "");//remove all whitespaces
                                    uint id = Convert.ToUInt32(rxMessage.Substring(0, 3), 16);
                                    if (acceptMessageId(id))
                                    {
                                        canMessage.setID(id);
                                        canMessage.setLength(8); // TODO: alter to match data
                                        //canMessage.setData(0x0000000000000000); // reset message content
                                        canMessage.setData(ExtractDataFromString(rxMessage));

                                        receivedMessage(canMessage);
                                    }
                                }
                                catch (Exception)
                                {
                                    //Console.WriteLine("MSG: " + rxMessage);
                                }
                            }
                            //disable whitespace logging
                            if (rxMessage.Length > 0)
                            {
                                logger.Debug("TELNET: " + rxMessage);
                            }
                        }
                    }
                    if (!isStopped)
                    {
                        logger.Debug("TELNET READY");
                        interfaceBusy = false;
                    }
                    rawString = null;
                }
            }
        }
Exemplo n.º 48
0
 abstract protected bool sendMessageDevice(CANMessage a_message);
Exemplo n.º 49
0
        //---------------------------------------------------------------------------------------------
        /**
        Sends a 11 bit CAN data frame.

        @param      msg         CAN message

        @return                 success (true/false)
        */
        protected override bool sendMessageDevice(CANMessage msg)
        {
            try
            {
            caCombiAdapter.caCANFrame frame;
            frame.id = msg.getID();
            frame.length = msg.getLength();
            frame.data = msg.getData();
            frame.is_extended = 0;
            frame.is_remote = 0;

            combi.CAN_SendMessage(ref frame);
            return true;
            }
            catch (Exception e)
            {
            logger.Debug("tx failed with Exception.Message: " + e.Message);
            return false;
            }
        }
Exemplo n.º 50
0
        protected override bool sendMessageDevice(CANMessage a_message)
        {
            lock (lockObj)
            {
                sendDataSempahore.WaitOne(timeoutWithoutReadyChar);
                interfaceBusy = true;
                if (a_message.getID() != _ECUAddress)
                {
                    _ECUAddress = a_message.getID();

                    string command = "ATSH" + a_message.getID().ToString("X3") + "\r";
                    SendControlMessage(command, false);
                }

                //check if it is beneficial to send ATR0 and ATR1 for ELM clones
                if (!supports8ByteResponse)
                {
                    if ((a_message.elmExpectedResponses == 0) != request0Responses)
                    {
                        if (a_message.elmExpectedResponses == 0)
                        {
                            SendControlMessage("ATR0\r", false);
                            request0Responses = true;
                        }
                        else
                        {
                            SendControlMessage("ATR1\r", false);
                            request0Responses = false;
                        }
                    }
                }
                lastSentCanMessage = a_message.Clone();
                string sendString = GetELMRequest(a_message);


                if (sendString.Length == 16 && !supports8ByteResponse)
                {
                    bool canIgnoreLastByte = a_message.getCanData(7) == 0;
                    if (canIgnoreLastByte)
                    {
                        sendString = sendString.Substring(0, 14);
                    }
                }

                if (sendString.Length <= 14 || supports8ByteResponse) //ELM 2.0 supports 8 bytes + response  count, previous versions dont
                {
                    //add expected responses, but this has to be one char only :(
                    if (a_message.elmExpectedResponses != -1 && a_message.elmExpectedResponses < 16)
                    {
                        sendString += " " + a_message.elmExpectedResponses.ToString("X1");
                    }
                }
                sendString += "\r";

                if (m_serialPort.IsOpen)
                {
                    lastSentTimestamp = Environment.TickCount;
                    WriteToSerialWithTrace(sendString);
                }
                return(true); // remove after implementation
            }
        }
Exemplo n.º 51
0
 public override uint waitForMessage(uint a_canID, uint timeout, out CANMessage canMsg)
 {
     canMsg = new CANMessage();
     return 0;
 }
Exemplo n.º 52
0
        // int thrdcnt = 0;
        /// <summary>
        /// readMessages is the "run" method of this class. It reads all incomming messages
        /// and publishes them to registered ICANListeners.
        /// </summary>
        public void readMessages()
        {
            while (true)
            {
                lock (m_synchObject)
                {
                    if (m_endThread)
                    {
                        m_endThread = false;
                        return;
                    }
                }
                if (m_serialPort.IsOpen)
                {
                    // read the status?

                    string line = string.Empty;

                    try
                    {
                        line = m_serialPort.ReadLine();
                        if (line.Length > 0)
                        {
                            if (line.Length == 25)
                            {
                                Lawicel.CANUSB.CANMsg r_canMsg = new Lawicel.CANUSB.CANMsg();
                                canMessage = new CANMessage();
                                // three bytes identifier
                                r_canMsg.id = (uint)Convert.ToInt32(line.Substring(1, 3), 16);
                                r_canMsg.len = (byte)Convert.ToInt32(line.Substring(4, 1), 16);
                                ulong data = 0;
                                // add all the bytes
                                data |= (ulong)(byte)Convert.ToInt32(line.Substring(5, 2), 16);
                                data |= (ulong)(byte)Convert.ToInt32(line.Substring(7, 2), 16) << 1 * 8;
                                data |= (ulong)(byte)Convert.ToInt32(line.Substring(9, 2), 16) << 2 * 8;
                                data |= (ulong)(byte)Convert.ToInt32(line.Substring(11, 2), 16) << 3 * 8;
                                data |= (ulong)(byte)Convert.ToInt32(line.Substring(13, 2), 16) << 4 * 8;
                                data |= (ulong)(byte)Convert.ToInt32(line.Substring(15, 2), 16) << 5 * 8;
                                data |= (ulong)(byte)Convert.ToInt32(line.Substring(17, 2), 16) << 6 * 8;
                                data |= (ulong)(byte)Convert.ToInt32(line.Substring(19, 2), 16) << 7 * 8;
                                r_canMsg.data = data;
                                canMessage.setID(r_canMsg.id);
                                canMessage.setLength(r_canMsg.len);
                                canMessage.setFlags(r_canMsg.flags);
                                canMessage.setData(r_canMsg.data);

                                lock (m_listeners)
                                {
                                    AddToCanTrace(string.Format("RX: {0} {1} {2}", canMessage.getID().ToString("X3"), line.Substring(5, 16), line));
                                    foreach (ICANListener listener in m_listeners)
                                    {
                                        listener.handleMessage(canMessage);
                                    }
                                }
                            }
                            else if(line.Contains("z"))
                            {
                                interfaceBusy = false;
                                //Console.WriteLine("clear");
                            }
                            else if (line.Length == 2 && Convert.ToInt32(line.Substring(1, 2), 16) != 0x07)
                            {
                                //Console.WriteLine("Send error");
                            }
                            else
                            {
                                //Console.WriteLine("Unknown message: " + line);
                            }
                        }
                    }
                    catch (Exception E)
                    {
                        Console.WriteLine("Failed to read frames from CANbus: " + E.Message);
                    }
                }
                //Thread.Sleep(2);
                Thread.Sleep(delayTimespan); // give others some air
            }
        }
Exemplo n.º 53
0
 /// <summary>
 /// Creates valid request string for ELM device. Calculates data size and formats it automatically
 /// </summary>
 /// <param name="input"></param>
 /// <returns></returns>
 private static string GetELMRequest(CANMessage msg)
 {
     ulong reversed = BitTools.ReverseOrder(msg.getData());
     //var length = BitTools.GetDataSize(reversed);
     return reversed.ToString("X16").Substring(0, msg.getLength() * 2);
 }
Exemplo n.º 54
0
 /// <summary>
 /// This message sends a CANMessage to the CAN device.
 /// The open method must have been called and returned possitive result
 /// before this method is called.
 /// </summary>
 /// <param name="a_message">The CANMessage</param>
 /// <returns>true on success, otherwise false.</returns>
 abstract public bool sendMessage(CANMessage a_message);