/// <summary> /// Creates valid request string for ELM device. Calculates data size and formats it automatically /// </summary> /// <param name="input"></param> /// <returns></returns> private string GetELMRequest(CANMessage msg) { ulong reversed = BitTools.ReverseOrder(msg.getData()); //var length = BitTools.GetDataSize(reversed); return(reversed.ToString("X16").Substring(0, msg.getLength() * 2)); }
//--------------------------------------------------------------------------------------------- /** * 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); } }
//--------------------------------------------------------------------------------------------- /** * 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); } }
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(); }
/*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); } }
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(); } } }
/// <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); }
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); } }
//--------------------------------------------------------------------------------------------- /** 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; } }
/// <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); }
/// <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; }
private bool requestDownload011() { CANMessage msg = new CANMessage(0x11, 0, 7); ulong cmd = 0x0000000000003406; msg.setData(cmd); m_canListener.setupWaitMessage(0x311); if (!canUsbDevice.sendMessage(msg)) { CastInfoEvent("Couldn't send message", ActivityType.ConvertingFile); return false; } CANMessage response = new CANMessage(); response = new CANMessage(); response = m_canListener.waitMessage(timeoutP2ct); ulong data = response.getData(); //CastInfoEvent("rx requestDownload: " + data.ToString("X16"), ActivityType.UploadingBootloader); if (getCanData(data, 0) != 0x01 || getCanData(data, 1) != 0x74) { return false; } return true; }
private bool RequestSecurityAccessCIM(int millisecondsToWaitWithResponse) { int secondsToWait = millisecondsToWaitWithResponse / 1000; ulong cmd = 0x0000000000012702; // request security access CANMessage msg = new CANMessage(0x245, 0, 8); msg.setData(cmd); m_canListener.setupWaitMessage(0x645); CastInfoEvent("Requesting security access to CIM", ActivityType.ConvertingFile); if (!canUsbDevice.sendMessage(msg)) { CastInfoEvent("Couldn't send message", ActivityType.ConvertingFile); return false; } CANMessage response = new CANMessage(); response = m_canListener.waitMessage(timeoutP2ct); //ulong data = response.getData(); Console.WriteLine("---" + response.getData().ToString("X16")); if (response.getCanData(1) == 0x67) { if (response.getCanData(2) == 0x01) { CastInfoEvent("Got seed value from CIM", ActivityType.ConvertingFile); while (secondsToWait > 0) { CastInfoEvent("Waiting for " + secondsToWait.ToString() + " seconds...", ActivityType.UploadingBootloader); Thread.Sleep(1000); SendKeepAlive(); secondsToWait--; } byte[] seed = new byte[2]; seed[0] = response.getCanData(3); seed[1] = response.getCanData(4); if (seed[0] == 0x00 && seed[1] == 0x00) { return true; // security access was already granted } else { SeedToKey s2k = new SeedToKey(); byte[] key = s2k.calculateKeyForCIM(seed); CastInfoEvent("Security access CIM : Key (" + key[0].ToString("X2") + key[1].ToString("X2") + ") calculated from seed (" + seed[0].ToString("X2") + seed[1].ToString("X2") + ")", ActivityType.ConvertingFile); ulong keydata = 0x0000000000022704; ulong key1 = key[1]; key1 *= 0x100000000; keydata ^= key1; ulong key2 = key[0]; key2 *= 0x1000000; keydata ^= key2; msg = new CANMessage(0x245, 0, 8); msg.setData(keydata); m_canListener.setupWaitMessage(0x645); if (!canUsbDevice.sendMessage(msg)) { CastInfoEvent("Couldn't send message", ActivityType.ConvertingFile); return false; } response = new CANMessage(); response = m_canListener.waitMessage(timeoutP2ct); // is it ok or not if (response.getCanData(1) == 0x67 && response.getCanData(2) == 0x02) { CastInfoEvent("Security access to CIM granted", ActivityType.ConvertingFile); return true; } else if (response.getCanData(1) == 0x7F && response.getCanData(2) == 0x27) { CastInfoEvent("Error: " + TranslateErrorCode(response.getCanData(3)), ActivityType.ConvertingFile); } } } else if (response.getCanData(2) == 0x02) { CastInfoEvent("Security access to CIM granted", ActivityType.ConvertingFile); return true; } } else if (response.getCanData(1) == 0x7F && response.getCanData(2) == 0x27) { CastInfoEvent("Error: " + TranslateErrorCode(response.getCanData(3)), ActivityType.ConvertingFile); } return false; }
//KWP2000 can read more than 6 bytes at a time.. but for now we are happy with this private byte[] sendReadCommandME96(int address, int length, out bool success) { success = false; byte[] retData = new byte[length]; if (!canUsbDevice.isOpen()) return retData; CANMessage msg = new CANMessage(0x7E0, 0, 8); //optimize reading speed for ELM if (length <= 3) msg.elmExpectedResponses = 1; //Console.WriteLine("Reading " + address.ToString("X8") + " len: " + length.ToString("X2")); ulong cmd = 0x0000000000002307; // always 2 bytes ulong addressHigh = (uint)address & 0x0000000000FF0000; addressHigh /= 0x10000; ulong addressMiddle = (uint)address & 0x000000000000FF00; addressMiddle /= 0x100; ulong addressLow = (uint)address & 0x00000000000000FF; ulong len = (ulong)length; cmd |= (addressLow * 0x10000000000); cmd |= (addressMiddle * 0x100000000); cmd |= (addressHigh * 0x1000000); cmd |= (len * 0x100000000000000); //Console.WriteLine("send: " + cmd.ToString("X16")); /*cmd |= (ulong)(byte)(address & 0x000000FF) << 4 * 8; cmd |= (ulong)(byte)((address & 0x0000FF00) >> 8) << 3 * 8; cmd |= (ulong)(byte)((address & 0x00FF0000) >> 2 * 8) << 2 * 8; cmd |= (ulong)(byte)((address & 0xFF000000) >> 3 * 8) << 8;*/ msg.setData(cmd); m_canListener.setupWaitMessage(0x7E8); if (!canUsbDevice.sendMessage(msg)) { logger.Debug("Couldn't send message"); } // wait for max two messages to get rid of the alive ack message CANMessage response = new CANMessage(); ulong data = 0; response = new CANMessage(); response = m_canListener.waitMessage(timeoutP2ct); data = response.getData(); if (getCanData(data, 0) == 0x7E) { logger.Debug("Got 0x7E message as response to 0x23, readMemoryByAddress command"); success = false; return retData; } else if (response.getData() == 0x00000000) { logger.Debug("Get blank response message to 0x23, readMemoryByAddress"); success = false; return retData; } else if (getCanData(data, 0) == 0x03 && getCanData(data, 1) == 0x7F && getCanData(data, 2) == 0x23 && getCanData(data, 3) == 0x31) { // reason was 0x31 RequestOutOfRange // memory address is either: invalid, restricted, secure + ECU locked // memory size: is greater than max logger.Debug("RequestOutOfRange. No security access granted"); RequestSecurityAccess(0); success = false; return retData; } else if (getCanData(data, 0) == 0x03 && getCanData(data, 1) == 0x7F && getCanData(data, 2) == 0x23) { logger.Debug("readMemoryByAddress " + TranslateErrorCode(getCanData(data, 3))); success = false; return retData; } /*else if (getCanData(data, 0) != 0x10) { AddToCanTrace("Incorrect response message to 0x23, readMemoryByAddress. Byte 0 was " + getCanData(data, 0).ToString("X2")); success = false; return retData; } else if (getCanData(data, 1) != len + 4) { AddToCanTrace("Incorrect length data message to 0x23, readMemoryByAddress. Byte 1 was " + getCanData(data, 1).ToString("X2")); success = false; return retData; }*/ else if (getCanData(data, 2) != 0x63 && getCanData(data, 1) != 0x63) { if (data == 0x0000000000007E01) { // was a response to a KA. } logger.Debug("Incorrect response to 0x23, readMemoryByAddress. Byte 2 was " + getCanData(data, 2).ToString("X2")); success = false; return retData; } //TODO: Check whether we need more than 2 bytes of data and wait for that many records after sending an ACK int rx_cnt = 0; byte frameIndex = 0x21; if (length > 3) { retData[rx_cnt++] = getCanData(data, 7); // in that case, we need more records from the ECU // Thread.Sleep(1); SendAckMessageT8(); // send ack to request more bytes //Thread.Sleep(1); // now we wait for the correct number of records to be received int m_nrFrameToReceive = (length / 7); if (len % 7 > 0) { m_nrFrameToReceive++; } logger.Debug("Number of frames: " + m_nrFrameToReceive.ToString()); while (m_nrFrameToReceive > 0) { // response = new CANMessage(); //response.setData(0); //response.setID(0); // m_canListener.setupWaitMessage(0x7E8); response = m_canListener.waitMessage(timeoutP2ct); data = response.getData(); logger.Debug("frame " + frameIndex.ToString("X2") + ": " + data.ToString("X16")); if (frameIndex != getCanData(data, 0)) { // sequence broken logger.Debug("Received invalid sequenced frame " + frameIndex.ToString("X2") + ": " + data.ToString("X16")); //m_canListener.dumpQueue(); success = false; return retData; } else if (data == 0x0000000000000000) { logger.Debug("Received blank message while waiting for data"); success = false; return retData; } frameIndex++; if (frameIndex == 0x30) { // reset index frameIndex = 0x20; } // additional check for sequencing of frames m_nrFrameToReceive--; logger.Debug("frames left: " + m_nrFrameToReceive.ToString()); // add the bytes to the receive buffer //string checkLine = string.Empty; for (uint fi = 1; fi < 8; fi++) { //checkLine += getCanData(data, fi).ToString("X2"); if (rx_cnt < retData.Length) // prevent overrun { retData[rx_cnt++] = getCanData(data, fi); } } //logger.Debug("frame(2): " + checkLine); //Thread.Sleep(1); } } else { if (retData.Length > rx_cnt) retData[rx_cnt++] = getCanData(data, 5); if (retData.Length > rx_cnt) retData[rx_cnt++] = getCanData(data, 6); if (retData.Length > rx_cnt) retData[rx_cnt++] = getCanData(data, 7); logger.Debug("received data: " + retData[0].ToString("X2")); } /*string line = address.ToString("X8") + " "; foreach (byte b in retData) { line += b.ToString("X2") + " "; } AddToCanTrace(line);*/ success = true; return retData; }
private byte[] sendReadDataByLocalIdentifier(int address, int length, out bool success) { // we send: 0040000000002106 // .. send: 06 21 80 00 00 00 00 00 success = false; byte[] retData = new byte[length]; if (!canUsbDevice.isOpen()) return retData; CANMessage msg = new CANMessage(0x7E0, 0, 7); //Console.WriteLine("Reading " + address.ToString("X8") + " len: " + length.ToString("X2")); ulong cmd = 0x0000000000002106; // always 2 bytes ulong addressHigh = (uint)address & 0x0000000000FF0000; addressHigh /= 0x10000; ulong addressMiddle = (uint)address & 0x000000000000FF00; addressMiddle /= 0x100; ulong addressLow = (uint)address & 0x00000000000000FF; ulong len = (ulong)length; cmd |= (addressLow * 0x1000000000000); cmd |= (addressMiddle * 0x10000000000); cmd |= (addressHigh * 0x100000000); cmd |= (len * 0x10000); // << 2 * 8 //Console.WriteLine("send: " + cmd.ToString("X16")); /*cmd |= (ulong)(byte)(address & 0x000000FF) << 4 * 8; cmd |= (ulong)(byte)((address & 0x0000FF00) >> 8) << 3 * 8; cmd |= (ulong)(byte)((address & 0x00FF0000) >> 2 * 8) << 2 * 8; cmd |= (ulong)(byte)((address & 0xFF000000) >> 3 * 8) << 8;*/ msg.setData(cmd); m_canListener.setupWaitMessage(0x7E8); msg.elmExpectedResponses = 19; //in 19 messages there are 0x82 = 130 bytes of data, bootloader requests 0x80 =128 each time if (!canUsbDevice.sendMessage(msg)) { logger.Debug("Couldn't send message"); } // wait for max two messages to get rid of the alive ack message CANMessage response = new CANMessage(); ulong data = 0; response = new CANMessage(); response = m_canListener.waitMessage(timeoutP2ct); data = response.getData(); if (getCanData(data, 0) == 0x7E) { logger.Debug("Got 0x7E message as response to 0x21, ReadDataByLocalIdentifier command"); success = false; return retData; } else if (response.getData() == 0x00000000) { logger.Debug("Get blank response message to 0x21, ReadDataByLocalIdentifier"); success = false; return retData; } else if (getCanData(data, 0) == 0x03 && getCanData(data, 1) == 0x7F && getCanData(data, 2) == 0x23) { // reason was 0x31 logger.Debug("No security access granted"); RequestSecurityAccess(0); success = false; return retData; } else if (getCanData(data, 2) != 0x61 && getCanData(data, 1) != 0x61) { if (data == 0x0000000000007E01) { // was a response to a KA. } logger.Debug("Incorrect response to 0x23, sendReadDataByLocalIdentifier. Byte 2 was " + getCanData(data, 2).ToString("X2")); success = false; return retData; } //TODO: Check whether we need more than 2 bytes of data and wait for that many records after sending an ACK int rx_cnt = 0; byte frameIndex = 0x21; if (length > 4) { retData[rx_cnt++] = getCanData(data, 4); retData[rx_cnt++] = getCanData(data, 5); retData[rx_cnt++] = getCanData(data, 6); retData[rx_cnt++] = getCanData(data, 7); // in that case, we need more records from the ECU // Thread.Sleep(1); SendAckMessageT8(); // send ack to request more bytes //Thread.Sleep(1); // now we wait for the correct number of records to be received int m_nrFrameToReceive = ((length - 4) / 7); if ((len - 4) % 7 > 0) m_nrFrameToReceive++; //AddToCanTrace("Number of frames: " + m_nrFrameToReceive.ToString()); while (m_nrFrameToReceive > 0) { // response = new CANMessage(); //response.setData(0); //response.setID(0); // m_canListener.setupWaitMessage(0x7E8); response = m_canListener.waitMessage(timeoutP2ct); data = response.getData(); //AddToCanTrace("frame " + frameIndex.ToString("X2") + ": " + data.ToString("X16")); if (frameIndex != getCanData(data, 0)) { // sequence broken logger.Debug("Received invalid sequenced frame " + frameIndex.ToString("X2") + ": " + data.ToString("X16")); m_canListener.dumpQueue(); success = false; return retData; } else if (data == 0x0000000000000000) { logger.Debug("Received blank message while waiting for data"); success = false; return retData; } frameIndex++; if (frameIndex > 0x2F) frameIndex = 0x20; // additional check for sequencing of frames m_nrFrameToReceive--; //AddToCanTrace("frames left: " + m_nrFrameToReceive.ToString()); // add the bytes to the receive buffer //string checkLine = string.Empty; for (uint fi = 1; fi < 8; fi++) { //checkLine += getCanData(data, fi).ToString("X2"); if (rx_cnt < retData.Length) // prevent overrun { retData[rx_cnt++] = getCanData(data, fi); } } //AddToCanTrace("frame(2): " + checkLine); //Thread.Sleep(1); } } else { if (retData.Length > rx_cnt) retData[rx_cnt++] = getCanData(data, 4); if (retData.Length > rx_cnt) retData[rx_cnt++] = getCanData(data, 5); if (retData.Length > rx_cnt) retData[rx_cnt++] = getCanData(data, 6); if (retData.Length > rx_cnt) retData[rx_cnt++] = getCanData(data, 7); //AddToCanTrace("received data: " + retData[0].ToString("X2")); } /*string line = address.ToString("X8") + " "; foreach (byte b in retData) { line += b.ToString("X2") + " "; } AddToCanTrace(line);*/ success = true; return retData; }
/// <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; } }
private bool StartSession20() { CANMessage msg = new CANMessage(0x7E0, 0, 2); ulong cmd = 0x0000000000002001; // 0x02 0x10 0x02 msg.setData(cmd); m_canListener.setupWaitMessage(0x7E8); if (!canUsbDevice.sendMessage(msg)) { CastInfoEvent("Couldn't send message", ActivityType.ConvertingFile); return false; } CANMessage response = new CANMessage(); response = new CANMessage(); response = m_canListener.waitMessage(timeoutP2ct); ulong data = response.getData(); if (getCanData(data, 0) != 0x01 || getCanData(data, 1) != 0x60) { return false; } return true; }
private bool StartBootloader011() { CANMessage msg = new CANMessage(0x11, 0, 7); ulong cmd = 0x0060241000803606; msg.setData(cmd); m_canListener.setupWaitMessage(0x311); if (!canUsbDevice.sendMessage(msg)) { CastInfoEvent("Couldn't send message", ActivityType.ConvertingFile); return false; } CANMessage response = new CANMessage(); response = new CANMessage(); response = m_canListener.waitMessage(timeoutP2ct); ulong data = response.getData(); if (getCanData(data, 0) != 0x01 || getCanData(data, 1) != 0x76) { return false; } return true; }
private bool SendTransferDataME96(int length, int address, uint waitforResponseID, byte firstByteToSend ) { CANMessage msg = new CANMessage(0x7E0, 0, 8); // <GS-24052011> test for ELM327, set length to 16 (0x10) ulong cmd = 0x0000000000360010; // 0x36 = transferData ulong addressHigh = (uint)address & 0x0000000000FF0000; addressHigh /= 0x10000; ulong addressMiddle = (uint)address & 0x000000000000FF00; addressMiddle /= 0x100; ulong addressLow = (uint)address & 0x00000000000000FF; ulong len = (ulong)length + 5; // The extra 5 comes from the Service ID plus the sub-function parameter byte plus the 3 byte startingAddress. ulong payload = (ulong)firstByteToSend; cmd |= (payload * 0x100000000000000); cmd |= (addressLow * 0x1000000000000); cmd |= (addressMiddle * 0x10000000000); cmd |= (addressHigh * 0x100000000); cmd |= (len * 0x100); Console.WriteLine("send: " + cmd.ToString("X16")); msg.setData(cmd); msg.elmExpectedResponses = 1; m_canListener.setupWaitMessage(waitforResponseID); if (!canUsbDevice.sendMessage(msg)) { logger.Debug("Couldn't send message"); } CANMessage response = new CANMessage(); response = new CANMessage(); response = m_canListener.waitMessage(timeoutP2ct); ulong data = response.getData(); Console.WriteLine("Received in SendTransferData: " + data.ToString("X16")); if (getCanData(data, 0) != 0x30 || getCanData(data, 1) != 0x00) { return false; } return true; }
private bool SendTransferData011(int length, int address, uint waitforResponseID) { CANMessage msg = new CANMessage(0x11, 0, 8); // <GS-24052011> test for ELM327, set length to 16 (0x10) ulong cmd = 0x0000000000360010; // 0x36 = transferData ulong addressHigh = (uint)address & 0x0000000000FF0000; addressHigh /= 0x10000; ulong addressMiddle = (uint)address & 0x000000000000FF00; addressMiddle /= 0x100; ulong addressLow = (uint)address & 0x00000000000000FF; ulong len = (ulong)length; cmd |= (addressLow * 0x100000000000000); cmd |= (addressMiddle * 0x1000000000000); cmd |= (addressHigh * 0x10000000000); cmd |= (len * 0x100); //Console.WriteLine("send: " + cmd.ToString("X16")); msg.elmExpectedResponses = 1; msg.setData(cmd); m_canListener.setupWaitMessage(waitforResponseID); if (!canUsbDevice.sendMessage(msg)) { logger.Debug("Couldn't send message"); } CANMessage response = new CANMessage(); response = new CANMessage(); response = m_canListener.waitMessage(timeoutP2ct); ulong data = response.getData(); //Console.WriteLine("Received in SendTransferData: " + data.ToString("X16")); if (getCanData(data, 0) != 0x30 || getCanData(data, 1) != 0x00) { return false; } return true; }
private bool SendSecretCodetoCIM() { //0044585349603B06 CANMessage msg = new CANMessage(0x245, 0, 8); ulong cmd = 0x0044585349603B06; msg.setData(cmd); m_canListener.setupWaitMessage(0x645); if (!canUsbDevice.sendMessage(msg)) { CastInfoEvent("Couldn't send message", ActivityType.ConvertingFile); return false; } CANMessage ECMresponse = new CANMessage(); ECMresponse = m_canListener.waitMessage(timeoutP2ct); ulong rxdata = ECMresponse.getData(); if (getCanData(rxdata, 1) == 0x7B && getCanData(rxdata, 2) == 0x60) { return true; } return false; }
private bool SendSecretCode2() { //44585349006EAE07 CANMessage msg = new CANMessage(0x7E0, 0, 8); ulong cmd = 0x44585349006EAE07; msg.setData(cmd); m_canListener.setupWaitMessage(0x7E8); if (!canUsbDevice.sendMessage(msg)) { CastInfoEvent("Couldn't send message", ActivityType.ConvertingFile); return false; } CANMessage ECMresponse = new CANMessage(); ECMresponse = m_canListener.waitMessage(timeoutP2ct); ulong rxdata = ECMresponse.getData(); if (getCanData(rxdata, 1) == 0xEE && getCanData(rxdata, 2) == 0x6E) { return true; } 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 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; } } } } } }
//------------------------------------------------------------------------- /** * 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())); }
private bool SendrequestDownloadME96(bool recoveryMode) { CANMessage msg = new CANMessage(0x7E0, 0, 7); //05 34 00 01 E0 00 00 00 ulong cmd = 0x000000E001003405; msg.setData(cmd); m_canListener.setupWaitMessage(0x7E8); if (!canUsbDevice.sendMessage(msg)) { CastInfoEvent("Couldn't send message", ActivityType.ConvertingFile); return false; } bool eraseDone = false; int eraseCount = 0; int waitCount = 0; while (!eraseDone) { m_canListener.setupWaitMessage(0x7E8); // TEST ELM327 31082011 CANMessage response = new CANMessage(); response = m_canListener.waitMessage(500); // 1 seconds! ulong data = response.getData(); if (data == 0) { m_canListener.setupWaitMessage(0x311); // TEST ELM327 31082011 response = new CANMessage(); response = m_canListener.waitMessage(500); // 1 seconds! data = response.getData(); } // response will be 03 7F 34 78 00 00 00 00 a couple of times while erasing if (getCanData(data, 0) == 0x03 && getCanData(data, 1) == 0x7F && getCanData(data, 2) == 0x34 && getCanData(data, 3) == 0x78) { if (recoveryMode) BroadcastKeepAlive(); else SendKeepAlive(); eraseCount++; string info = "Erasing FLASH"; for (int i = 0; i < eraseCount; i++) info += "."; CastInfoEvent(info, ActivityType.ErasingFlash); } else if (getCanData(data, 0) == 0x01 && getCanData(data, 1) == 0x74) { if (recoveryMode) BroadcastKeepAlive(); else SendKeepAlive(); eraseDone = true; return true; } else if (getCanData(data, 0) == 0x03 && getCanData(data, 1) == 0x7F && getCanData(data, 2) == 0x34 && getCanData(data, 3) == 0x11) { CastInfoEvent("Erase cannot be performed", ActivityType.ErasingFlash); return false; } else { Console.WriteLine("Rx: " + data.ToString("X16")); if (canUsbDevice is CANELM327Device) { if (recoveryMode) BroadcastKeepAlive(); else SendKeepAlive(); } } waitCount++; if (waitCount > 35) { if (canUsbDevice is CANELM327Device) { CastInfoEvent("Erase completed", ActivityType.ErasingFlash); // ELM327 seem to be unable to wait long enough for this response // Instead we assume its finnished ok after 35 seconds return true; } else { CastInfoEvent("Erase timed out after 35 seconds", ActivityType.ErasingFlash); return false; } } Thread.Sleep(m_sleepTime); } return true; }
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(); }
/// <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 override RequestResult sendRequest(KWPRequest a_request, out KWPReply r_reply) { uint row; uint all_rows = row = nrOfRowsToSend(a_request.getData()); m_kwpCanListener.setupWaitMessage(0x258); // Send one or several request messages. for (; row > 0; row--) { CANMessage msg = new CANMessage(0x240, 0, 8); msg.elmExpectedResponses = a_request.ElmExpectedResponses; msg.setData(createCanMessage(a_request.getData(), row - 1)); if ((msg.getData() & 0xFFFFUL) == 0xA141UL) msg.elmExpectedResponses = 0; if (all_rows == 22) { msg.elmExpectedResponses = row == 1 ? 1 : 0; // on last message (expect 1 reply) } if (!m_canDevice.sendMessage(msg)) { r_reply = new KWPReply(); return RequestResult.ErrorSending; } } var response = m_kwpCanListener.waitMessage(getTimeout()); // Receive one or several replys and send an ack for each reply. if (response.getID() == 0x258) { uint nrOfRows = (uint)(response.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, response.getData(), row); sendAck(nrOfRows - 1); nrOfRows--; m_kwpCanListener.setupWaitMessage(0x258); while (nrOfRows > 0) { response = m_kwpCanListener.waitMessage(getTimeout()); if (response.getID() == 0x258) { row++; reply = collectReply(reply, response.getData(), row); sendAck(nrOfRows - 1); nrOfRows--; } else { logger.Debug("1response.getID == " + response.getID()); r_reply = new KWPReply(); return RequestResult.Timeout; } } r_reply = new KWPReply(reply, a_request.getNrOfPID()); return RequestResult.NoError; } else { logger.Debug("2response.getID == " + response.getID()); 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()); }
/// <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); } } }
//--------------------------------------------------------------------------------------------- /** 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; } }
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(); }*/ }
/// <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; } }
private bool MarryCIMAndECU() { //0000000000633B02 CANMessage msg = new CANMessage(0x245, 0, 8); ulong cmd = 0x0000000000633B02; msg.setData(cmd); m_canListener.setupWaitMessage(0x645); if (!canUsbDevice.sendMessage(msg)) { CastInfoEvent("Couldn't send message", ActivityType.ConvertingFile); return false; } int waitMsgCount = 0; while (waitMsgCount < 10) { CANMessage ECMresponse = new CANMessage(); ECMresponse = m_canListener.waitMessage(timeoutP2ct); ulong rxdata = ECMresponse.getData(); // response might be 00000000783B7F03 for some time // final result should be 0000000000637B02 if (getCanData(rxdata, 1) == 0x7B && getCanData(rxdata, 2) == 0x63) { return true; } else if (getCanData(rxdata, 1) == 0x7F && getCanData(rxdata, 2) == 0x3B && getCanData(rxdata, 3) == 0x78) { CastInfoEvent("Waiting for marry process to complete between CIM and car", ActivityType.ConvertingFile); } waitMsgCount++; } 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); } } }
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 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); } } }
private bool SendRestoreT8() { CANMessage msg = new CANMessage(0x7E0, 0, 3); // 02 1A 79 00 00 00 00 00 ulong cmd = 0x0000000000791A02; msg.setData(cmd); m_canListener.setupWaitMessage(0x7E8); if (!canUsbDevice.sendMessage(msg)) { CastInfoEvent("Couldn't send message", ActivityType.ConvertingFile); // Do not return here want to wait for the response } CANMessage response = new CANMessage(); response = new CANMessage(); response = m_canListener.waitMessage(200); ulong data = response.getData(); // 7E8 03 5A 79 01 00 00 00 00 if (getCanData(data, 0) == 0x03 && getCanData(data, 1) == 0x5A && getCanData(data, 2) == 0x79 && getCanData(data, 3) == 0x01) { return true; } 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) { 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; } }
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> /// 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); }
private int GetProgrammingStateNormal() { Console.WriteLine("Get programming state"); CANMessage msg = new CANMessage(0x7E0, 0, 2); ulong cmd = 0x000000000000A201; // 0x02 0x10 0x02 msg.setData(cmd); m_canListener.setupWaitMessage(0x7E8); if (!canUsbDevice.sendMessage(msg)) { CastInfoEvent("Couldn't send message", ActivityType.ConvertingFile); return 0; } CANMessage response = new CANMessage(); response = new CANMessage(); response = m_canListener.waitMessage(timeoutP2ct); ulong data = response.getData(); Console.WriteLine("Get programming state response: " + data.ToString("X16")); //\__ 00 00 03 11 02 e2 01 00 00 00 00 00 Magic reply, T8 replies with 0311 and programming state 01(recovery state?) if (getCanData(data, 1) != 0xE2 || getCanData(data, 0) != 0x02) { return 0; } return Convert.ToInt32(getCanData(data, 2)); }