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 } }
public override bool sendMessage(CANMessage a_message) { string sendString = "t"; sendString += a_message.getID().ToString("X3"); sendString += a_message.getLength().ToString("X1"); for (uint i = 0; i < a_message.getLength(); i++) // leave out the length field, the ELM chip assigns that for us { sendString += a_message.getCanData(i).ToString("X2"); } sendString += "\r"; if (m_serialPort.IsOpen) { AddToCanTrace("TX: " + a_message.getID().ToString("X3") + " " + a_message.getLength().ToString("X1") + " " + a_message.getData().ToString("X16")); m_serialPort.Write(sendString); //Console.WriteLine("TX: " + sendString); } // bitrate = 38400bps -> 3840 bytes per second // sending each byte will take 0.2 ms approx //Thread.Sleep(a_message.getLength()); // sleep length ms // Thread.Sleep(10); Thread.Sleep(1); return(true); // remove after implementation }
/// <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); }
//--------------------------------------------------------------------------------------------- /** * 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); } }
public override bool sendMessage(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 (a_message.getLength() < 8 || 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); AddToCanTrace(string.Format("TX: {0} {1}", a_message.getID().ToString("X3"), sendString)); } return(true); // remove after implementation } }
override public 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(); }
protected override bool sendMessageDevice(CANMessage a_message) { if (!m_serialPort.IsOpen) { return(false); } string sendString = "t"; sendString += a_message.getID().ToString("X3"); sendString += a_message.getLength().ToString("X1"); for (uint i = 0; i < a_message.getLength(); i++) // leave out the length field, the ELM chip assigns that for us { sendString += a_message.getCanData(i).ToString("X2"); } sendString += "\r"; m_serialPort.Write(sendString); //logger.Debug("TX: " + sendString); // bitrate = 38400bps -> 3840 bytes per second // sending each byte will take 0.2 ms approx //Thread.Sleep(a_message.getLength()); // sleep length ms // Thread.Sleep(10); Thread.Sleep(1); return(true); // remove after implementation }
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(); } } }
//--------------------------------------------------------------------------------------------- /** * 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; if (!UseOnlyPBus) { Thread.Sleep(4); } combi.CAN_SendMessage(ref frame); return(true); } catch (Exception e) { logger.Debug("tx failed with Exception.Message: " + e.Message); return(false); } }
/// <summary> /// This method 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> public bool sendMessage(CANMessage a_message) { bool result = sendMessageDevice(a_message); string prefix = result == true ? "tx:" : "tx failed:"; logger.Trace(String.Format("{0} {1:X3} {2:X16}", prefix, a_message.getID(), BitTools.ReverseOrder(a_message.getData()))); return(result); }
public void readMessages() { CANMessage canMessage = new CANMessage(); string rxMessage = string.Empty; Console.WriteLine("readMessages started"); while (true) { lock (m_synchObject) { if (m_endThread) { Console.WriteLine("readMessages ended"); return; } } try { if (m_serialPort.IsOpen) { do { 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 } while (rxMessage.StartsWith("w") == false); uint id = Convert.ToUInt32(rxMessage.Substring(1, 3), 16); if (acceptMessageId(id)) { 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); } lock (m_listeners) { AddToCanTrace("RX: " + canMessage.getID().ToString("X3") + " " + canMessage.getLength().ToString("X1") + " " + canMessage.getData().ToString("X16")); //Console.WriteLine("MSG: " + rxMessage); foreach (ICANListener listener in m_listeners) { listener.handleMessage(canMessage); } } } } } catch (Exception) { Console.WriteLine("MSG: " + rxMessage); } } }
/// <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); }
public void receivedMessage(CANMessage a_message) { lock (m_listeners) { logger.Trace(String.Format("rx: {0:X3} {1:X16}", a_message.getID(), BitTools.ReverseOrder(a_message.getData()))); foreach (ICANListener listener in m_listeners) { listener.handleMessage(a_message); } } }
/*private void AddToCanTrace(string line) * { * if (m_EnableCanLog) * { * DateTime dtnow = DateTime.Now; * using (StreamWriter sw = new StreamWriter(System.Windows.Forms.Application.StartupPath + "\\CanTraceCANUSBDevice.txt", true)) * { * sw.WriteLine(dtnow.ToString("dd/MM/yyyy HH:mm:ss") + " - " + line); * } * } * }*/ /// <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) { EASYSYNC.CANMsg msg = new EASYSYNC.CANMsg(); msg.id = a_message.getID(); msg.len = a_message.getLength(); msg.flags = a_message.getFlags(); msg.data = a_message.getData(); //Console.WriteLine("Data to send: " + msg.data.ToString("X16")); //Console.WriteLine("Data (original) to send: " + a_message.getData().ToString("X16")); int writeResult; AddToCanTrace("Sending message"); writeResult = EASYSYNC.canusb_Write(m_deviceHandle, ref msg); if (writeResult == EASYSYNC.ERROR_CANUSB_OK) { AddToCanTrace("Message sent successfully"); return(true); } else { switch (writeResult) { case EASYSYNC.ERROR_CANUSB_COMMAND_SUBSYSTEM: AddToCanTrace("Message failed to send: ERROR_CANUSB_COMMAND_SUBSYSTEM"); break; case EASYSYNC.ERROR_CANUSB_INVALID_PARAM: AddToCanTrace("Message failed to send: ERROR_CANUSB_INVALID_PARAM"); break; case EASYSYNC.ERROR_CANUSB_NO_MESSAGE: AddToCanTrace("Message failed to send: ERROR_CANUSB_NO_MESSAGE"); break; case EASYSYNC.ERROR_CANUSB_NOT_OPEN: AddToCanTrace("Message failed to send: ERROR_CANUSB_NOT_OPEN"); break; case EASYSYNC.ERROR_CANUSB_OPEN_SUBSYSTEM: AddToCanTrace("Message failed to send: ERROR_CANUSB_OPEN_SUBSYSTEM"); break; case EASYSYNC.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); } }
/// <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) { byte[] msg = a_message.getDataAsByteArray(); writeStatus = Canlib.canWrite(handleWrite, (int)a_message.getID(), msg, a_message.getLength(), 0); if (writeStatus == Canlib.canStatus.canOK) { return(true); } else { logger.Debug(String.Format("tx failed with status {0}", writeStatus)); return(false); } }
/// <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); } } }
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(); * }*/ }
/// <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); } }
/// <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; }
// 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 } }
//--------------------------------------------------------------------------------------------- /** 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; } }
// 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 } }
/// <summary> /// Send a KWP request. /// </summary> /// <param name="a_request">A KWP request.</param> /// <param name="r_reply">A KWP reply.</param> /// <returns>The status of the request.</returns> public RequestResult sendRequest(KWPRequest a_request, out KWPReply r_reply) { CANMessage msg = new CANMessage(0x240, 0, 8); uint row = nrOfRowsToSend(a_request.getData()); m_kwpCanListener.setupWaitMessage(0x258); // Send one or several request messages. for (; row > 0; row--) { msg.setData(createCanMessage(a_request.getData(), row - 1)); if (!m_canDevice.sendMessage(msg)) { r_reply = new KWPReply(); return RequestResult.ErrorSending; } } msg = m_kwpCanListener.waitMessage(timeoutPeriod); // msg = m_kwpCanListener.waitForMessage(0x258, timeoutPeriod); // Receive one or several replys and send an ack for each reply. if (msg.getID() == 0x258) { uint nrOfRows = (uint)(msg.getCanData(0) & 0x3F)+ 1; row = 0; if (nrOfRows == 0) throw new Exception("Wrong nr of rows"); //Assume that no KWP reply contains more than 0x200 bytes byte[] reply = new byte[0x200]; reply = collectReply(reply, msg.getData(), row); sendAck(nrOfRows - 1); nrOfRows--; m_kwpCanListener.setupWaitMessage(0x258); while (nrOfRows > 0) { // msg = m_kwpCanListener.waitForMessage(0x258, timeoutPeriod); msg = m_kwpCanListener.waitMessage(timeoutPeriod); if (msg.getID() == 0x258) { row++; reply = collectReply(reply, msg.getData(), row); sendAck(nrOfRows - 1); nrOfRows--; } else { r_reply = new KWPReply(); return RequestResult.Timeout; } } r_reply = new KWPReply(reply, a_request.getNrOfPID()); return RequestResult.NoError; } else { r_reply = new KWPReply(); return RequestResult.Timeout; } }
//------------------------------------------------------------------------- /** * 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())); }
public void readMessages() { CANMessage canMessage = new CANMessage(); StringBuilder receiveText = new StringBuilder(); Console.WriteLine("readMessages started"); while (true) { lock (m_synchObject) { if (m_endThread) { Console.WriteLine("readMessages ended"); return; } } receiveDataSemaphore.WaitOne(); if (m_serialPort != null) { if (m_serialPort.IsOpen) { if (m_serialPort.BytesToRead > 0) { string rawString = m_serialPort.ReadExisting(); //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")) { AddToSerialTrace("NO DATA"); Console.WriteLine("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)); 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); } } } } catch (Exception) { //Console.WriteLine("MSG: " + rxMessage); } } //disable whitespace logging if (rxMessage.Length > 0) { AddToSerialTrace("SERRX: " + rxMessage); } } } if (rawString.Contains(">") && !isStopped) { AddToSerialTrace("SERIAL READY"); sendDataSempahore.WaitOne(0); sendDataSempahore.Release(); interfaceBusy = false; } } } } } }
public override bool sendMessage(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 (a_message.getLength() < 8 || 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); AddToCanTrace(string.Format("TX: {0} {1}", a_message.getID().ToString("X3"), sendString)); } return true; // remove after implementation } }
/// <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; } }
public void readMessages() { CANMessage canMessage = new CANMessage(); string rxMessage = string.Empty; Console.WriteLine("readMessages started"); while (true) { lock (m_synchObject) { if (m_endThread) { Console.WriteLine("readMessages ended"); return; } } try { if (m_serialPort.IsOpen) { do { 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 } while (rxMessage.StartsWith("w") == false); uint id = Convert.ToUInt32(rxMessage.Substring(1, 3), 16); if (acceptMessageId(id)) { 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); lock (m_listeners) { AddToCanTrace("RX: " + canMessage.getID().ToString("X3") + " " + canMessage.getLength().ToString("X1") + " " + canMessage.getData().ToString("X16")); //Console.WriteLine("MSG: " + rxMessage); foreach (ICANListener listener in m_listeners) { listener.handleMessage(canMessage); } } } } } catch (Exception) { Console.WriteLine("MSG: " + rxMessage); } } }
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(); }*/ }
//--------------------------------------------------------------------------------------------- /** 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; } }
public override bool sendMessage(CANMessage a_message) { string sendString = "t"; sendString += a_message.getID().ToString("X3"); sendString += a_message.getLength().ToString("X1"); for (uint i = 0; i < a_message.getLength(); i++) // leave out the length field, the ELM chip assigns that for us { sendString += a_message.getCanData(i).ToString("X2"); } sendString += "\r"; if (m_serialPort.IsOpen) { AddToCanTrace("TX: " + a_message.getID().ToString("X3") + " " + a_message.getLength().ToString("X1") + " " + a_message.getData().ToString("X16")); m_serialPort.Write(sendString); //Console.WriteLine("TX: " + sendString); } // bitrate = 38400bps -> 3840 bytes per second // sending each byte will take 0.2 ms approx //Thread.Sleep(a_message.getLength()); // sleep length ms // Thread.Sleep(10); Thread.Sleep(1); return true; // remove after implementation }
public bool ClearDTCCodes() { bool retval = false; // ClearDiagnosticInformation ($04) Service ulong cmd = 0x0000000000000401; // 7DF 01 04 00 00 00 00 00 00 CANMessage msg = new CANMessage(0x7DF, 0, 2); msg.setData(cmd); msg.elmExpectedResponses = 15; m_canListener.setupWaitMessage(0x7E8); canUsbDevice.SetupCANFilter("7E8", "000"); if (!canUsbDevice.sendMessage(msg)) { CastInfoEvent("Couldn't send message", ActivityType.ConvertingFile); return false; } CANMessage response = new CANMessage(); ulong data = 0; // Wait for response // 7E8 01 44 00 00 00 00 00 00 response = m_canListener.waitMessage(timeoutP2ct); data = response.getData(); // Positive Response if (response.getID() == 0x7E8 && response.getCanData(1) == 0x44) { retval = true; } // RequestCorrectlyReceived-ResponsePending ($78, RC_RCR-RP) else if (response.getCanData(1) == 0x7F && response.getCanData(2) == 0x04 && response.getCanData(3) == 0x78) { // Wait one more second m_canListener.setupWaitMessage(0x7E8); m_canListener.waitMessage(timeoutP2ct); if (response.getID() == 0x7E8 && response.getCanData(1) == 0x44) { retval = true; } } // Other errors else if (response.getCanData(1) == 0x7F && response.getCanData(2) == 0x04) { string info = TranslateErrorCode(response.getCanData(3)); CastInfoEvent("Error: " + info, ActivityType.ConvertingFile); } Send0120(); return retval; }
/// <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; }
/// <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; } }
//------------------------------------------------------------------------- /** 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()); }
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(); }
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 } }
public string[] ReadDTC() { // test code //ulong c = 0x0000006F00070181;//81 01 07 00 6F 00 00 00 //ulong c = 0x000000FD00220181; //81 01 22 00 FD 00 00 00 //CANMessage test = new CANMessage(); //test.setData(c); //AddToCanTrace(GetDtcDescription(test)); // send message to read DTC StartSession10(); listDTC = new List<string>(); // ReadDiagnosticInformation $A9 Service // readStatusOfDTCByStatusMask $81 Request // DTCStatusMask $12= 0001 0010 // 0 Bit 7 warningIndicatorRequestedState // 0 Bit 6 currentDTCSincePowerUp // 0 Bit 5 testNotPassedSinceCurrentPowerUp // 1 Bit 4 historyDTC // 0 Bit 3 testFailedSinceDTCCleared // 0 Bit 2 testNotPassedSinceDTCCleared // 1 Bit 1 currentDTC // 0 Bit 0 DTCSupportedByCalibration ulong cmd = 0x000000001281A903; // 7E0 03 A9 81 12 00 00 00 00 CANMessage msg = new CANMessage(0x7E0, 0, 4); msg.setData(cmd); msg.elmExpectedResponses = 15; m_canListener.setupWaitMessage(0x7E8,0x5e8); canUsbDevice.SetupCANFilter("7E8", "DFF"); // Mask will allow 7E8 and 5E8 if (!canUsbDevice.sendMessage(msg)) { CastInfoEvent("Couldn't send message", ActivityType.ConvertingFile); return listDTC.ToArray(); } CANMessage response = new CANMessage(); ulong data = 0; // Wait for response // 7E8 03 7F A9 78 00 00 00 00 // or the first DTC // 5E8 81 07 03 00 7F 00 00 00 response = m_canListener.waitMessage(timeoutP2ct); data = response.getData(); if (response.getID() == 0x5E8 && response.getCanData(0) == 0x81) { // Now wait for all DTCs m_canListener.setupWaitMessage(0x5E8); bool more_errors = addDTC(response); while (more_errors) { CANMessage responseDTC = new CANMessage(); responseDTC = m_canListener.waitMessage(timeoutP2ct); more_errors = addDTC(responseDTC); } } // RequestCorrectlyReceived-ResponsePending ($78, RC_RCR-RP) else if (response.getCanData(1) == 0x7F && response.getCanData(2) == 0xA9 && response.getCanData(3) == 0x78) { // Now wait for all DTCs m_canListener.setupWaitMessage(0x5E8); bool more_errors = true; while (more_errors) { CANMessage responseDTC = new CANMessage(); responseDTC = m_canListener.waitMessage(timeoutP2ct); more_errors = addDTC(responseDTC); } } else if (response.getCanData(1) == 0x7F && response.getCanData(2) == 0xA9) { string info = TranslateErrorCode(response.getCanData(3)); CastInfoEvent("Error: " + info, ActivityType.ConvertingFile); } Send0120(); return listDTC.ToArray(); }