//Opens the channel selected in the "Channel" input box
        void openChannelButton_Click(object sender, RoutedEventArgs e)
        {
            //channel = Convert.ToInt32(channelBox.Text);
            channel     = Convert.ToInt32(channelComboBox.SelectedIndex);
            channelName = ((ComboBoxItem)channelComboBox.SelectedItem).Content.ToString();

            //Get a handle for sending
            sendHandle = Canlib.canOpenChannel(channel, Canlib.canOPEN_REQUIRE_EXTENDED | Canlib.canOPEN_ACCEPT_VIRTUAL);
            //Get a handle for reading
            readHandle = Canlib.canOpenChannel(channel, Canlib.canOPEN_REQUIRE_EXTENDED | Canlib.canOPEN_ACCEPT_VIRTUAL);

            CheckStatus("Opening channel " + channelName, (Canlib.canStatus)sendHandle);
            if (sendHandle >= 0 && readHandle >= 0)
            {
                openChannelButton.IsEnabled = false;
                //channelBox.IsEnabled = false;
                channelComboBox.IsEnabled    = false;
                closeChannelButton.IsEnabled = true;
                busOnButton.IsEnabled        = true;
                bitrateComboBox.IsEnabled    = true;
            }
            else
            {
                MessageBox.Show("Opening Channel " + channelName + " failed. Please try again.");
            }
        }
Beispiel #2
0
        /*
         * Initiates the channel
         */
        public void initChannel(int channel, string bitrate)
        {
            Canlib.canStatus status;

            Canlib.canInitializeLibrary();
            int hnd = Canlib.canOpenChannel(channel, Canlib.canOPEN_ACCEPT_VIRTUAL);

            if (hnd >= 0)
            {
                chanHandle = hnd;

                Dictionary <string, int> dicBitRates = new Dictionary <string, int>()
                {
                    { "125 kb/s", Canlib.canBITRATE_125K },
                    { "250 kb/s", Canlib.canBITRATE_250K },
                    { "500 kb/s", Canlib.canBITRATE_500K },
                    { "1 Mb/s", Canlib.BAUD_1M }
                };

                status = Canlib.canSetBusParams(chanHandle, dicBitRates[bitrate], 0, 0, 0, 0, 0);
                status = Canlib.canBusOn(chanHandle);
                if (status == Canlib.canStatus.canOK)
                {
                    channelOn = true;
                }
            }
        }
Beispiel #3
0
        public bool CAN_OpenChannel(int mode)
        {
            int _hnd = -1;

            if (mode == 0)
            {
                _hnd = Canlib.canOpenChannel(this._Channel, Canlib.canOPEN_ACCEPT_LARGE_DLC);
            }
            else
            {
                _hnd = Canlib.canOpenChannel(this._Channel, Canlib.canOPEN_ACCEPT_LARGE_DLC);
            }

            if (_hnd >= 0)
            {
                this.handle = _hnd;
                Canlib.canAccept(handle, 0x7DF, Canlib.canFILTER_SET_CODE_STD);
                Canlib.canAccept(handle, 0x7D0, Canlib.canFILTER_SET_MASK_STD);
                return(true);
            }
            else
            {
                return(false);
            }
        }
        //Opens the channel selected in the "Channel" input box
        public void openChannel(int channel)
        {
            int hnd = Canlib.canOpenChannel(channel, Canlib.canOPEN_ACCEPT_VIRTUAL);

            if (hnd >= 0)
            {
                handle       = hnd;
                this.channel = channel;
            }
        }
Beispiel #5
0
 private void OpenChannelWithParamsC200(out int hnd, byte btr0, byte btr1)
 {
     logger.Debug("hnd = canlibCLSNET.Canlib.canOpenChannel()");
     hnd = Canlib.canOpenChannel(ChannelNumber, 0);
     logger.Debug("canlibCLSNET.Canlib.canSetBusParams(hnd)");
     Canlib.canStatus statusSetParam = Canlib.canSetBusParamsC200(hnd, btr0, btr1);
     logger.Debug("canlibCLSNET.Canlib.canBusOn(hnd)");
     Canlib.canStatus statusOn = Canlib.canBusOn(hnd);
     Canlib.canIoCtl(hnd, Canlib.canIOCTL_SET_LOCAL_TXECHO, 0);
 }
Beispiel #6
0
 private void OpenChannel(out int hnd, int bitrate)
 {
     logger.Debug("hnd = canlibCLSNET.Canlib.canOpenChannel()");
     hnd = Canlib.canOpenChannel(ChannelNumber, 0);
     logger.Debug("canlibCLSNET.Canlib.canSetBusParams(hnd)");
     Canlib.canStatus statusSetParam = Canlib.canSetBusParams(hnd, bitrate, 0, 0, 0, 0, 0);
     logger.Debug("canlibCLSNET.Canlib.canBusOn(hnd)");
     Canlib.canStatus statusOn = Canlib.canBusOn(hnd);
     Canlib.canIoCtl(hnd, Canlib.canIOCTL_SET_LOCAL_TXECHO, 0);
 }
Beispiel #7
0
        //Opens the channel selected in the "Channel" input box
        private void openChannelButton_Click(object sender, RoutedEventArgs e)
        {
            channel = Convert.ToInt32(channelBox.Text);
            int hnd = Canlib.canOpenChannel(channel, Canlib.canOPEN_ACCEPT_VIRTUAL);

            CheckStatus("Open channel", (Canlib.canStatus)hnd);
            if (hnd >= 0)
            {
                handle = hnd;
            }
        }
Beispiel #8
0
        /// <summary>
        /// The open method tries to connect to both busses to see if one of them is connected and
        /// active. The first strategy is to listen for any CAN message. If this fails there is a
        /// check to see if the application is started after an interrupted flash session. This is
        /// done by sending a message to set address and length (only for P-bus).
        /// </summary>
        /// <returns>OpenResult.OK is returned on success. Otherwise OpenResult.OpenError is
        /// returned.</returns>
        override public OpenResult open()
        {
            Canlib.canInitializeLibrary();

            //Check if bus is connected
            if (isOpen())
            {
                close();
            }
            Thread.Sleep(200);
            m_readThread = new Thread(readMessages)
            {
                Name = "KvaserCANDevice.m_readThread"
            };

            m_endThread = false;

            // Take first adapter...
            string[] adapters = GetAdapterNames();
            if (adapters.Length == 0)
            {
                return(OpenResult.OpenError);
            }
            SetSelectedAdapter(adapters[0]);

            //Check if P bus is connected
            logger.Debug("handle1 = canlibCLSNET.Canlib.canOpenChannel()");
            handleWrite = Canlib.canOpenChannel(ChannelNumber, 0);
            logger.Debug("canlibCLSNET.Canlib.canSetBusParams(handleWrite)");
            Canlib.canStatus statusSetParamWrite = Canlib.canSetBusParamsC200(handleWrite, 0x40, 0x37);
            logger.Debug("canlibCLSNET.Canlib.canBusOn(handleWrite)");
            Canlib.canStatus statusOnWrite = Canlib.canBusOn(handleWrite);
            Canlib.canIoCtl(handleWrite, Canlib.canIOCTL_SET_LOCAL_TXECHO, 0);
            //
            logger.Debug("handle2 = canlibCLSNET.Canlib.canOpenChannel()");
            handleRead = Canlib.canOpenChannel(ChannelNumber, 0);
            logger.Debug("canlibCLSNET.Canlib.canSetBusParams(handleRead)");
            Canlib.canStatus statusSetParamRead = Canlib.canSetBusParamsC200(handleRead, 0x40, 0x37);
            logger.Debug("canlibCLSNET.Canlib.canBusOn(handleRead)");
            Canlib.canStatus statusOnRead = Canlib.canBusOn(handleRead);
            Canlib.canIoCtl(handleRead, Canlib.canIOCTL_SET_LOCAL_TXECHO, 0);

            if (handleWrite < 0 || handleRead < 0)
            {
                return(OpenResult.OpenError);
            }

            logger.Debug("P bus connected");
            if (m_readThread.ThreadState == ThreadState.Unstarted)
            {
                m_readThread.Start();
            }
            return(OpenResult.OK);
        }
Beispiel #9
0
        /*
         * Looks for messages and sends them to the output box.
         */
        private void DumpMessageLoop(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            Canlib.canStatus status;
            int id;

            byte[] data = new byte[8];
            int    dlc;
            int    flags;
            long   time;
            bool   noError = true;
            string msg;

            //Open up a new handle for reading
            readHandle = Canlib.canOpenChannel(channel, Canlib.canOPEN_ACCEPT_VIRTUAL);

            status = Canlib.canBusOn(readHandle);

            while (noError && onBus && readHandle >= 0)
            {
                status = Canlib.canReadWait(readHandle, out id, data, out dlc, out flags, out time, 50);

                if (status == Canlib.canStatus.canOK)
                {
                    if ((flags & Canlib.canMSG_ERROR_FRAME) == Canlib.canMSG_ERROR_FRAME)
                    {
                        msg = "***ERROR FRAME RECEIVED***";
                    }
                    else
                    {
                        msg = String.Format("{0}  {1}  {2:x2} {3:x2} {4:x2} {5:x2} {6:x2} {7:x2} {8:x2} {9:x2}   {10}\r",
                                            id, dlc, data[0], data[1], data[2], data[3], data[4],
                                            data[5], data[6], data[7], time);
                    }

                    //Sends the message to the ProcessMessage method
                    worker.ReportProgress(0, msg);
                }

                else if (status != Canlib.canStatus.canERR_NOMSG)
                {
                    //Sends the error status to the ProcessMessage method and breaks the loop
                    worker.ReportProgress(100, status);
                    noError = false;
                }
            }
            Canlib.canBusOff(readHandle);
        }
 public bool _OpenChannel(int canNodeId)
 {
     lock (LockCanIdsDic) {
         CANNodeId = canNodeId;
         int openedChanel = Canlib.canOpenChannel(lastOpenedChanel + 1, CANNodeId);
         if (openedChanel < 0)
         {
             return(FAIL);
         }
         dic_CanChanels[CANNodeId] = openedChanel;
         CANHandle            = openedChanel;
         hasChangeInNodesList = true;
         return(PASS);
     }
 }
Beispiel #11
0
        public KvaserCAN(MainWindow wnd) //public constructor
        {
            this.wnd = wnd;

            Canlib.canInitializeLibrary();

            hcan = Canlib.canOpenChannel(channel, Canlib.canOPEN_REQUIRE_INIT_ACCESS);
            if (hcan < 0)
            {
                string error;
                Canlib.canGetErrorText((Canlib.canStatus)hcan, out error);
                send2Terminal(error);
            }
            else
            {
                Canlib.canSetBusParams(hcan, bitr, 0, 0, 0, 0, 0); //parameters set by dafault based on bitr
                Canlib.canBusOn(hcan);
                send2Terminal("Can liin avatud");

                //DumpMessageLoop(hcan);
            }
        }
Beispiel #12
0
        public bool CanLongMsgSend(int id, byte[] data, int datalength, int retrycount, double timeout, ref int EcuID, ref byte[] READDATA, ref string errmsg)
        {
            if ((datalength < 9) || (data.Length < 9))
            {
                errmsg = "Command Data Length <=8";
                return(false);
            }

            bool _LoopChk = true;
            int  _EcuID;

            byte[] _EcuData = new byte[8];
            int    _EcuDlc;
            int    _EcuFlags;
            long   _EcuTime;

            int    _Ecu_FS    = -1; // 정상적으로 수신시 확인되는 값, FS FlowStatus, BS BlockSize, STmin
            int    _Ecu_BS    = 0;
            int    _Ecu_STmin = 0;
            double _Ecu_Stmin_sec; // 소수점단위 계산
            bool   _Ecu_FlowControl_Receive_OK = false;

            byte[] _Data_FF           = new byte[8];
            byte[] _Data_CF           = new byte[8];
            int    _LastSendDataIndex = 0;

            Canlib.canStatus status;
            Stopwatch        _stopwatch_total = new Stopwatch();
            Stopwatch        _stopwatch_send  = new Stopwatch();

            // 명령 만들기
            _Data_FF[0] = 0x10;

            Int32 _DataLength_12bit = 0x00000000;

            _DataLength_12bit = (Int32)datalength;
            _DataLength_12bit = _DataLength_12bit & 0x00000FFF;

            byte byte1Lownibble;
            byte byte2;

            byte1Lownibble = (byte)((_DataLength_12bit & 0x00000F00) >> 16);
            byte2          = (byte)(_DataLength_12bit & 0x000000FF);

            _Data_FF[0] = (byte)(0x10 | byte1Lownibble);
            _Data_FF[1] = byte2;
            _Data_FF[2] = data[0];
            _Data_FF[3] = data[1];
            _Data_FF[4] = data[2];
            _Data_FF[5] = data[3];
            _Data_FF[6] = data[4];
            _Data_FF[7] = data[5];

            _LastSendDataIndex = 6;
            //
            //Canlib.canBusOn(handle);
            //status = Canlib.canWrite(handle, id, _Data_FF, 8, flags);
            //Open up a new handle for reading
            readHandle = Canlib.canOpenChannel(channel, Canlib.canOPEN_ACCEPT_LARGE_DLC);
            status     = Canlib.canAccept(readHandle, 0x7DF, Canlib.canFILTER_SET_CODE_STD);
            status     = Canlib.canAccept(readHandle, 0x7D0, Canlib.canFILTER_SET_MASK_STD);
            status     = Canlib.canBusOn(readHandle);
            if (status == Canlib.canStatus.canOK)
            {
                onBus = true;
            }
            else
            {
                onBus = false;
            }
            if (readHandle < 0)
            {
                errmsg = "canOpenChannel Handle create error";
                return(false);
            }
            if (!onBus)
            {
                errmsg = "onBus false";
                return(false);
            }
            _stopwatch_total.Reset();
            _stopwatch_total.Start();
            _stopwatch_send.Reset();
            _stopwatch_send.Start();
            // Receive Channel Open -> SEND
            Canlib.canBusOn(handle);
            status = Canlib.canWrite(handle, id, _Data_FF, 8, flags);
            while (_LoopChk)
            {
                // TimeOut Check
                long   st            = _stopwatch_total.ElapsedMilliseconds;
                double _durationtime = st / 1000.0;  // ms -> sec
                if (_durationtime > timeout)
                {
                    // 설정시간안에 메세지 및 처리를 못했을 경우 종료
                    errmsg   = "timeout error";
                    _LoopChk = false;
                    break;
                }
                // Message Recieve Check
                bool _RecvOK = false;
                status = Canlib.canReadWait(readHandle, out _EcuID, _EcuData, out _EcuDlc, out _EcuFlags, out _EcuTime, 100); // 100ms timeout
                if (status == Canlib.canStatus.canOK)
                {
                    if ((_EcuFlags & Canlib.canMSG_ERROR_FRAME) == Canlib.canMSG_ERROR_FRAME)
                    {
                        errmsg = "***ERROR FRAME RECEIVED***";
                    }
                    else
                    {
                        errmsg = String.Format("ID={0:X4}  {1}  {2:X2} {3:X2} {4:X2} {5:X2} {6:X2} {7:X2} {8:X2} {9:X2}   {10}\r",
                                               _EcuID, _EcuDlc, _EcuData[0], _EcuData[1], _EcuData[2], _EcuData[3], _EcuData[4],
                                               _EcuData[5], _EcuData[6], _EcuData[7], _EcuTime);
                        if (_EcuID == 0x07D9)
                        {
                            _RecvOK = true;
                        }
                    }
                }
                else if (status != Canlib.canStatus.canERR_NOMSG)
                {
                    errmsg = "TimeOut:NO MSG";
                }
                //CheckStatus("Read message " + errmsg, status);
                //Canlib.canBusOff(readHandle);
                if ((_EcuID == 0x07D9) && (_RecvOK))
                {
                    byte EcuFC_Check = _EcuData[0];
                    EcuFC_Check = (byte)((EcuFC_Check & 0x00F0) >> 4);
                    if (EcuFC_Check == 3)
                    {
                        _LoopChk   = false;
                        _Ecu_FS    = (_EcuData[0] & 0x000F);
                        _Ecu_BS    = (int)(_EcuData[1] & 0x00FF);
                        _Ecu_STmin = (int)(_EcuData[2] & 0x00FF);
                        if (_Ecu_STmin <= 0x7F)
                        {
                            _Ecu_Stmin_sec = _Ecu_STmin * 0.001;
                        }
                        if (_Ecu_STmin >= 0xF1)
                        {
                            _Ecu_Stmin_sec = (_Ecu_STmin - 0xF0) * 0.0001;
                        }
                        _Ecu_FlowControl_Receive_OK = true;
                    }
                    string sndmsg = String.Format("ID={0:X4}  {1}  {2:X2} {3:X2} {4:X2} {5:X2} {6:X2} {7:X2} {8:X2} {9:X2}\r",
                                                  id, 8, _Data_FF[0], _Data_FF[1], _Data_FF[2], _Data_FF[3], _Data_FF[4],
                                                  _Data_FF[5], _Data_FF[6], _Data_FF[7]);
                    CheckStatus("PC->ECU " + sndmsg, Canlib.canStatus.canOK);
                    CheckStatus("ECU->PC " + errmsg, status);
                }
            }

            Canlib.canClose(readHandle);

            if (!_Ecu_FlowControl_Receive_OK)
            {
                errmsg = "Ecu FlowControl not arrived";
                return(false);
            }
            if (_Ecu_FS > 0)
            {
                errmsg = "Ecu FlowControl signal Busy";
                return(false);
            }



            // ECU에서 FC를 정상적으로 수신후 데이터 전송....
            _stopwatch_total.Reset();
            _stopwatch_total.Start();
            _stopwatch_send.Reset();
            _stopwatch_send.Start();
            _LoopChk = true;
            int  _SequenceNumber     = 1;
            byte _SN                 = (byte)_SequenceNumber;
            int  _BlockSendLoopCount = _Ecu_BS;

            Canlib.canBusOn(handle);
            bool _EcuLastReceiveOK = false;

            // CF 전송후 수신확인.
            //Open up a new handle for reading
            readHandle = Canlib.canOpenChannel(channel, Canlib.canOPEN_ACCEPT_LARGE_DLC);
            status     = Canlib.canAccept(readHandle, 0x7DF, Canlib.canFILTER_SET_CODE_STD);
            status     = Canlib.canAccept(readHandle, 0x7D0, Canlib.canFILTER_SET_MASK_STD);
            status     = Canlib.canBusOn(readHandle);
            if (status == Canlib.canStatus.canOK)
            {
                onBus = true;
            }
            else
            {
                onBus = false;
            }
            if (readHandle < 0)
            {
                errmsg = "canOpenChannel Handle create error";
                return(false);
            }
            if (!onBus)
            {
                errmsg = "onBus false";
                return(false);
            }

            while (_LoopChk)
            {
                // TimeOut Check
                long   st            = _stopwatch_total.ElapsedMilliseconds;
                double _durationtime = st / 1000.0;  // ms -> sec
                if (_durationtime > timeout)
                {
                    // 설정시간안에 메세지 및 처리를 못했을 경우 종료
                    errmsg   = "timeout error";
                    _LoopChk = false;
                    break;
                }
                if (datalength < _LastSendDataIndex)
                {
                    _LoopChk = false;
                    break;
                }
                _stopwatch_send.Reset();
                _stopwatch_send.Start();
                // CF 전송
                for (int hs = 0; hs < _BlockSendLoopCount; hs++)
                {
                    // FF전송후 CF 데이터 전송 준비
                    _Data_CF[0] = 0x20;
                    _Data_CF[0] = (byte)(_Data_CF[0] + _SN);
                    for (int i = 0; i < 7; i++)
                    {
                        if (_LastSendDataIndex < datalength)
                        {
                            _Data_CF[1 + i] = data[_LastSendDataIndex];
                        }
                        else
                        {
                            _Data_CF[1 + i] = 0x00; // 0xAA;
                        }
                        _LastSendDataIndex++;
                    }
                    _SN++;
                    if (_SN > 16)
                    {
                        _SN = 0;
                    }
                    status = Canlib.canWrite(handle, id, _Data_CF, 8, flags);
                    long   _dt    = _stopwatch_send.ElapsedMilliseconds;
                    string sndmsg = String.Format("ID={0:X4}  {1}  {2:X2} {3:X2} {4:X2} {5:X2} {6:X2} {7:X2} {8:X2} {9:X2}   {10:D5}ms\r",
                                                  id, 8, _Data_CF[0], _Data_CF[1], _Data_CF[2], _Data_CF[3], _Data_CF[4],
                                                  _Data_CF[5], _Data_CF[6], _Data_CF[7], _dt);
                    CheckStatus("PC->ECU " + sndmsg, status);
                    break; // Only One Run-----------------------------------------------실제 전송될 데이터 길이만큼만 전송함----------------------------------------------------------
                }


                // Message Recieve Check
                bool _RecvOK = false;

                bool      _FinalReceiveCheck = true;
                Stopwatch _Final             = new Stopwatch();
                _Final.Reset();
                _Final.Start();
                while (_FinalReceiveCheck)
                {
                    if ((_Final.ElapsedMilliseconds / 1000.0) > 3.0)
                    {
                        errmsg             = "Finnal ECU Receive Msg TIMEOUT";
                        _FinalReceiveCheck = false;
                        break;
                    }
                    status = Canlib.canReadWait(readHandle, out _EcuID, _EcuData, out _EcuDlc, out _EcuFlags, out _EcuTime, 100); // 100ms timeout
                    if (status == Canlib.canStatus.canOK)
                    {
                        if ((_EcuFlags & Canlib.canMSG_ERROR_FRAME) == Canlib.canMSG_ERROR_FRAME)
                        {
                            errmsg = "***ERROR FRAME RECEIVED***";
                        }
                        else
                        {
                            errmsg = String.Format("ID={0:X4}  {1}  {2:X2} {3:X2} {4:X2} {5:X2} {6:X2} {7:X2} {8:X2} {9:X2}   {10}\r",
                                                   _EcuID, _EcuDlc, _EcuData[0], _EcuData[1], _EcuData[2], _EcuData[3], _EcuData[4],
                                                   _EcuData[5], _EcuData[6], _EcuData[7], _EcuTime);
                            if (_EcuID == 0x07D9)
                            {
                                _RecvOK = true;
                                CheckStatus("ECU->PC " + errmsg, status);
                            }
                        }
                    }
                    else if (status != Canlib.canStatus.canERR_NOMSG)
                    {
                        errmsg = "TimeOut:NO MSG";
                    }
                    //CheckStatus("Read message " + errmsg, status);
                    //Canlib.canBusOff(readHandle);
                    if ((_EcuID == 0x07D9) && (_RecvOK))
                    {
                        Canlib.canBusOn(handle);
                        byte[] temp = new byte[8] {
                            0x30, 0x00, 0x02, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA
                        };
                        status = Canlib.canWrite(handle, 0x07D1, _Data_FF, 8, flags);
                        CheckStatus("PC->ECU " + "PC AutoResponse(0x30,0x00,0x02,0xAA,0xAA,0xAA,0xAA,0xaa", status);
                        Canlib.canBusOff(handle);
                        status = Canlib.canReadWait(readHandle, out _EcuID, _EcuData, out _EcuDlc, out _EcuFlags, out _EcuTime, 100);
                        if (status == Canlib.canStatus.canOK)
                        {
                            errmsg = String.Format("ID={0:X4}  {1}  {2:X2} {3:X2} {4:X2} {5:X2} {6:X2} {7:X2} {8:X2} {9:X2}   {10}\r",
                                                   _EcuID, _EcuDlc, _EcuData[0], _EcuData[1], _EcuData[2], _EcuData[3], _EcuData[4],
                                                   _EcuData[5], _EcuData[6], _EcuData[7], _EcuTime);
                            if (_EcuID == 0x07D9)
                            {
                                _RecvOK = true;
                                CheckStatus("ECU->PC " + errmsg, status);
                            }
                        }
                        _FinalReceiveCheck = false;
                        _EcuLastReceiveOK  = true;
                        _LoopChk           = false;
                        break;
                    }
                }
            }
            if (readHandle >= 0)
            {
                Canlib.canClose(readHandle);
            }
            if (_EcuLastReceiveOK)
            {
                if (_EcuData[1] == 0x62)
                {
                    return(true);
                }
                return(false);
            }
            else
            {
                return(false);
            }
        }
Beispiel #13
0
        /*
         * Looks for messages and sends them to the output box.
         */
        private void DumpMessageLoop(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            Canlib.canStatus status;
            int id;

            byte[] data = new byte[8];
            int    dlc;
            int    flags;
            long   time;
            bool   noError = true;
            var    msg     = "";

            //Open up a new handle for reading
            readHandle = Canlib.canOpenChannel(channel, Canlib.canOPEN_ACCEPT_VIRTUAL);

            status = Canlib.canBusOn(readHandle);

            while (noError && onBus && readHandle >= 0)
            {
                #region 接收指定ID报文
                var message = new byte[8];

                var idRS16 = Convert.ToInt32(idBox.Text, 16);
                var idRS   = Convert.ToInt32(idBox.Text);

                status = Canlib.canReadSpecific(readHandle, idRS16, message, out int dlcRS, out int flagRS, out long timeRS);
                if (status == Canlib.canStatus.canOK)
                {
                    DumpMessage dumpMessage = new DumpMessage();

                    if ((flagRS & Canlib.canMSG_ERROR_FRAME) == Canlib.canMSG_ERROR_FRAME)
                    {
                        //msgRS = "ERROR FRAME RECEIVED" + Environment.NewLine;
                    }
                    else
                    {
                        dumpMessage.id    = idRS16;
                        dumpMessage.idStr = idBox.Text;
                        dumpMessage.dlc   = dlcRS;
                        dumpMessage.data  = message;
                        dumpMessage.flags = flagRS;
                        dumpMessage.time  = timeRS;
                    }
                    //Sends the message to the ProcessMessage method
                    worker.ReportProgress(1, dumpMessage);
                }
                else if (status != Canlib.canStatus.canERR_NOMSG)
                {
                    //Sends the error status to the ProcessMessage method and breaks the loop
                    worker.ReportProgress(100, status);
                }
                #endregion

                #region 接收所有报文
                //status = Canlib.canReadWait(readHandle, out id, data, out dlc, out flags, out time, 50);
                //if (status == Canlib.canStatus.canOK)
                //{
                //    DumpMessage dumpMessage = new DumpMessage();

                //    if ((flags & Canlib.canMSG_ERROR_FRAME) == Canlib.canMSG_ERROR_FRAME)
                //    {
                //        //msg = "***ERROR FRAME RECEIVED***" + Environment.NewLine;
                //    }
                //    else
                //    {
                //        dumpMessage.id = id;
                //        dumpMessage.dlc = dlc;
                //        dumpMessage.data = data;
                //        dumpMessage.flags = flags;
                //        dumpMessage.time = time;
                //    }
                //    //Sends the message to the ProcessMessage method
                //    worker.ReportProgress(0, dumpMessage);
                //}
                //else if (status != Canlib.canStatus.canERR_NOMSG)
                //{
                //    //Sends the error status to the ProcessMessage method and breaks the loop
                //    worker.ReportProgress(100, status);
                //    noError = false;
                //}
                #endregion
            }
            Canlib.canBusOff(readHandle);
        }
Beispiel #14
0
        private void canThreadFunct()
        {
            int canHandle;

            Canlib.canStatus status;

            int channel_number = 0;
            int id;

            byte[] msg = new byte[8];
            int    dlc;
            int    flag;
            long   time;
            long   timeout;
            int    val0   = 0;
            int    val1   = 0;
            int    val2   = 0;
            int    val3   = 0;
            long   count0 = 1;
            long   count1 = 2;
            long   count2 = 3;
            long   count3 = 4;

            Canlib.canInitializeLibrary();
            canHandle = Canlib.canOpenChannel(channel_number, Canlib.canOPEN_NO_INIT_ACCESS);
            CheckStatus((Canlib.canStatus)canHandle, "canOpenChannel");

            // Next, take the channel on bus using the canBusOn method. This
            // needs to be done before we can send a message.
            status = Canlib.canBusOn(canHandle);
            CheckStatus(status, "canBusOn");

            timeout = 1000;

            while (!exit_request)
            {
                status = Canlib.canReadWait(canHandle, out id, msg, out dlc, out flag, out time, timeout);
                CheckStatus(status, "canReadWait");
                if (id == 0x700)
                {
                    val0   = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(msg, 0));
                    count0 = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(msg, 4));
                }
                if (id == 0x701)
                {
                    val1   = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(msg, 0));
                    count1 = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(msg, 4));
                }
                if (id == 0x702)
                {
                    val2   = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(msg, 0));
                    count2 = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(msg, 4));
                }
                if (id == 0x703)
                {
                    val3   = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(msg, 0));
                    count3 = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(msg, 4));
                }
                if (count0 == count1 && count0 == count2 && count0 == count3)
                {
                    realtimeChart.DataSample genValue = new realtimeChart.DataSample();
                    genValue.value[0] = val0;
                    genValue.value[1] = val1;
                    genValue.value[2] = val2;
                    genValue.value[3] = val3;
                    mainChart.AddValue(genValue);
                }
            }
            status = Canlib.canBusOff(canHandle);
            CheckStatus(status, "canBusOff");
        }
Beispiel #15
0
        } // End DetectCanInterfaces

        // ***************************************
        // GenericCanBusOn
        // Turns canInterface on based on User Selection
        // ***************************************
        public static int CanBusOn(string canInterface, string bitRateSetting)
        {
            string hardwareString0 = canInterface.Replace(" ", "");

            string[] msgOutput = hardwareString0.Split(';');

            int canHandle;
            int channelFlags;
            int KvaserCANBitrate = Canlib.canBITRATE_500K;

            Canlib.canStatus status;

            // Assigns settings for the adapter
            if (bitRateSetting == "1M")
            {
                KvaserCANBitrate = Canlib.canBITRATE_1M;
            }
            else if (bitRateSetting == "500K")
            {
                KvaserCANBitrate = Canlib.canBITRATE_500K;
            }
            else if (bitRateSetting == "250K")
            {
                KvaserCANBitrate = Canlib.canBITRATE_250K;
            }
            else if (bitRateSetting == "125K")
            {
                KvaserCANBitrate = Canlib.canBITRATE_125K;
            }
            else if (bitRateSetting == "100K")
            {
                KvaserCANBitrate = Canlib.canBITRATE_100K;
            }
            else if (bitRateSetting == "62K")
            {
                KvaserCANBitrate = Canlib.canBITRATE_62K;
            }
            else if (bitRateSetting == "50K")
            {
                KvaserCANBitrate = Canlib.canBITRATE_50K;
            }
            else if (bitRateSetting == "33K")
            {
                KvaserCANBitrate = 33000;
            }

            // Checks for Virtual Flag
            if (msgOutput[1].IndexOf("Virtual") != -1)
            {
                channelFlags = Canlib.canOPEN_ACCEPT_VIRTUAL;
            }
            else
            {
                channelFlags = 0;
            }

            // Opens CAN channel
            canHandle = Canlib.canOpenChannel(Convert.ToInt32(msgOutput[3]), channelFlags);

            // Sets parameters for the CAN channel; special parameters for 33K, single-wire operation
            if (bitRateSetting == "33K")
            {
                status = Canlib.canSetBusParams(canHandle, 33000, 5, 2, 2, 1, 0);
            }
            else
            {
                // Standard settings for other operations
                status = Canlib.canSetBusParams(canHandle, KvaserCANBitrate, 0, 0, 0, 0, 0);
            }

            if (status < 0)
            {
                ErrorLog.NewLogEntry("CAN", "Kvaser bus setting parameters failed: " + KvaserCANBitrate);
                return(-1);
            }
            else
            {
                ErrorLog.NewLogEntry("CAN", "Kvaser bus setting parameters success: " + KvaserCANBitrate);
            }

            // possible configuration for 33K single-wire operation; above settings work
            //Canlib.canSetBusParamsC200(canHandle, 0x5D, 0x05);

            status = Canlib.canBusOn(canHandle);
            if (status < 0)
            {
                ErrorLog.NewLogEntry("CAN", "Bus On Failed: " + msgOutput[1]);
                return(-1);
            }
            else
            {
                ErrorLog.NewLogEntry("CAN", "Bus On Success: " + msgOutput[1]);
            }

            // Associates the int holder for the Kvaser interface back with the interface dictionary structure
            BusInterface.AddHandle(canInterface, canHandle);

            //MainWindow.ErrorDisplayString("Bus On - BusInterface: " + canInterface + " ; Handle: " + canHandle);

            return(1);
        }
        public void _OpenAllConnections()
        {
            if (ActiveCanDriver == Consts.INTERFACE_RS232)
            {
                if (PortConnection.OpenPort())
                {
                    dic_CanChanels.Clear();
                    foreach (var entry in Globals.Vm_scis)
                    {
                        dic_CanChanels[entry.VM_UC_Main.NodeId] = 0;
                    }
                    Task.Factory.StartNew(() => {
                        int i = 0;
                        do
                        {
                            Globals.Vm_scis[0].HighFrequencyOn = true;
                            FrequencyManager.SendCCComand(vm_sci: Globals.Vm_scis[0]);
                            Thread.Sleep(5);
                        } while (!graphStarted && i < 500);//max 25 seconds
                    });
                }
            }
            else if (ActiveCanDriver == Consts.CAN_DRIVER_KVASER)
            {
                lock (LockCanIdsDic) {
                    hasChangeInNodesList = true;

                    Canlib.canInitializeLibrary();
                    foreach (var value in dic_CanChanels.Where(x => x.Value >= 0).Select(x => x.Value))
                    {
                        Canlib.canBusOff(value);
                        Canlib.canClose(value);
                    }
                    //lastOpenedChanel = 0;
                    dic_CanChanels.Clear();
                    foreach (var entry in Globals.Vm_scis.Where(entry => entry.VM_UC_Main != null))
                    {
                        dic_CanChanels[entry.VM_UC_Main.NodeId] = -1;
                    }
                    foreach (var key in dic_CanChanels.Select(x => x.Key).ToList())
                    {
                        int openedChanel = Canlib.canOpenChannel(lastOpenedChanel + 1, key);
                        if (openedChanel >= 0)
                        {
                            dic_CanChanels[key] = openedChanel;
                        }
                    }

                    foreach (var entry in dic_CanChanels.Where(x => x.Value >= 0))
                    {
                        Canlib.canSetBusParams(
                            handle: entry.Value,
                            freq: CANDesiredBitRate,
                            tseg2: 0,
                            tseg1: 0,
                            sjw: 0,
                            noSamp: 0,
                            syncmode: 0
                            );
                        Canlib.canBusOn(entry.Value);

                        //if (!setCanCardName() || !getCanBitRate()) {
                        //    CANStatus = Consts.BOOL_FAILED;
                        //    CANHandle = -1;
                        //}

                        //initialize the node
                        Canlib.canWrite(
                            handle: entry.Value,
                            id: 0,
                            msg: new byte[] { 1, (byte)entry.Key },
                            dlc: 2, //size of msg
                            flag: 2 //we have defined this as const
                            );
                    }
                }
                //get multiply value
                WriteToAll("AD", 0, true, true);

                //get ISR
                WriteToAll("AE", 0, true, true);
                graphStarted = false;
                //start Graph
                //todo fix for each nodeId
                Task.Factory.StartNew(() => {
                    int i = 0;
                    do
                    {
                        if (Globals.Vm_scis.Count > 0)
                        {
                            Globals.Vm_scis[0].HighFrequencyOn = true;
                            FrequencyManager.SendCCComand(1, vm_sci: Globals.Vm_scis[0]); // start graph plot with 6k frequency.
                            Thread.Sleep(5);
                        }
                        else
                        {
                            Debugger.Break();
                        }
                    } while (!graphStarted && i < 500 && Globals.Vm_scis.Count > 0);//max 25 seconds
                });
                //_can_status = RoundBoolLed.DISABLED;
            }
        }
        //initialise the usb interface library based on which interface was selected
        public static void initialiseCAN()
        {
            for (int i = 0; i < CAN_Channel.numOfChan; i++)
            {
                switch (CAN_Channel._INTERFACEs[i])
                {
                case CAN_Channel.CAN_INTERFACE.KVASER:


                    if (!KvaserInit)
                    {
                        Canlib.canInitializeLibrary();
                    }

                    if (CanInit)
                    {
                        Close();
                    }

                    numOfKvaser++;

                    canHandle[i] = Canlib.canOpenChannel(numOfKvaser - 1, Canlib.canOPEN_ACCEPT_VIRTUAL);
                    KvaserInit   = true;

                    //check whether handle was gotten successfully
                    ErrorControl(handle: canHandle[i], location: "canOpenChannel: initialise()");

                    switch (CAN_Channel._BAUDRATEs[i])
                    {
                    case CAN_Channel.CAN_BAUDRATE._250K:

                        status = Canlib.canSetBusParams(canHandle[i], Canlib.canBITRATE_250K, 0, 0, 0, 0, 0);

                        break;

                    case CAN_Channel.CAN_BAUDRATE._500K:

                        status = Canlib.canSetBusParams(canHandle[i], Canlib.canBITRATE_500K, 0, 0, 0, 0, 0);

                        break;

                    case CAN_Channel.CAN_BAUDRATE._1M:

                        status = Canlib.canSetBusParams(canHandle[i], Canlib.canBITRATE_1M, 0, 0, 0, 0, 0);
                        break;
                    }

                    ErrorControl(status: status, location: "canSetBusParams: initialise()");
                    Canlib.canSetBusOutputControl(canHandle[i], Canlib.canDRIVER_NORMAL);

                    //turn the bus on with a handle to the open channel to write data
                    Canlib.canBusOn(canHandle[i]);

                    break;

                case CAN_Channel.CAN_INTERFACE.PEAK:

                    if (CanInit)
                    {
                        Close();
                    }

                    numOfPeak++;

                    if (numOfPeak == 1)
                    {
                        canHandle[i] = PCANBasic.PCAN_USBBUS1;
                    }
                    if (numOfPeak == 2)
                    {
                        canHandle[i] = PCANBasic.PCAN_USBBUS2;
                    }

                    switch (CAN_Channel._BAUDRATEs[i])
                    {
                    case CAN_Channel.CAN_BAUDRATE._250K:

                        pCANBaudrate[numOfPeak - 1] = TPCANBaudrate.PCAN_BAUD_250K;

                        break;

                    case CAN_Channel.CAN_BAUDRATE._500K:

                        pCANBaudrate[numOfPeak - 1] = TPCANBaudrate.PCAN_BAUD_500K;

                        break;

                    case CAN_Channel.CAN_BAUDRATE._1M:

                        pCANBaudrate[numOfPeak - 1] = TPCANBaudrate.PCAN_BAUD_1M;
                        break;
                    }


                    if (PCANBasic.Initialize((ushort)canHandle[i], pCANBaudrate[numOfPeak - 1]) == TPCANStatus.PCAN_ERROR_INITIALIZE)
                    {
                        ErrorControl(-1, location: "PCANBasic.initialize: initialise()");
                        return;
                    }


                    break;
                }
            }

            CanInit     = true;
            numOfPeak   = 0;
            numOfKvaser = 0;
        }
Beispiel #18
0
        /// <summary>
        /// 打开CAN通道
        /// </summary>
        /// <param name="channel"></param>
        /// <param name="baud"></param>
        /// <returns></returns>
        public bool OpenChannel(int channel, string baud)
        {
            int canFreq;

            canHandler = Canlib.canOpenChannel(channel, Canlib.canOPEN_ACCEPT_VIRTUAL);
            if (canHandler != (int)Canlib.canStatus.canOK)
            {
                return(false);
            }

            switch (baud)
            {
            case "50000":
                canFreq = Canlib.BAUD_50K;
                break;

            case "62000":
                canFreq = Canlib.BAUD_62K;
                break;

            case "83000":
                canFreq = Canlib.BAUD_83K;
                break;

            case "100000":
                canFreq = Canlib.BAUD_100K;
                break;

            case "125000":
                canFreq = Canlib.BAUD_125K;
                break;

            case "250000":
                canFreq = Canlib.BAUD_250K;
                break;

            case "500000":
                canFreq = Canlib.BAUD_500K;
                break;

            case "1000000":
                canFreq = Canlib.BAUD_1M;
                break;

            default:
                canFreq = Canlib.BAUD_500K;
                break;
            }

            Canlib.canStatus canStatus = Canlib.canSetBusParams(canHandler, canFreq, 0x80, 0x3A, 1, 1, 0);
            if (canStatus != Canlib.canStatus.canOK)
            {
                return(false);
            }

            canStatus = Canlib.canBusOn(canHandler);
            if (canStatus != Canlib.canStatus.canOK)
            {
                return(false);
            }

            return(true);
        }
Beispiel #19
0
        /// <summary>
        /// The open method tries to connect to both busses to see if one of them is connected and
        /// active. The first strategy is to listen for any CAN message. If this fails there is a
        /// check to see if the application is started after an interrupted flash session. This is
        /// done by sending a message to set address and length (only for P-bus).
        /// </summary>
        /// <returns>OpenResult.OK is returned on success. Otherwise OpenResult.OpenError is
        /// returned.</returns>
        override public OpenResult open()
        {
            Canlib.canInitializeLibrary();

            //Check if bus is connected
            if (isOpen())
            {
                close();
            }
            Thread.Sleep(200);
            m_readThread = new Thread(readMessages)
            {
                Name = "KvaserCANDevice.m_readThread"
            };

            if (!UseOnlyPBus)
            {
                if (TrionicECU == ECU.TRIONIC7)
                {
                    logger.Debug("handle1 = canlibCLSNET.Canlib.canOpenChannel()");
                    handleWrite = Canlib.canOpenChannel(ChannelNumber, Canlib.canOPEN_ACCEPT_VIRTUAL);
                    logger.Debug("canlibCLSNET.Canlib.canSetBusParams(handleWrite)");
                    Canlib.canStatus statusSetParam1 = Canlib.canSetBusParamsC200(handleWrite, CAN_BAUD_BTR_47K_btr0, CAN_BAUD_BTR_47K_btr1);
                    logger.Debug("canlibCLSNET.Canlib.canBusOn(handleWrite)");
                    Canlib.canStatus statusOn1 = Canlib.canBusOn(handleWrite);
                    Canlib.canIoCtl(handleWrite, Canlib.canIOCTL_SET_LOCAL_TXECHO, 0);
                    //
                    logger.Debug("handle2 = canlibCLSNET.Canlib.canOpenChannel()");
                    handleRead = Canlib.canOpenChannel(ChannelNumber, Canlib.canOPEN_ACCEPT_VIRTUAL);
                    logger.Debug("canlibCLSNET.Canlib.canSetBusParams(handleRead)");
                    Canlib.canStatus statusSetParam2 = Canlib.canSetBusParamsC200(handleWrite, CAN_BAUD_BTR_47K_btr0, CAN_BAUD_BTR_47K_btr1);
                    logger.Debug("canlibCLSNET.Canlib.canBusOn(handleRead)");
                    Canlib.canStatus statusOn2 = Canlib.canBusOn(handleRead);
                    Canlib.canIoCtl(handleRead, Canlib.canIOCTL_SET_LOCAL_TXECHO, 0);
                }
                else if (TrionicECU == ECU.TRIONIC8)
                {
                    logger.Debug("handle1 = canlibCLSNET.Canlib.canOpenChannel()");
                    handleWrite = Canlib.canOpenChannel(ChannelNumber, Canlib.canOPEN_ACCEPT_VIRTUAL);
                    logger.Debug("canlibCLSNET.Canlib.canSetBusParams(handleWrite)");
                    Canlib.canStatus statusSetParam1 = Canlib.canSetBusParamsC200(handleWrite, CAN_BAUD_BTR_33K_btr0, CAN_BAUD_BTR_33K_btr1);
                    logger.Debug("canlibCLSNET.Canlib.canBusOn(handleWrite)");
                    Canlib.canStatus statusOn1 = Canlib.canBusOn(handleWrite);
                    Canlib.canIoCtl(handleWrite, Canlib.canIOCTL_SET_LOCAL_TXECHO, 0);
                    //
                    logger.Debug("handle2 = canlibCLSNET.Canlib.canOpenChannel()");
                    handleRead = Canlib.canOpenChannel(ChannelNumber, Canlib.canOPEN_ACCEPT_VIRTUAL);
                    logger.Debug("canlibCLSNET.Canlib.canSetBusParams(handleRead)");
                    Canlib.canStatus statusSetParam2 = Canlib.canSetBusParamsC200(handleWrite, CAN_BAUD_BTR_33K_btr0, CAN_BAUD_BTR_33K_btr1);
                    logger.Debug("canlibCLSNET.Canlib.canBusOn(handleRead)");
                    Canlib.canStatus statusOn2 = Canlib.canBusOn(handleRead);
                    Canlib.canIoCtl(handleRead, Canlib.canIOCTL_SET_LOCAL_TXECHO, 0);
                }

                if (handleWrite < 0 || handleRead < 0)
                {
                    return(OpenResult.OpenError);
                }

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

            m_endThread = false;

            //Check if P bus is connected
            logger.Debug("handle1 = canlibCLSNET.Canlib.canOpenChannel()");
            handleWrite = Canlib.canOpenChannel(ChannelNumber, Canlib.canOPEN_ACCEPT_VIRTUAL);
            logger.Debug("canlibCLSNET.Canlib.canSetBusParams(handleWrite)");
            Canlib.canStatus statusSetParamWrite = Canlib.canSetBusParams(handleWrite, Canlib.canBITRATE_500K, 0, 0, 0, 0, 0);
            logger.Debug("canlibCLSNET.Canlib.canBusOn(handleWrite)");
            Canlib.canStatus statusOnWrite = Canlib.canBusOn(handleWrite);
            Canlib.canIoCtl(handleWrite, Canlib.canIOCTL_SET_LOCAL_TXECHO, 0);
            //
            logger.Debug("handle2 = canlibCLSNET.Canlib.canOpenChannel()");
            handleRead = Canlib.canOpenChannel(ChannelNumber, Canlib.canOPEN_ACCEPT_VIRTUAL);
            logger.Debug("canlibCLSNET.Canlib.canSetBusParams(handleRead)");
            Canlib.canStatus statusSetParamRead = Canlib.canSetBusParams(handleRead, Canlib.canBITRATE_500K, 0, 0, 0, 0, 0);
            logger.Debug("canlibCLSNET.Canlib.canBusOn(handleRead)");
            Canlib.canStatus statusOnRead = Canlib.canBusOn(handleRead);
            Canlib.canIoCtl(handleRead, Canlib.canIOCTL_SET_LOCAL_TXECHO, 0);

            if (handleWrite < 0 || handleRead < 0)
            {
                return(OpenResult.OpenError);
            }

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