Esempio n. 1
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)
        {
            if (m_endThread)
            {
                return(false);
            }
            byte[] msg = a_message.getHeaderAndData();

            PassThruMsg txMsg = new PassThruMsg();

            txMsg.ProtocolID = ProtocolID.CAN;
            txMsg.TxFlags    = TxFlag.NONE;
            txMsg.SetBytes(msg);

            int       numMsgs = 1;
            const int timeout = 0;

            m_status = passThru.PassThruWriteMsgs(m_channelId, txMsg.ToIntPtr(), ref numMsgs, timeout);

            if (J2534Err.STATUS_NOERROR != m_status)
            {
                logger.Debug(String.Format("tx failed with status {0} {1}", m_status, BitConverter.ToString(msg)));
                return(false);
            }
            return(true);
        }
Esempio n. 2
0
        public override void Write(byte[] buffer, int offset, int count)
        {
            if (this.channel == null)
            {
                throw new InvalidOperationException("PassThruStream.OpenSsmStream() must succeed before calling PassThruStream.Read()");
            }

            int written = 0;

            while (written < count)
            {
                PassThruMsg message = new PassThruMsg();
                message.ProtocolID = PassThruProtocol.Iso9141;

                int length = Math.Min(count, message.Data.Length);
                for (int i = 0; i < length; i++)
                {
                    message.Data[i] = buffer[offset + i];
                }
                message.DataSize = (uint)length;

                this.channel.WriteMessage(message, TimeSpan.FromSeconds(0.5));
                written += length;
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Set filter
        /// </summary>
        private Response <J2534Err> SetFilter(UInt32 Mask, UInt32 Pattern, UInt32 FlowControl, TxFlag txflag, FilterType Filtertype)
        {
            PassThruMsg maskMsg;
            PassThruMsg patternMsg;

            IntPtr MaskPtr;
            IntPtr PatternPtr;
            IntPtr FlowPtr;

            maskMsg    = new PassThruMsg(Protocol, txflag, new Byte[] { (byte)(0xFF & (Mask >> 16)), (byte)(0xFF & (Mask >> 8)), (byte)(0xFF & Mask) });
            patternMsg = new PassThruMsg(Protocol, txflag, new Byte[] { (byte)(0xFF & (Pattern >> 16)), (byte)(0xFF & (Pattern >> 8)), (byte)(0xFF & Pattern) });
            MaskPtr    = maskMsg.ToIntPtr();
            PatternPtr = patternMsg.ToIntPtr();
            FlowPtr    = IntPtr.Zero;

            int tempfilter = 0;

            OBDError = J2534Port.Functions.PassThruStartMsgFilter((int)ChannelID, Filtertype, MaskPtr, PatternPtr, FlowPtr, ref tempfilter);

            Marshal.FreeHGlobal(MaskPtr);
            Marshal.FreeHGlobal(PatternPtr);
            Marshal.FreeHGlobal(FlowPtr);
            if (OBDError != J2534Err.STATUS_NOERROR)
            {
                return(Response.Create(ResponseStatus.Error, OBDError));
            }
            Filters.Add((ulong)tempfilter);
            return(Response.Create(ResponseStatus.Success, OBDError));
        }
Esempio n. 4
0
        public void ConnectISO15765()
        {
            Connect();

            byte[] value;
            J2534Status = J2534Interface.PassThruConnect(DeviceId, ProtocolID.ISO15765, ConnectFlag.NONE, BaudRate.ISO15765, ref ChannelId);
            if (J2534Err.STATUS_NOERROR != J2534Status)
            {
                throw new J2534Exception(J2534Status);
            }

            //List<SConfig> configBits = new List<SConfig>();
            //SConfig conf = new SConfig();
            //conf.Parameter = ConfigParameter.LOOPBACK;
            //conf.Value = 0;
            //SConfig conf1 = new SConfig();
            //conf1.Parameter = ConfigParameter.DATA_RATE;
            //conf1.Value = 0;

            //configBits.Add(conf);
            //configBits.Add(conf1);
            //m_status = m_j2534Interface.GetConfig(m_channelId, ref configBits);


            int filterId = 0;

            byte i;

            for (i = 0; i < 1; i++)
            {
                PassThruMsg maskMsg        = new PassThruMsg(ProtocolID.ISO15765, TxFlag.ISO15765_FRAME_PAD, new byte[] { 0xff, 0xff, 0xff, 0xff });
                PassThruMsg patternMsg     = new PassThruMsg(ProtocolID.ISO15765, TxFlag.ISO15765_FRAME_PAD, new byte[] { 0x00, 0x00, 0x07, (byte)(0xE8 + i) });
                PassThruMsg flowControlMsg = new PassThruMsg(ProtocolID.ISO15765, TxFlag.ISO15765_FRAME_PAD, new byte[] { 0x00, 0x00, 0x07, (byte)(0xE0 + i) });

                J2534Status = J2534Interface.PassThruStartMsgFilter(
                    ChannelId,
                    FilterType.FLOW_CONTROL_FILTER,
                    maskMsg.ToIntPtr(),
                    patternMsg.ToIntPtr(),
                    flowControlMsg.ToIntPtr(),
                    ref filterId);

                if (J2534Err.STATUS_NOERROR != J2534Status)
                {
                    J2534Interface.PassThruDisconnect(ChannelId);
                    throw new J2534Exception(J2534Status);
                }
            }

            //Check we can read some PIDs back
            ReadObdPid(OBDcmd.Mode.REQUEST_CURRENT_DATA, out value);
            if (value.Length <= 0)
            {
                //m_status = j2534Interface.PassThruDisconnect(channelId);
                //throw new OBDException(OBDcmd.Response.NEGATIVE_RESPONSE);
            }

            ProtocolId = ProtocolID.ISO15765;
        }
Esempio n. 5
0
        public void Transmit_Message(string DID_REAL, string MessageToSend)
        {
            int DID = Convert.ToInt32(DID_REAL.Trim(), 16);

            string[] dataStr = MessageToSend.Trim().Split(' ');
            int[]    byteStr = new int[dataStr.Length + 4];
            byteStr[0] = 0;
            byteStr[1] = 0;
            byteStr[2] = (byte)((int)DID / 256);
            byteStr[3] = (byte)((int)DID % 256);

            strDatebyte = "";
            for (int i = 0; i < dataStr.Length; i++)
            {
                byteStr[i + 4] = Convert.ToInt32(dataStr[i], 16);
            }

            PassThruMsg TxMsg = new PassThruMsg();

            TxMsg.ProtocolID = ProtocolID.ISO15765;   //SEND
            TxMsg.TxFlags    = TxFlag.ISO15765_FRAME_PAD;
            //TxMsg.ProtocolID = ProtocolID.CAN;
            //TxMsg.TxFlags = TxFlag.NONE;

            TxMsg.Data = new byte[byteStr.Length];
            for (int i = 0; i < byteStr.Length; i++)
            {
                TxMsg.Data[i] = (byte)byteStr[i];
            }
            for (int i = 0; i < (TxMsg.Data.Length - 4); i++)
            {
                strDatebyte += string.Format("{0:X2}", TxMsg.Data[i + 4]) + " ";
            }

            passThru.ClearRxBuffer(channelId);
            int numMsgs = 1;    //to be tested later

            J2534Error = passThru.WriteMsgs(channelId, ref TxMsg, ref numMsgs, 50);

            if (strDatebyte.Substring(0, 2) == "3E")
            {
                return;
            }

            Sum_Message = DTCANRxScroll.Rows.Count;

            DataRow canRow;

            canRow    = DTCANRxScroll.NewRow();
            canRow[0] = Sum_Message + 1;
            canRow[1] = "Tx";
            canRow[2] = "0x" + RequestID.Text.Trim();
            canRow[3] = TxMsg.Data.Length - 4;
            canRow[4] = strDatebyte;
            canRow[5] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");//string.Format("{0:G}", System.DateTime.Now);//结果为:2009-3-20 15:39:27
            DTCANRxScroll.Rows.Add(canRow);
            INIT_Timestamp = TxMsg.Timestamp;
            dgvCANRx.FirstDisplayedScrollingRowIndex = dgvCANRx.RowCount - 1;
        }
Esempio n. 6
0
        /// <summary>
        /// Parse the replies checking for a valid response, if we have a valid response extract the payload data
        /// </summary>
        /// <param name="rxMsgs"></param>
        /// <param name="txMode"></param>
        /// <param name="payload"></param>
        /// <returns></returns>
        UDSPacket ParseUDSResponse(PassThruMsg rxMsg, UDScmd.Mode txMode)
        {
            var       rxMsgBytes = rxMsg.GetBytes();
            UDSPacket rxPacket   = new UDSPacket();
            //Iterate the reply bytes to find the echod ECU index, response code, function response and payload data if there is any
            //If we could use some kind of HEX regex this would be a bit neater
            int stateMachine = 0;

            for (int i = 0; i < rxMsgBytes.Length; i++)
            {
                switch (stateMachine)
                {
                case 0:
                    if (rxMsgBytes[i] == 0x07)
                    {
                        stateMachine = 1;
                    }
                    else if (rxMsgBytes[i] != 0)
                    {
                        return(rxPacket);
                    }
                    break;

                case 1:
                    if (rxMsgBytes[i] == 0xE8)
                    {
                        stateMachine = 2;
                    }
                    else
                    {
                        return(rxPacket);
                    }
                    break;

                case 2:
                    var payload = new byte[rxMsgBytes.Length - i];

                    int payloadLength = rxMsgBytes.Length - i;
                    if (payloadLength > 0)
                    {
                        payload = new byte[payloadLength];
                        Array.Copy(rxMsgBytes, i, payload, 0, payloadLength);
                        rxPacket = new UDSPacket(payload, txMode);
                        ;
                    }
                    return(rxPacket);

                case 3:
                default:
                    return(rxPacket);
                }
            }
            return(rxPacket);
        }
Esempio n. 7
0
        public bool ResetECU()
        {
            PassThruMsg txMsg = new PassThruMsg();
            int         timeout;
            var         value = new byte[0];

            txMsg.ProtocolID = ProtocolId;
            switch (ProtocolId)
            {
            case ProtocolID.ISO15765:
                txMsg.TxFlags = TxFlag.ISO15765_FRAME_PAD;

                txMsg.SetBytes(new byte[] { 0, 0, 0x07, 0xE0, 0x11, 0x02, 0, 0 });

                timeout = 50;
                break;

            case ProtocolID.J1850PWM:
            case ProtocolID.J1850VPW:
            case ProtocolID.ISO9141:
            case ProtocolID.ISO14230:
            default:
                return(false);
            }

            J2534Interface.ClearRxBuffer(ChannelId);

            int numMsgs = 1;

            J2534Status = J2534Interface.PassThruWriteMsgs(ChannelId, txMsg.ToIntPtr(), ref numMsgs, timeout);
            if (J2534Err.STATUS_NOERROR != J2534Status)
            {
                return(false);
            }

            //Attempt to read at least 1 message as a reply
            List <PassThruMsg> messages;

            J2534Status = J2534Interface.ReadAllMessages(ChannelId, 1, _defaultTimeout, out messages, true);

            if (messages.Count <= 0)
            {
                return(false);
            }
            var response1 = messages[0].GetBytes();
            var response2 = messages[1].GetBytes();   //needs to respond with 00 00 07 e8 67 03 xx xx xx
            var code      = response2[6];

            if (response2[4] != 0x7F)
            {
                return(true);
            }
            return(false);
        }
Esempio n. 8
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            if (this.channel == null)
            {
                throw new InvalidOperationException("PassThruStream.OpenSsmStream() must succeed before calling PassThruStream.Read()");
            }

            if (this.received != null)
            {
                int bytesToCopy = Math.Min(count, this.received.Length);
                for (int i = 0; i < bytesToCopy; i++)
                {
                    buffer[i + offset] = this.received[i];
                }

                int remaining = this.received.Length - bytesToCopy;
                if (remaining > 0)
                {
                    byte[] newBuffer = new byte[remaining];
                    for (int i = 0; i < remaining; i++)
                    {
                        newBuffer[i] = this.received[bytesToCopy + i];
                    }
                    this.received = newBuffer;
                }
                else
                {
                    this.received = null;
                }
                return(bytesToCopy);
            }
            else
            {
                PassThruMsg message = new PassThruMsg();
                this.channel.ReadMessage(message, TimeSpan.FromSeconds(0.5));
                int bytesToCopy = (int)Math.Min(count, message.DataSize);
                for (int i = 0; i < bytesToCopy; i++)
                {
                    buffer[i + offset] = message.Data[i];
                }

                if (bytesToCopy < message.DataSize)
                {
                    this.received = new byte[message.DataSize - bytesToCopy];
                    for (int i = 0; i < (message.DataSize - bytesToCopy); i++)
                    {
                        this.received[i] = message.Data[bytesToCopy + i];
                    }
                }
                return(bytesToCopy);
            }
        }
Esempio n. 9
0
        public unsafe PassThruMsg[] ReadMsgs(int timeout, int numMsgs)
        {
            var msgs = new PassThruMsg[numMsgs];

            fixed(void *ptr = &msgs[0])
            {
                var status = PassThruInterface.PassThruReadMsgs(channelId, new IntPtr(ptr), ref numMsgs, timeout);

                ThrowIfError(status);
            }

            return(msgs);
        }
Esempio n. 10
0
        public void TxMsg(string msgID, string msgData, Action <string, int, string, string> Callback)
        {
            /* if not connect device, return */
            if (!IsConnectDevice)
            {
                MessageBox.Show("Please connect device!", "Error");
                return;
            }

            string strDatebyte = "";
            int    ID          = Convert.ToInt32(msgID.Trim(), 16);

            string[] dataStr = msgData.Trim().Split(' ');
            int[]    byteStr = new int[dataStr.Length + 4];
            byteStr[0] = 0;
            byteStr[1] = 0;
            byteStr[2] = (byte)((int)ID / 256);
            byteStr[3] = (byte)((int)ID % 256);

            for (int i = 0; i < dataStr.Length; i++)
            {
                byteStr[i + 4] = Convert.ToInt32("0x" + dataStr[i], 16);
            }

            PassThruMsg TxMsg = new PassThruMsg();

            TxMsg.ProtocolID = ProtocolID.ISO15765;   //SEND
            TxMsg.TxFlags    = TxFlag.ISO15765_FRAME_PAD;
            //TxMsg.ProtocolID = ProtocolID.CAN;
            //TxMsg.TxFlags = TxFlag.NONE;

            TxMsg.Data = new byte[byteStr.Length];
            for (int i = 0; i < byteStr.Length; i++)
            {
                TxMsg.Data[i] = (byte)byteStr[i];
            }
            for (int i = 0; i < (TxMsg.Data.Length - 4); i++)
            {
                strDatebyte += string.Format("{0:X2}", TxMsg.Data[i + 4]) + " ";
            }
            //passThru.ClearRxBuffer(channelId);
            int numMsgs = 1;    //to be tested later

            J2534ErrStatus = passThru.WriteMsgs(channelId, ref TxMsg, ref numMsgs, 50);

            //Console.Write("Debug"); // Debug

            /* Update UI */
            Callback(msgID, TxMsg.Data.Length - 4, strDatebyte, "Tx");
        }
Esempio n. 11
0
        /// <summary>
        /// Read an network packet from the interface, and return a Response/Message
        /// </summary>
        protected override Task Receive()
        {
            //this.Logger.AddDebugMessage("Trace: Read Network Packet");

            PassThruMsg PassMess    = new PassThruMsg();
            Message     TempMessage = new Message(null);
            int         NumMessages = 1;
            IntPtr      rxMsgs      = Marshal.AllocHGlobal((int)(Marshal.SizeOf(typeof(PassThruMsg)) * NumMessages));

            OBDError = 0; //Clear any previous faults

            Stopwatch sw = new Stopwatch();

            sw.Start();

            while (OBDError == J2534Err.STATUS_NOERROR || sw.ElapsedMilliseconds > (long)ReadTimeout)
            {
                NumMessages = 1;
                OBDError    = J2534Port.Functions.PassThruReadMsgs((int)ChannelID, rxMsgs, ref NumMessages, ReadTimeout);
                if (OBDError != J2534Err.STATUS_NOERROR)
                {
                    this.Logger.AddDebugMessage("ReadMsgs OBDError: " + OBDError);
                    return(Task.FromResult(0));
                }

                sw.Stop();
                PassMess = rxMsgs.AsMsgList(1).Last();
                if ((int)PassMess.RxStatus == (((int)RxStatus.TX_INDICATION_SUCCESS) + ((int)RxStatus.TX_MSG_TYPE)) || (PassMess.RxStatus == RxStatus.START_OF_MESSAGE))
                {
                    continue;
                }
                else
                {
                    byte[] TempBytes = PassMess.GetBytes();
                    //Perform additional filter check if required here... or show to debug
                    break;//leave while loop
                }
            }
            Marshal.FreeHGlobal(rxMsgs);

            if (OBDError != J2534Err.STATUS_NOERROR || sw.ElapsedMilliseconds > (long)ReadTimeout)
            {
                this.Logger.AddDebugMessage("ReadMsgs OBDError: " + OBDError);
                return(Task.FromResult(0));
            }

            this.Logger.AddDebugMessage("RX: " + PassMess.GetBytes().ToHex());
            this.Enqueue(new Message(PassMess.GetBytes(), PassMess.Timestamp, (ulong)OBDError));
            return(Task.FromResult(0));
        }
Esempio 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()
        {
            uint       id;
            int        numMsgs    = 1;
            const int  timeout    = 1000;
            CANMessage canMessage = new CANMessage();

            logger.Debug("readMessages started");
            while (true)
            {
                lock (m_synchObject)
                {
                    if (m_endThread)
                    {
                        logger.Debug("readMessages thread ended");
                        return;
                    }
                }
                IntPtr rxMsgs = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(PassThruMsg)));
                m_status = passThru.PassThruReadMsgs(m_channelId, rxMsgs, ref numMsgs, timeout);
                if (m_status == J2534Err.STATUS_NOERROR)
                {
                    if (numMsgs > 0)
                    {
                        PassThruMsg msg = rxMsgs.AsMsgList(numMsgs)[0];

                        byte[] all = msg.GetBytes();
                        id = (uint)(all[2] * 0x100 + all[3]);
                        uint   length = msg.DataSize - 4;
                        byte[] data   = new byte[length];
                        Array.Copy(all, 4, data, 0, length);

                        if (acceptMessageId(id))
                        {
                            canMessage.setID(id);
                            canMessage.setTimeStamp(msg.Timestamp);
                            canMessage.setCanData(data, (byte)(length));

                            receivedMessage(canMessage);
                        }
                    }
                }
                else
                {
                    logger.Debug(String.Format("PassThruReadMsgs, status:{0}", m_status));
                }
                Marshal.FreeHGlobal(rxMsgs);
            }
        }
Esempio n. 13
0
        public bool ConnectIso15765()
        {
            List <byte> value = new List <byte>();

            m_status = m_j2534Interface.Connect(m_deviceId, ProtocolID.ISO15765, ConnectFlag.NONE, BaudRate.ISO15765, ref m_channelId);
            if (J2534Err.STATUS_NOERROR != m_status)
            {
                return(false);
            }

            PassThruMsg maskMsg        = new PassThruMsg();
            PassThruMsg patternMsg     = new PassThruMsg();
            PassThruMsg flowControlMsg = new PassThruMsg();
            int         filterId       = 0;

            byte i;

            //for (i=0; i < 8; i++)
            for (i = 0; i < 1; i++)
            {
                maskMsg.ProtocolID = ProtocolID.ISO15765;
                maskMsg.TxFlags    = TxFlag.ISO15765_FRAME_PAD;
                maskMsg.Data       = new byte[] { 0xff, 0xff, 0xff, 0xff };

                patternMsg.ProtocolID = ProtocolID.ISO15765;
                patternMsg.TxFlags    = TxFlag.ISO15765_FRAME_PAD;
                patternMsg.Data       = new byte[] { 0x00, 0x00, 0x07, (byte)(0xE8 + i) };

                flowControlMsg.ProtocolID = ProtocolID.ISO15765;
                flowControlMsg.TxFlags    = TxFlag.ISO15765_FRAME_PAD;
                flowControlMsg.Data       = new byte[] { 0x00, 0x00, 0x07, (byte)(0xE0 + i) };

                m_status = m_j2534Interface.StartMsgFilter(m_channelId, FilterType.FLOW_CONTROL_FILTER, ref maskMsg, ref patternMsg, ref flowControlMsg, ref filterId);
                if (J2534Err.STATUS_NOERROR != m_status)
                {
                    m_j2534Interface.Disconnect(m_channelId);
                    return(false);
                }
            }

            if (!ReadObdPid(0x01, 0x00, ProtocolID.ISO15765, ref value))
            {
                m_j2534Interface.Disconnect(m_channelId);
                return(false);
            }
            return(true);
        }
Esempio n. 14
0
        private bool connectCAN()
        {
            J2534Error = passThru.Connect(deviceId, ProtocolID.CAN, ConnectFlag.NONE, baudRate, ref channelId);

            if (J2534Error == J2534Err.STATUS_NOERROR)
            {
                PassThruMsg maskMsg    = new PassThruMsg(ProtocolID.CAN, TxFlag.NONE, new byte[] { 0x00, 0x00, 0x00, 0x00 }); //all to receive
                PassThruMsg patternMsg = new PassThruMsg(ProtocolID.CAN, TxFlag.NONE, new byte[] { 0x00, 0x00, 0x00, 0x00 });
                passThru.StartMsgFilter(channelId, FilterType.PASS_FILTER, ref maskMsg, ref patternMsg, ref filterId);
                passThru.ClearRxBuffer(channelId);
                return(true);
            }
            else
            {
                return(false);
            }
        }
Esempio n. 15
0
        public bool ConnectIso15765(string RequestID, string ResponseID, BaudRate baudRate)
        {
            List <byte> value = new List <byte>();

            J2534ErrStatus = passThru.Connect(deviceId, ProtocolID.ISO15765, ConnectFlag.NONE, baudRate, ref channelId);
            if (J2534Err.STATUS_NOERROR != J2534ErrStatus)
            {
                return(false);
            }

            PassThruMsg maskMsg        = new PassThruMsg();
            PassThruMsg patternMsg     = new PassThruMsg();
            PassThruMsg flowControlMsg = new PassThruMsg();

            byte i;

            for (i = 0; i < 1; i++)
            {
                maskMsg.ProtocolID = ProtocolID.ISO15765;
                maskMsg.TxFlags    = TxFlag.ISO15765_FRAME_PAD;
                maskMsg.Data       = new byte[] { 0xff, 0xff, 0xff, 0xff }; //4 "FF" for stand ID,5 "FF" for extend ID

                byte ReqID_1 = (byte)Convert.ToUInt16(RequestID.Trim().ToUpper().Substring(0, 1), 16);
                byte ReqID_2 = (byte)Convert.ToUInt16(RequestID.Trim().ToUpper().Substring(1, 2), 16);

                byte RespID_1 = (byte)Convert.ToUInt16(ResponseID.Trim().ToUpper().Substring(0, 1), 16);
                byte RespID_2 = (byte)Convert.ToUInt16(ResponseID.Trim().ToUpper().Substring(1, 2), 16);

                patternMsg.ProtocolID = ProtocolID.ISO15765;
                patternMsg.TxFlags    = TxFlag.ISO15765_FRAME_PAD;
                patternMsg.Data       = new byte[] { 0x00, 0x00, RespID_1, RespID_2 };

                flowControlMsg.ProtocolID = ProtocolID.ISO15765;
                flowControlMsg.TxFlags    = TxFlag.ISO15765_FRAME_PAD;
                flowControlMsg.Data       = new byte[] { 0x00, 0x00, ReqID_1, ReqID_2 };

                J2534ErrStatus = passThru.StartMsgFilter(channelId, FilterType.FLOW_CONTROL_FILTER, ref maskMsg, ref patternMsg, ref flowControlMsg, ref filterId);
                if (J2534Err.STATUS_NOERROR != J2534ErrStatus)
                {
                    passThru.Disconnect(channelId);
                    return(false);
                }
            }
            return(true);
        }
Esempio n. 16
0
        public void SendMessage(byte[] payload, bool headerSuppled = false)
        {
            J2534Status = J2534Interface.ClearTxBuffer(ChannelId);

            var txMsg = new PassThruMsg();
            int timeout;

            if (headerSuppled)
            {
                txMsg.SetBytes(payload);
            }
            else
            {
                //Use the standard header
                //First 4 bytes are 00 00 07 E8
                byte[] txMsgBytes = new byte[4 + payload.Length];
                txMsgBytes[2] = 0x07;
                txMsgBytes[3] = 0xE0;
                Array.Copy(payload, 0, txMsgBytes, 4, payload.Length);
                txMsg.SetBytes(txMsgBytes);
            }


            txMsg.ProtocolID = ProtocolId;


            if (ProtocolId != ProtocolID.ISO15765)
            {
                throw new J2534Exception(J2534Err.ERR_NOT_SUPPORTED);
            }

            txMsg.TxFlags = TxFlag.ISO15765_FRAME_PAD;
            timeout       = 50;


            J2534Interface.ClearRxBuffer(ChannelId);

            var numMsgs = 1;

            J2534Status = J2534Interface.PassThruWriteMsgs(ChannelId, txMsg.ToIntPtr(), ref numMsgs, timeout);
            if (J2534Err.STATUS_NOERROR != J2534Status)
            {
                throw new J2534Exception(J2534Status);
            }
        }
Esempio n. 17
0
        public void TxMsg(UInt32 RequestID, byte[] msgData, Action <string, string, string, string, string> UpdateUICallback)
        {
            J2534Err    J2534ErrStatus;
            int         numMsgs = 1;
            PassThruMsg TxMsg   = new PassThruMsg();

            TxMsg.ProtocolID = ProtocolID.ISO15765;   //SEND
            TxMsg.TxFlags    = TxFlag.ISO15765_FRAME_PAD;
            //TxMsg.ProtocolID = ProtocolID.CAN;
            //TxMsg.TxFlags = TxFlag.NONE;

            TxMsg.Data = PackMsgTxData(RequestID, msgData);

            //passThru.ClearRxBuffer(channelId);
            J2534ErrStatus = passThru.WriteMsgs(channelId, ref TxMsg, ref numMsgs, 10);

            UpdateUICallback(string.Format("{0:X}", RequestID), Convert.ToString(TxMsg.Data.Length - 4), GetMsgDataString(TxMsg.Data), "Tx", DateTime.Now.ToString("HH:mm:ss:fff:ffffff"));
        }
Esempio n. 18
0
        public void SetNullFilters(int swChannelId, int dwChannelId)
        {
            // Set up a message filter to watch for response messages
            int filterId = 0;


            PassThruMsg swMask1 = new PassThruMsg(
                ProtocolID.SW_CAN,
                TxFlag.CAN_29BIT_ID,
                new byte[] { 0x00, 0x00, 0x00, 0x00 });

            PassThruMsg swMask2 = new PassThruMsg(
                ProtocolID.SW_CAN,
                TxFlag.CAN_29BIT_ID,
                new byte[] { 0x10, 0x00, 0x00, 0x00 });

            PassThruMsg swMask3 = new PassThruMsg(
                ProtocolID.SW_CAN,
                TxFlag.CAN_29BIT_ID,
                new byte[] { 0x0f, 0x00, 0x00, 0x00 });

            PassThruMsg dwMask1 = new PassThruMsg(
                ProtocolID.DW_CAN,
                TxFlag.CAN_29BIT_ID,
                new byte[] { 0x00, 0x00, 0x00, 0x00 });

            PassThruMsg dwMask2 = new PassThruMsg(
                ProtocolID.DW_CAN,
                TxFlag.CAN_29BIT_ID,
                new byte[] { 0x10, 0x00, 0x00, 0x00 });

            PassThruMsg dwMask3 = new PassThruMsg(
                ProtocolID.DW_CAN,
                TxFlag.CAN_29BIT_ID,
                new byte[] { 0x0f, 0x00, 0x00, 0x00 });

            m_j2534Interface.PassThruStartMsgFilter(swChannelId, FilterType.PASS_FILTER, swMask1.ToIntPtr(), swMask1.ToIntPtr(), IntPtr.Zero, ref filterId);
            m_j2534Interface.PassThruStartMsgFilter(swChannelId, FilterType.PASS_FILTER, swMask2.ToIntPtr(), swMask2.ToIntPtr(), IntPtr.Zero, ref filterId);
            m_j2534Interface.PassThruStartMsgFilter(swChannelId, FilterType.PASS_FILTER, swMask3.ToIntPtr(), swMask3.ToIntPtr(), IntPtr.Zero, ref filterId);

            m_j2534Interface.PassThruStartMsgFilter(dwChannelId, FilterType.PASS_FILTER, dwMask1.ToIntPtr(), dwMask1.ToIntPtr(), IntPtr.Zero, ref filterId);
            m_j2534Interface.PassThruStartMsgFilter(dwChannelId, FilterType.PASS_FILTER, dwMask2.ToIntPtr(), dwMask2.ToIntPtr(), IntPtr.Zero, ref filterId);
            m_j2534Interface.PassThruStartMsgFilter(dwChannelId, FilterType.PASS_FILTER, dwMask3.ToIntPtr(), dwMask3.ToIntPtr(), IntPtr.Zero, ref filterId);
        }
Esempio n. 19
0
        public bool ConnectIso15765()
        {
            List <byte> value = new List <byte>();

            m_status = m_j2534Interface.PassThruConnect(m_deviceId, ProtocolID.ISO15765, ConnectFlag.NONE, BaudRate.ISO15765, ref m_channelId);
            if (J2534Err.STATUS_NOERROR != m_status)
            {
                return(false);
            }

            int filterId = 0;

            byte i;

            for (i = 0; i < 1; i++)
            {
                PassThruMsg maskMsg        = new PassThruMsg(ProtocolID.ISO15765, TxFlag.ISO15765_FRAME_PAD, new byte[] { 0xff, 0xff, 0xff, 0xff });
                PassThruMsg patternMsg     = new PassThruMsg(ProtocolID.ISO15765, TxFlag.ISO15765_FRAME_PAD, new byte[] { 0x00, 0x00, 0x07, (byte)(0xE8 + i) });
                PassThruMsg flowControlMsg = new PassThruMsg(ProtocolID.ISO15765, TxFlag.ISO15765_FRAME_PAD, new byte[] { 0x00, 0x00, 0x07, (byte)(0xE0 + i) });

                m_status = m_j2534Interface.PassThruStartMsgFilter(
                    m_channelId,
                    FilterType.FLOW_CONTROL_FILTER,
                    maskMsg.ToIntPtr(),
                    patternMsg.ToIntPtr(),
                    flowControlMsg.ToIntPtr(),
                    ref filterId);

                if (J2534Err.STATUS_NOERROR != m_status)
                {
                    m_j2534Interface.PassThruDisconnect(m_channelId);
                    return(false);
                }
            }

            if (!ReadObdPid(0x01, 0x00, ProtocolID.ISO15765, ref value))
            {
                m_j2534Interface.PassThruDisconnect(m_channelId);
                return(false);
            }
            return(true);
        }
Esempio n. 20
0
        /// <summary>
        /// Convert a Message to an J2534 formatted transmit, and send to the interface
        /// </summary>
        private Response <J2534Err> SendNetworkMessage(Message message, TxFlag Flags)
        {
            //this.Logger.AddDebugMessage("Trace: Send Network Packet");

            PassThruMsg TempMsg = new PassThruMsg();

            TempMsg.ProtocolID = Protocol;
            TempMsg.TxFlags    = Flags;
            TempMsg.SetBytes(message.GetBytes());

            int NumMsgs = 1;

            IntPtr MsgPtr = TempMsg.ToIntPtr();

            OBDError = J2534Port.Functions.PassThruWriteMsgs((int)ChannelID, MsgPtr, ref NumMsgs, WriteTimeout);
            Marshal.FreeHGlobal(MsgPtr);
            if (OBDError != J2534Err.STATUS_NOERROR)
            {
                //Debug messages here...check why failed..
                return(Response.Create(ResponseStatus.Error, OBDError));
            }
            return(Response.Create(ResponseStatus.Success, OBDError));
        }
Esempio n. 21
0
        public bool SendDwMessage(String id, bool extended, bool highVoltage, String data)
        {
            PassThruMsg txMsg   = new PassThruMsg();
            int         timeout = 200;
            String      rawMessage;

            if (extended)
            {
                rawMessage = CreateExtendedMessage(id, data);
            }
            else
            {
                rawMessage = CreateStandardMessage(id, data);
            }

            txMsg.ProtocolID = ProtocolID.DW_CAN;
            txMsg.SetBytes(StringToHex(rawMessage));
            if (extended)
            {
                txMsg.TxFlags |= TxFlag.CAN_29BIT_ID;
            }
            if (highVoltage)
            {
                txMsg.TxFlags |= TxFlag.SW_CAN_HV_TX;
            }

            int numMsgs = 1;

            m_status = m_j2534Interface.PassThruWriteMsgs(m_dwChannelId, txMsg.ToIntPtr(), ref numMsgs, timeout);
            if (J2534Err.STATUS_NOERROR != m_status)
            {
                return(false);
            }

            return(true);
        }
Esempio n. 22
0
        public void SendReceiveHighLevelApi()
        {
            try
            {
                System.IO.File.Copy(@"..\..\..\J2534Mock\Debug\J2534Mock.dll", "J2534Mock.dll");
            }
            catch (System.IO.IOException ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            try
            {
                System.IO.File.Copy(@"..\..\..\J2534Mock\Debug\J2534Mock.pdb", "J2534Mock.pdb");
            }
            catch (System.IO.IOException ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            Debug.WriteLine("Opening device");
            //PassThruDevice device = PassThruDevice.GetInstance(new OpenPort20());
            PassThruDevice device = PassThruDevice.GetInstance(new MockPassThru());

            device.Open();

            Debug.WriteLine("Opening channel");
            PassThruChannel channel = device.OpenChannel(
                PassThruProtocol.Iso9141,
                PassThruConnectFlags.Iso9141NoChecksum,
                PassThruBaudRate.Rate4800);

            Debug.WriteLine("Initializing channel for SSM");
            channel.InitializeSsm();

            byte[]      messageBytes   = new byte[] { 0x80, 0x10, 0xF0, 0x01, 0xBF, 0x40 };
            PassThruMsg initRequestMsg = new PassThruMsg(PassThruProtocol.Iso9141);

            initRequestMsg.ProtocolID = PassThruProtocol.Iso9141;
            initRequestMsg.DataSize   = (UInt32)messageBytes.Length;
            for (int i = 0; i < messageBytes.Length; i++)
            {
                initRequestMsg.Data[i] = messageBytes[i];
            }

            PassThruMsg[] initRequestMsgs = new PassThruMsg[] { initRequestMsg };
            UInt32        numMsgs         = 1;

            Debug.WriteLine("Sending SSM init message");
            channel.WriteMessages(initRequestMsgs, ref numMsgs, TimeSpan.FromMilliseconds(1000));

            PassThruMsg received = new PassThruMsg(PassThruProtocol.Iso9141);

            Debug.WriteLine("Waiting for SSM init response");
            channel.ReadMessage(
                received,
                TimeSpan.FromMilliseconds(1000));

            Debug.WriteLine("Closing channel");
            channel.Close();

            Debug.WriteLine("Closing device");
            device.Close();
        }
Esempio n. 23
0
        private bool ReadObdPid(byte mode, byte pid, ProtocolID protocolId, ref List <byte> value)
        {
            List <PassThruMsg> rxMsgs = new List <PassThruMsg>();
            PassThruMsg        txMsg  = new PassThruMsg();
            int timeout;

            txMsg.ProtocolID = protocolId;
            switch (protocolId)
            {
            case ProtocolID.ISO15765:
                txMsg.TxFlags = TxFlag.ISO15765_FRAME_PAD;
                if (mode == 0x03 || mode == 0x04)
                {
                    txMsg.Data = new byte[] { 0x00, 0x00, 0x07, 0xdf, mode };
                }
                else
                {
                    txMsg.Data = new byte[] { 0x00, 0x00, 0x07, 0xdf, mode, pid };
                }
                timeout = 50;
                break;

            case ProtocolID.J1850PWM:
            case ProtocolID.J1850VPW:
            case ProtocolID.ISO9141:
            case ProtocolID.ISO14230:
                byte protocolByte = (byte)((protocolId == ProtocolID.J1850PWM) ? 0x61 : 0x68);
                txMsg.TxFlags = TxFlag.NONE;
                txMsg.Data    = new byte[] { protocolByte, 0x6A, 0xF1, mode, pid };
                timeout       = 100;
                break;

            default:
                return(false);
            }

            m_j2534Interface.ClearRxBuffer(m_channelId);

            int numMsgs = 1;

            m_status = m_j2534Interface.WriteMsgs(m_channelId, ref txMsg, ref numMsgs, timeout);
            if (J2534Err.STATUS_NOERROR != m_status)
            {
                return(false);
            }

            numMsgs = 1;
            while (J2534Err.STATUS_NOERROR == m_status)
            {
                m_status = m_j2534Interface.ReadMsgs(m_channelId, ref rxMsgs, ref numMsgs, timeout * 4);
            }

            if (J2534Err.ERR_BUFFER_EMPTY == m_status || J2534Err.ERR_TIMEOUT == m_status)
            {
                if (rxMsgs.Count > 1)
                {
                    // Select the last value
                    value = rxMsgs[rxMsgs.Count - 1].Data.ToList();
                    value.RemoveRange(0, txMsg.Data.Length);
                    return(true);
                }
                return(false);
            }
            return(false);
        }
Esempio n. 24
0
        /*
         *
         *  Example 2:
         *      Use the J2534 protocol to send and receive a message (w/o error checking)
         *
         */
        private void SendReceiveNoErrorChecking(object sender, EventArgs e)
        {
            J2534Extended passThru = new J2534Extended();

            // Find all of the installed J2534 passthru devices
            List <J2534Device> availableJ2534Devices = J2534Detect.ListDevices();

            J2534Device j2534Device;
            var         sd = new SelectDevice();

            if (sd.ShowDialog() == DialogResult.OK)
            {
                j2534Device = sd.Device;
            }
            else
            {
                return;
            }

            // We will always choose the first J2534 device in the list, if there are multiple devices
            //   installed, you should do something more intelligent.
            passThru.LoadLibrary(j2534Device);

            // Attempt to open a communication link with the pass thru device
            int deviceId = 0;

            passThru.PassThruOpen(IntPtr.Zero, ref deviceId);

            // Open a new channel configured for ISO15765 (CAN)
            int channelId = 0;

            passThru.PassThruConnect(deviceId, ProtocolID.ISO15765, ConnectFlag.NONE, BaudRate.ISO15765, ref channelId);

            // Set up a message filter to watch for response messages
            int         filterId = 0;
            PassThruMsg maskMsg  = new PassThruMsg(
                ProtocolID.ISO15765,
                TxFlag.ISO15765_FRAME_PAD,
                new byte[] { 0xff, 0xff, 0xff, 0xff });
            PassThruMsg patternMsg = new PassThruMsg(
                ProtocolID.ISO15765,
                TxFlag.ISO15765_FRAME_PAD,
                new byte[] { 0x00, 0x00, 0x07, 0xE8 });
            PassThruMsg flowControlMsg = new PassThruMsg(
                ProtocolID.ISO15765,
                TxFlag.ISO15765_FRAME_PAD,
                new byte[] { 0x00, 0x00, 0x07, 0xE0 });

            IntPtr maskMsgPtr        = maskMsg.ToIntPtr();
            IntPtr patternMsgPtr     = patternMsg.ToIntPtr();
            IntPtr flowControlMsgPtr = flowControlMsg.ToIntPtr();

            passThru.PassThruStartMsgFilter(channelId, FilterType.FLOW_CONTROL_FILTER, maskMsgPtr, patternMsgPtr, flowControlMsgPtr, ref filterId);

            // Clear out the response buffer so we know we're getting the freshest possible data
            passThru.ClearRxBuffer(channelId);

            // Finally we can send the message!
            PassThruMsg txMsg = new PassThruMsg(
                ProtocolID.ISO15765,
                TxFlag.ISO15765_FRAME_PAD,
                new byte[] { 0x00, 0x00, 0x07, 0xdf, 0x01, 0x00 });
            var txMsgPtr = txMsg.ToIntPtr();
            int numMsgs  = 1;

            passThru.PassThruWriteMsgs(channelId, txMsgPtr, ref numMsgs, 50);

            // Read messages in a loop until we either timeout or we receive data
            numMsgs = 1;
            IntPtr   rxMsgs = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(PassThruMsg)) * numMsgs);
            J2534Err status = J2534Err.STATUS_NOERROR;

            while (J2534Err.STATUS_NOERROR == status)
            {
                status = passThru.PassThruReadMsgs(channelId, rxMsgs, ref numMsgs, 200);
            }

            // If we received data, we want to extract the data of interest.  I'm removing the reflection of the transmitted message.
            if ((J2534Err.ERR_BUFFER_EMPTY == status || J2534Err.ERR_TIMEOUT == status) && numMsgs > 0)
            {
                foreach (PassThruMsg msg in rxMsgs.AsList <PassThruMsg>(numMsgs))
                {
                    //
                    //
                    // Now do something with the data!
                    //
                    //
                }
            }


            // Disconnect this channel
            passThru.PassThruDisconnect(channelId);

            // When we are done with the device, we can free the library.
            passThru.FreeLibrary();
        }
Esempio n. 25
0
        /*
         *
         *  Example 2:
         *      Use the J2534 protocol to send and receive a message (w/o error checking)
         *
         */
        private void SendReceiveNoErrorChecking(object sender, EventArgs e)
        {
            J2534 passThru = new J2534();

            // Find all of the installed J2534 passthru devices
            List <J2534Device> availableJ2534Devices = J2534Detect.ListDevices();

            // We will always choose the first J2534 device in the list, if there are multiple devices
            //   installed, you should do something more intelligent.
            passThru.LoadLibrary(availableJ2534Devices[0]);

            // Attempt to open a communication link with the pass thru device
            int deviceId = 0;

            passThru.Open(ref deviceId);

            // Open a new channel configured for ISO15765 (CAN)
            int channelId = 0;

            passThru.Connect(deviceId, ProtocolID.ISO15765, ConnectFlag.NONE, BaudRate.ISO15765, ref channelId);

            // Set up a message filter to watch for response messages
            int         filterId = 0;
            PassThruMsg maskMsg  = new PassThruMsg(
                ProtocolID.ISO15765,
                TxFlag.ISO15765_FRAME_PAD,
                new byte[] { 0xff, 0xff, 0xff, 0xff });
            PassThruMsg patternMsg = new PassThruMsg(
                ProtocolID.ISO15765,
                TxFlag.ISO15765_FRAME_PAD,
                new byte[] { 0x00, 0x00, 0x07, 0xE8 });
            PassThruMsg flowControlMsg = new PassThruMsg(
                ProtocolID.ISO15765,
                TxFlag.ISO15765_FRAME_PAD,
                new byte[] { 0x00, 0x00, 0x07, 0xE0 });

            passThru.StartMsgFilter(channelId, FilterType.FLOW_CONTROL_FILTER, ref maskMsg, ref patternMsg, ref flowControlMsg, ref filterId);

            // Clear out the response buffer so we know we're getting the freshest possible data
            passThru.ClearRxBuffer(channelId);

            // Finally we can send the message!
            PassThruMsg txMsg = new PassThruMsg(
                ProtocolID.ISO15765,
                TxFlag.ISO15765_FRAME_PAD,
                new byte[] { 0x00, 0x00, 0x07, 0xdf, 0x01, 0x00 });
            int numMsgs = 1;

            passThru.WriteMsgs(channelId, ref txMsg, ref numMsgs, 50);

            // Read messages in a loop until we either timeout or we receive data
            List <PassThruMsg> rxMsgs = new List <PassThruMsg>();
            J2534Err           status = J2534Err.STATUS_NOERROR;

            numMsgs = 1;
            while (J2534Err.STATUS_NOERROR == status)
            {
                status = passThru.ReadMsgs(channelId, ref rxMsgs, ref numMsgs, 200);
            }

            // If we received data, we want to extract the data of interest.  I'm removing the reflection of the transmitted message.
            List <byte> responseData;

            if ((J2534Err.ERR_BUFFER_EMPTY == status || J2534Err.ERR_TIMEOUT == status) && rxMsgs.Count > 1)
            {
                responseData = rxMsgs[rxMsgs.Count - 1].Data.ToList();
                responseData.RemoveRange(0, txMsg.Data.Length);
            }

            //
            //
            // Now do something with the data!
            //
            //

            // Disconnect this channel
            passThru.Disconnect(channelId);

            // When we are done with the device, we can free the library.
            passThru.FreeLibrary();
        }
Esempio n. 26
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                PrintUsage();
                return;
            }

            string    mode           = args[0];
            IPassThru implementation = null;

            if (mode.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
            {
                implementation = DynamicPassThru.GetInstance(mode);
            }
            else if (mode == "mock")
            {
                //Copy("J2534Mock.dll");
                //Copy("J2534Mock.pdb");
                implementation = new MockPassThru();
            }
            else if (mode == "op")
            {
                implementation = new OpenPort20PassThru();
            }
            else
            {
                PrintUsage();
                return;
            }

            Console.WriteLine("Opening device");
            PassThruDevice device = PassThruDevice.GetInstance(implementation);

            device.Open();

            Console.WriteLine("Opening channel");
            PassThruChannel channel = device.OpenChannel(
                PassThruProtocol.Iso9141,
                PassThruConnectFlags.Iso9141NoChecksum,
                PassThruBaudRate.Rate4800);

            Console.WriteLine("Initializing channel for SSM");
            channel.InitializeSsm();

            byte[]      messageBytes   = new byte[] { 0x80, 0x10, 0xF0, 0x01, 0xBF, 0x40 };
            PassThruMsg initRequestMsg = new PassThruMsg(PassThruProtocol.Iso9141);

            initRequestMsg.ProtocolID = PassThruProtocol.Iso9141;
            initRequestMsg.DataSize   = (UInt32)messageBytes.Length;
            for (int i = 0; i < messageBytes.Length; i++)
            {
                initRequestMsg.Data[i] = messageBytes[i];
            }

            //PassThruMsg[] initRequestMsgs = new PassThruMsg[] { initRequestMsg };
            //UInt32 numMsgs = 1;

            Console.WriteLine("Sending SSM init message");
            channel.WriteMessage(initRequestMsg, TimeSpan.FromMilliseconds(1000));

            PassThruMsg received = new PassThruMsg(PassThruProtocol.Iso9141);

            //PassThruMsg[] receivedMessages = new PassThruMsg[] { received };
            //UInt32 numMsgs = 1;

            Console.WriteLine("Waiting for SSM init response");
            bool success = channel.ReadMessage(
                received,
                TimeSpan.FromMilliseconds(1000));

            Console.WriteLine("ReadMessage success: " + success);

            Console.WriteLine("SSM init response:");
            string response = BitConverter.ToString(received.Data, 0, (int)received.DataSize);

            Console.WriteLine(response);

            Console.WriteLine("Closing channel");
            channel.Close();

            Console.WriteLine("Closing device");
            device.Close();
            implementation.Dispose();
        }
Esempio n. 27
0
        public void SendReceiveLowLevelApi()
        {
            UInt32 deviceID;
            Int32  status = NativeOpenPort20.PassThruOpen(null, out deviceID);

            TraceStatus("PassThruOpen", status);
            Trace.WriteLine("Device ID: " + deviceID);

            UInt32 channelID;

            status = NativeOpenPort20.PassThruConnect(
                deviceID,
                (UInt32)PassThruProtocol.Iso9141,
                (UInt32)PassThruConnectFlags.Iso9141NoChecksum,
                (UInt32)PassThruBaudRate.Rate4800,
                out channelID);
            TraceStatus("PassThruConnect", status);
            Trace.WriteLine("Channel ID: " + channelID);

            SetConfiguration P1Max      = new SetConfiguration(SetConfigurationParameter.P1Max, 2);
            SetConfiguration P3Min      = new SetConfiguration(SetConfigurationParameter.P3Min, 0);
            SetConfiguration P4Min      = new SetConfiguration(SetConfigurationParameter.P4Min, 0);
            SetConfiguration Terminator = new SetConfiguration(SetConfigurationParameter.FinalParam, 0);

            // TODO: add loopback=1
            SetConfiguration[] setConfigurationArray = new SetConfiguration[] { P1Max, P3Min, P4Min };
            using (SetConfigurationList setConfigurationList = new SetConfigurationList(setConfigurationArray))
                //IntPtr buffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(SetConfiguration) * setConfigurationArray.Length);
                //IntPtr buffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(setConfigurationList));
                //{
                status = NativeOpenPort20.PassThruIoctl(
                    channelID,
                    PassThruIOControl.SetConfig,
                    ref setConfigurationArray,//setConfigurationList.Pointer,
                    IntPtr.Zero);
            //}
            //Marshal.FreeCoTaskMem(buffer);

            TraceStatus("PassThruIoCtl SetConfig", status);

            UInt32      filterID;
            PassThruMsg maskMsg = new PassThruMsg(PassThruProtocol.Iso9141);

            //maskMsg.ExtraDataIndex = 1;
            maskMsg.DataSize = 1;

            status = NativeOpenPort20.PassThruStartMsgFilter(
                channelID,
                (UInt32)PassThruFilterType.Pass,
                maskMsg,
                maskMsg,
                null,
                out filterID);
            TraceStatus("PassThruStartMsgFilter", status);
            Trace.WriteLine("Filter ID: " + filterID);

            byte[]      messageBytes   = new byte[] { 0x80, 0x10, 0xF0, 0x01, 0xBF, 0x40 };
            PassThruMsg initRequestMsg = new PassThruMsg(PassThruProtocol.Iso9141);

            initRequestMsg.ProtocolID = PassThruProtocol.Iso9141;
            initRequestMsg.DataSize   = (UInt32)messageBytes.Length;
            for (int i = 0; i < messageBytes.Length; i++)
            {
                initRequestMsg.Data[i] = messageBytes[i];
            }

            PassThruMsg[] initRequestMsgs = new PassThruMsg[] { initRequestMsg };
            UInt32        numMsgs         = 1;

            status = NativeOpenPort20.PassThruWriteMsgs(
                channelID,
                initRequestMsgs,
                ref numMsgs,
                500);
            TraceStatus("PassThruWriteMsgs", status);

            PassThruMsg received = new PassThruMsg(PassThruProtocol.Iso9141);

            PassThruMsg[] receivedMessages = new PassThruMsg[] { received };
            numMsgs = 1;
            status  = NativeOpenPort20.PassThruReadMsgs(
                channelID,
                receivedMessages,
                ref numMsgs,
                500);
            TraceStatus("PassThruReadMsgs", status);

            if (status == (UInt32)PassThruStatus.NoError)
            {
                for (int i = 0; i < received.DataSize; i++)
                {
                    Trace.Write(received.Data[i].ToString());
                    Trace.Write(' ');
                }
            }

            status = NativeOpenPort20.PassThruDisconnect(channelID);
            TraceStatus("PassThruDisconnect", status);

            status = NativeOpenPort20.PassThruClose(deviceID);
            TraceStatus("PassThruClose", status);
        }
Esempio n. 28
0
        private bool ReadObdPid(byte mode, byte pid, ProtocolID protocolId, ref List <byte> value)
        {
            PassThruMsg txMsg = new PassThruMsg();
            int         timeout;

            txMsg.ProtocolID = protocolId;
            switch (protocolId)
            {
            case ProtocolID.ISO15765:
                txMsg.TxFlags = TxFlag.ISO15765_FRAME_PAD;
                if (mode == 0x03 || mode == 0x04)
                {
                    txMsg.SetBytes(new byte[] { 0x00, 0x00, 0x07, 0xdf, mode });
                }
                else
                {
                    txMsg.SetBytes(new byte[] { 0x00, 0x00, 0x07, 0xdf, mode, pid });
                }
                timeout = 50;
                break;

            case ProtocolID.J1850PWM:
            case ProtocolID.J1850VPW:
            case ProtocolID.ISO9141:
            case ProtocolID.ISO14230:
                byte protocolByte = (byte)((protocolId == ProtocolID.J1850PWM) ? 0x61 : 0x68);
                txMsg.TxFlags = TxFlag.NONE;
                txMsg.SetBytes(new byte[] { protocolByte, 0x6A, 0xF1, mode, pid });
                timeout = 100;
                break;

            default:
                return(false);
            }

            m_j2534Interface.ClearRxBuffer(m_channelId);

            int numMsgs = 1;

            m_status = m_j2534Interface.PassThruWriteMsgs(m_channelId, txMsg.ToIntPtr(), ref numMsgs, timeout);
            if (J2534Err.STATUS_NOERROR != m_status)
            {
                return(false);
            }

            IntPtr rxMsgs = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(PassThruMsg)) * numMsgs);

            numMsgs = 1;
            while (J2534Err.STATUS_NOERROR == m_status)
            {
                m_status = m_j2534Interface.PassThruReadMsgs(m_channelId, rxMsgs, ref numMsgs, timeout * 4);
            }

            if (J2534Err.ERR_BUFFER_EMPTY == m_status || J2534Err.ERR_TIMEOUT == m_status)
            {
                if (numMsgs > 0)
                {
                    // Select the last value
                    PassThruMsg msg = rxMsgs.AsMsgList(numMsgs).Last();
                    value = msg.GetBytes().ToList();
                    value.RemoveRange(0, txMsg.GetBytes().Length);
                    return(true);
                }
                return(false);
            }
            return(false);
        }
Esempio n. 29
0
        /// <summary>
        /// </summary>
        /// <returns>OpenResult.OK is returned on success. Otherwise OpenResult.OpenError is
        /// returned.</returns>
        override public OpenResult open()
        {
            if (isOpen())
            {
                close();
            }

            m_deviceId = 0;
            m_status   = passThru.PassThruOpen(IntPtr.Zero, ref m_deviceId);
            if (m_status != J2534Err.STATUS_NOERROR)
            {
                return(OpenResult.OpenError);
            }

            m_readThread = new Thread(readMessages)
            {
                Name = "J2534CANDevice.m_readThread"
            };
            m_endThread = false;

            if (TrionicECU == API.ECU.TRIONIC5)
            {
                m_status = passThru.PassThruConnect(m_deviceId, ProtocolID.CAN, ConnectFlag.NONE, BaudRate.CAN_615000, ref m_channelId);
            }
            else
            {
                m_status = passThru.PassThruConnect(m_deviceId, ProtocolID.CAN, ConnectFlag.NONE, BaudRate.CAN_500000, ref m_channelId);
            }
            if (J2534Err.STATUS_NOERROR != m_status)
            {
                return(OpenResult.OpenError);
            }

            uint acpFilt = 0xFFFF;
            uint acpMask = 0x0000;

            foreach (var id in AcceptOnlyMessageIds)
            {
                acpFilt &= id;
                acpMask |= id;
            }
            acpMask = (~acpMask & 0x7FF) | acpFilt;

            logger.Debug("Filter: " + acpFilt.ToString("X8"));
            logger.Debug("Mask:   " + acpMask.ToString("X8"));

            byte[] maskBytes    = new byte[4];
            byte[] patternBytes = new byte[4];

            for (int i = 0; i < 4; i++)
            {
                maskBytes[i]    = (byte)(acpMask >> (i * 8));
                patternBytes[i] = (byte)(acpFilt >> (i * 8));
            }

            //PassThruMsg maskMsg    = new PassThruMsg(ProtocolID.CAN, TxFlag.NONE, maskBytes);
            //PassThruMsg patternMsg = new PassThruMsg(ProtocolID.CAN, TxFlag.NONE, patternBytes);
            PassThruMsg maskMsg    = new PassThruMsg(ProtocolID.CAN, TxFlag.NONE, new byte[] { 0x00, 0x00, 0x00, 0x00 });
            PassThruMsg patternMsg = new PassThruMsg(ProtocolID.CAN, TxFlag.NONE, new byte[] { 0x00, 0x00, 0x00, 0x00 });
            int         filterId   = 0;

            m_status = passThru.PassThruStartMsgFilter(
                m_channelId,
                FilterType.PASS_FILTER,
                maskMsg.ToIntPtr(),
                patternMsg.ToIntPtr(),
                IntPtr.Zero,
                ref filterId);
            if (J2534Err.STATUS_NOERROR != m_status)
            {
                return(OpenResult.OpenError);
            }

            m_status = passThru.PassThruIoctl(m_channelId, (int)Ioctl.CLEAR_RX_BUFFER, IntPtr.Zero, IntPtr.Zero);
            if (J2534Err.STATUS_NOERROR != m_status)
            {
                return(OpenResult.OpenError);
            }

            logger.Debug("P bus connected");
            if (m_readThread.ThreadState == ThreadState.Unstarted)
            {
                m_readThread.Start();
            }
            m_deviceIsOpen = true;
            return(OpenResult.OK);
        }