Exemple #1
0
        /*
         * Connect to GMLan SW CAN Protocol (PIN 1)
         */
        private bool ConnectSWCan(int deviceId, ref int channelId)
        {
            m_status = m_j2534Interface.PassThruConnect(deviceId, ProtocolID.SW_CAN, ConnectFlag.CAN_ID_BOTH, BaudRate.CAN_33300, ref channelId);
            if (J2534Err.STATUS_NOERROR != m_status)
            {
                m_j2534Interface.PassThruDisconnect(channelId);
                return(false);
            }

            SConfig sConfig = new SConfig();

            sConfig.Parameter = ConfigParameter.J1962_PINS;
            sConfig.Value     = 0x0100;
            List <SConfig> sConfigs = new List <SConfig>();

            sConfigs.Add(sConfig);

            SConfigList sConfigList = new SConfigList();

            sConfigList.Count   = 1;
            sConfigList.ListPtr = sConfigs.ToIntPtr();

            m_status = m_j2534Interface.PassThruIoctl(channelId, (int)Ioctl.SET_CONFIG, sConfigList.ToIntPtr(), IntPtr.Zero);
            if (J2534Err.STATUS_NOERROR != m_status)
            {
                m_j2534Interface.PassThruDisconnect(channelId);
                return(false);
            }

            return(true);
        }
Exemple #2
0
 public OBDConnection(IJ2534Extended j2534Interface)
 {
     this.J2534Interface = j2534Interface;
     _isConnected        = false;
     ProtocolId          = ProtocolID.ISO15765;
     J2534Status         = J2534Err.STATUS_NOERROR;
 }
Exemple #3
0
        public float PassThruSetProgrammingVoltage(PinNumber pinNumber, PinVoltage mv)
        {
            uint milliVolts = (uint)mv;

            if (milliVolts < 5000)
            {
                milliVolts = 5000;
            }
            if (milliVolts > 20000 && mv != PinVoltage.VOLTAGE_OFF && mv != PinVoltage.SHORT_TO_GROUND)
            {
                milliVolts = 20000;
            }

            J2534Status = J2534Interface.PassThruSetProgrammingVoltage(DeviceId, pinNumber, milliVolts);
            if (J2534Status != J2534Err.STATUS_NOERROR)
            {
                throw new J2534Exception(J2534Status);
            }

            Thread.Sleep(10);
            int mvActual = 0;

            J2534Status = J2534Interface.ReadProgrammingVoltage(DeviceId, ref mvActual);
            if (J2534Status != J2534Err.STATUS_NOERROR)
            {
                throw new J2534Exception(J2534Status);
            }
            float voltage = ((float)mvActual);

            return(voltage);
        }
Exemple #4
0
 private void ThrowIfError(J2534Err status)
 {
     if (status != J2534Err.STATUS_NOERROR)
     {
         throw PassThruInterface.GetPassThruException();
     }
 }
Exemple #5
0
 public ObdComm(IJ2534 j2534Interface)
 {
     m_j2534Interface = j2534Interface;
     m_isConnected = false;
     m_protocol = ProtocolID.ISO15765;
     m_status = J2534Err.STATUS_NOERROR;
 }
Exemple #6
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);
        }
Exemple #7
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));
        }
Exemple #8
0
 public ObdComm(IJ2534Extended j2534Interface)
 {
     m_j2534Interface = j2534Interface;
     m_isConnected    = false;
     m_protocol       = ProtocolID.ISO15765;
     m_status         = J2534Err.STATUS_NOERROR;
 }
        public bool IsConnectDevice = false; //用于表示是否成功连接一个设备


        public retstate connectToDevice(int DeviceSelect, string RequestID, string ResponseID, BaudRate baudRate)
        {
            retstate ret = retstate.OK;

            if (!IsConnectDevice)
            {
                passThru.LoadLibrary(availableJ2534Devices[DeviceSelect]);
                J2534ErrStatus = passThru.Open(ref deviceId);

                if ((J2534ErrStatus == J2534Err.STATUS_NOERROR))
                {
                    // OpenADevice = connectCAN();
                    IsConnectDevice = ConnectIso15765(RequestID, ResponseID, baudRate);
                    if (!IsConnectDevice)
                    {
                        ret = retstate.NOT_OK;
                    }
                }
                else
                {
                    ret = retstate.NOT_OK;
                }
            }

            return(ret);
        }
Exemple #10
0
        public J2534Err ReadMsgs(int channelId, ref List <PassThruMsg> msgs, ref int numMsgs, int timeout)
        {
            UnsafePassThruMsg[] pMsgs       = new UnsafePassThruMsg[numMsgs];
            J2534Err            returnValue = (J2534Err)m_wrapper.ReadMsgs(channelId, ref pMsgs[0], ref numMsgs, timeout);

            if (returnValue == J2534Err.STATUS_NOERROR)
            {
                for (int i = 0; i < numMsgs; i++)
                {
                    msgs.Add(ConvertPassThruMsg(pMsgs[i]));
                }
            }


            /*
             * IntPtr pMsg = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UnsafePassThruMsg)) * 50);
             * IntPtr pNextMsg = IntPtr.Zero;
             * IntPtr[] pMsgs = new IntPtr[50];
             *
             * J2534Err returnValue = (J2534Err)m_wrapper.ReadMsgs(channelId, pMsg, ref numMsgs, timeout);
             * if (returnValue == J2534Err.STATUS_NOERROR)
             * {
             *  for (int i = 0; i < numMsgs; i++)
             *  {
             *      pNextMsg = (IntPtr)(Marshal.SizeOf(typeof(UnsafePassThruMsg)) * i + (int)pMsg);
             *      UnsafePassThruMsg uMsg = (UnsafePassThruMsg)Marshal.PtrToStructure(pMsg, typeof(UnsafePassThruMsg));
             *      msgs.Add(ConvertPassThruMsg(uMsg));
             *  }
             * }
             * Marshal.FreeHGlobal(pMsg);
             */
            return(returnValue);
        }
Exemple #11
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;
        }
Exemple #12
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;
        }
Exemple #13
0
 public void Connect()
 {
     DeviceId    = 0;
     J2534Status = J2534Interface.PassThruOpen(IntPtr.Zero, ref DeviceId);
     if (J2534Status != J2534Err.STATUS_NOERROR)
     {
         throw new J2534Exception(J2534Status);
     }
 }
Exemple #14
0
 public bool Disconnect()
 {
     m_status = m_j2534Interface.PassThruClose(m_deviceId);
     if (m_status != J2534Err.STATUS_NOERROR)
     {
         return(false);
     }
     return(true);
 }
Exemple #15
0
 /// <summary>
 /// Disconnects from physical scantool
 /// </summary>
 private Response <J2534Err> DisconnectTool()
 {
     OBDError = J2534Port.Functions.PassThruClose(DeviceID);
     if (OBDError != J2534Err.STATUS_NOERROR)
     {
         //big problems, do something here
     }
     IsJ2534Open = false;
     return(Response.Create(ResponseStatus.Success, OBDError));
 }
Exemple #16
0
 /// <summary>
 /// Disconnect from protocol
 /// </summary>
 private Response <J2534Err> DisconnectFromProtocol()
 {
     OBDError = J2534Port.Functions.PassThruDisconnect((int)ChannelID);
     if (OBDError != J2534Err.STATUS_NOERROR)
     {
         return(Response.Create(ResponseStatus.Error, OBDError));
     }
     IsProtocolOpen = false;
     return(Response.Create(ResponseStatus.Success, OBDError));
 }
Exemple #17
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);
        }
Exemple #18
0
 /// <summary>
 /// connect to selected protocol
 /// Must provide protocol, speed, connection flags, recommended optional is pins
 /// </summary>
 private Response <J2534Err> ConnectToProtocol(ProtocolID ReqProtocol, BaudRate Speed, ConnectFlag ConnectFlags)
 {
     OBDError = J2534Port.Functions.PassThruConnect(DeviceID, ReqProtocol, ConnectFlags, Speed, ref ChannelID);
     if (OBDError != J2534Err.STATUS_NOERROR)
     {
         return(Response.Create(ResponseStatus.Error, OBDError));
     }
     Protocol       = ReqProtocol;
     IsProtocolOpen = true;
     return(Response.Create(ResponseStatus.Success, OBDError));
 }
Exemple #19
0
        public bool GetBatteryVoltage(ref double voltage)
        {
            int millivolts = 0;

            m_status = m_j2534Interface.ReadBatteryVoltage(m_deviceId, ref millivolts);
            if (J2534Err.STATUS_NOERROR == m_status)
            {
                voltage = millivolts / 1000.0;
                return(true);
            }
            return(false);
        }
Exemple #20
0
        public float ReadProgrammingVoltage()
        {
            int mv = 0;

            J2534Status = J2534Interface.ReadProgrammingVoltage(DeviceId, ref mv);
            if (J2534Status != J2534Err.STATUS_NOERROR)
            {
                throw new J2534Exception(J2534Status);
            }
            float voltage = ((float)mv);

            return(voltage);
        }
        public void RxMsg(TextBox ResponseID, Action <string, int, string, string> Callback, Action <byte[]> CallDllCallback, Action <byte[]> CallSyncCallback)
        {
            int                numMsgs     = 100;
            int                msgCount    = 0;
            string             strDataID   = "";
            string             strDatebyte = "";
            List <PassThruMsg> rxMsgs      = new List <PassThruMsg>();
            J2534Err           status      = J2534Err.STATUS_NOERROR;

            /* if not connect device, return */
            if (!IsConnectDevice)
            {
                return;
            }

            numMsgs = 10;                                                       //test line
            status  = passThru.ReadMsgs(channelId, ref rxMsgs, ref numMsgs, 0); /////////////////////
            if (status == J2534Err.STATUS_NOERROR)                              //maybe no use
            {
                msgCount = rxMsgs.Count;
                for (int k = 0; k < msgCount; k++)
                {
                    strDataID   = "";
                    strDatebyte = "";
                    if (rxMsgs[k].Data.Length > 4)   //前四个字节是地址  //长帧回的第一帧猜测只是ID的4个字节
                    {
                        for (int i = 0; i < 4; i++)
                        {
                            strDataID += string.Format("{0:X2}", rxMsgs[k].Data[i]);   //转2个16进制表示的数字
                        }
                        if (strDataID.TrimStart('0') == ResponseID.Text.Trim().ToUpper())
                        {
                            for (int i = 0; i < (rxMsgs[k].Data.Length - 4); i++)
                            {
                                strDatebyte += string.Format("{0:X2}", rxMsgs[k].Data[i + 4]) + " ";
                            }
                            /*Update UI*/
                            Callback(strDataID.TrimStart('0'), rxMsgs[k].Data.Length - 4, strDatebyte, "Rx");
                            /*calldll caculate  key by receive seed*/
                            CallDllCallback(rxMsgs[k].Data);
                            /* synchronous rx data for other module */
                            CallSyncCallback(rxMsgs[k].Data);
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
            }
        }
        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");
        }
Exemple #23
0
        public J2534Err GetLastError(ref string errorDescription)
        {
            IntPtr   pErrorDescription = Marshal.AllocHGlobal(120);
            J2534Err returnValue       = (J2534Err)m_wrapper.GetLastError(pErrorDescription);

            if (returnValue == J2534Err.STATUS_NOERROR)
            {
                errorDescription = Marshal.PtrToStringAnsi(pErrorDescription);
            }

            Marshal.FreeHGlobal(pErrorDescription);

            return(returnValue);
        }
Exemple #24
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));
        }
Exemple #25
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);
            }
        }
Exemple #26
0
        /// <summary>
        /// Read battery voltage
        /// </summary>
        public Response <double> ReadVoltage()
        {
            double Volts      = 0;
            int    VoltsAsInt = 0;

            OBDError = J2534Port.Functions.ReadBatteryVoltage((int)DeviceID, ref VoltsAsInt);
            if (OBDError != J2534Err.STATUS_NOERROR)
            {
                return(Response.Create(ResponseStatus.Error, Volts));
            }
            else
            {
                Volts = VoltsAsInt / 1000.0;
                return(Response.Create(ResponseStatus.Success, Volts));
            }
        }
Exemple #27
0
        /// <summary>
        /// Returns a list of byte arrays with the tX messages
        /// </summary>
        /// <param name="replyBytes"></param>
        /// <returns></returns>
        public void ReadAllMessages(out List <PassThruMsg> messages, int numMsgs, int timeout, bool readUntilTimeout = true)
        {
            J2534Status = J2534Interface.ReadAllMessages(ChannelId, numMsgs, timeout, out messages, readUntilTimeout);

            if (J2534Status != J2534Err.STATUS_NOERROR)
            {
                throw new J2534Exception(J2534Status);
            }
            else
            {
                if (messages.Count < numMsgs)
                {
                    throw new J2534Exception(J2534Err.ERR_BUFFER_EMPTY);
                }
            }
        }
Exemple #28
0
        public J2534Err ReadBatteryVoltage(int deviceId, ref int voltage)
        {
            IntPtr input  = IntPtr.Zero;
            IntPtr output = Marshal.AllocHGlobal(8);

            J2534Err returnValue = (J2534Err)m_wrapper.Ioctl(deviceId, (int)Ioctl.READ_VBATT, input, output);

            if (returnValue == J2534Err.STATUS_NOERROR)
            {
                voltage = Marshal.ReadInt32(output);
            }

            Marshal.FreeHGlobal(output);

            return(returnValue);
        }
Exemple #29
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);
        }
Exemple #30
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);
            }
        }
Exemple #31
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);
            }
        }
Exemple #32
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;
        }
Exemple #33
0
 public bool GetBatteryVoltage(ref double voltage)
 {
     int millivolts = 0;
     m_status = m_j2534Interface.ReadBatteryVoltage(m_deviceId, ref millivolts);
     if (J2534Err.STATUS_NOERROR == m_status)
     {
         voltage = millivolts / 1000.0;
         return true;
     }
     return false;
 }
Exemple #34
0
 public bool DetectProtocol()
 {
     // possible return values:
     //  ProtocolID.ISO15765; // CAN
     //  ProtocolID.ISO9141;  // ISO-K
     //  ProtocolID.J1850PWM;  // J1850PWM
     //  ProtocolID.J1850VPW;  // J1850VPW
     m_deviceId = 0;
     m_status = m_j2534Interface.Open(ref m_deviceId);
     if (m_status != J2534Err.STATUS_NOERROR)
         return false;
     if (ConnectIso15765())
     {
         m_protocol = ProtocolID.ISO15765;
         m_isConnected = true;
     }
     return true;
 }
Exemple #35
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;
        }
Exemple #36
0
 public bool Disconnect()
 {
     m_status = m_j2534Interface.Close(m_deviceId);
     if (m_status != J2534Err.STATUS_NOERROR)
     {
         return false;
     }
     return true;
 }
Exemple #37
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;
        }
Exemple #38
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;
        }