Example #1
0
        //Reads message data from user input and writes a message to the channel
        private void sendButton_Click(object sender, RoutedEventArgs e)
        {
            int id = Convert.ToInt32(idBox.Text);

            TextBox[] textBoxes = { dataBox0, dataBox1, dataBox2, dataBox3, dataBox4,
                                    dataBox5, dataBox6, dataBox7 };
            byte[]    data = new byte[8];
            for (int i = 0; i < 8; i++)
            {
                data[i] = textBoxes[i].Text == "" ? (byte)0 : Convert.ToByte(textBoxes[i].Text);
            }

            CheckBox[] boxes = { RTRBox,   STDBox,  EXTBox,   WakeUpBox, NERRBox, errorBox,
                                 TXACKBox, TXRQBox, delayBox, BRSBox,    ESIBox };
            int        flags = 0;

            foreach (CheckBox box in boxes)
            {
                if (box.IsChecked.Value)
                {
                    flags += Convert.ToInt32(box.Tag);
                }
            }

            int dlc = Convert.ToInt32(DLCBox.Text);

            string msg = String.Format("{0}  {1}  {2:x2} {3:x2} {4:x2} {5:x2} {6:x2} {7:x2} {8:x2} {9:x2}   to handle {10}",
                                       id, dlc, data[0], data[1], data[2], data[3], data[4],
                                       data[5], data[6], data[7], handle);

            Canlib.canStatus status = Canlib.canWrite(handle, id, data, dlc, flags);
            CheckStatus("Writing message " + msg, status);
        }
//         private CAN_Common(){


//#if DEBUG
//             //Task.Factory.StartNew(

//             //   action: () =>{
//             //       Thread.Sleep(2000);
//             //       float f = 0;
//             //       Stopwatch sw = Stopwatch.StartNew();
//             //       Random rand = new Random();
//             //       FrequencyManager.SendCCComand(1, Globals.Vm_scis[0]);

//             //       while (true){
//             //           short sin = (short)((Math.Sin(f) * Math.Pow(2, 15)));
//             //           byte[] data = new byte[12];
//             //           Buffer.BlockCopy(Utils.makePacket("FT", 1, false, true, (Math.Sin(f) * 100).ToString()),0,data,0,8);
//             //           data[5] = (byte)(sin >> 8);
//             //           data[4] = (byte)sin;
//             //           data[6] = 0;
//             //           data[7] = 0;
//             //           innerTranmit(data);
//             //           //SaveToDisk.Write(data);
//             //           while (sw.ElapsedMilliseconds < f *5) ;
//             //           f+=0.01f;
//             //       }
//             //   });

//#endif

//        }
        //private CAN_Common(){
        //    //ActiveCANDriver = Tbl_CanDriver.ActiveCANDriver;
        //    Task.Factory.StartNew(
        //        action: () =>{
        //            ActiveCANDriver = Static_Utils.ActiveCANDriver;
        //            if (ActiveCANDriver.Equals(Consts.CAN_DRIVER_KVASER)){
        //                initForKvaser();
        //            } else if (ActiveCANDriver.Equals(Consts.CAN_DRIVER_GINKGO)){
        //                initForGinkgo();
        //            }
        //            initLoop();
        //        });
        //    //Active = true;

        //}


        #endregion

        #region METHODS

        public static void CloseConnection(int NodeId)
        {
            if (!Instance.dic_CanChanels.ContainsKey(NodeId))
            {
                return;
            }
            byte[] packet = Utils.makePacket(NodeId, "CC", 0, false, false, "0");
            for (int i = 0; i < 3; i++)
            {
                Canlib.canWrite(Instance.dic_CanChanels[NodeId], 0x37f, packet, packet.Length, 2);
                Write(packet);
                Thread.Sleep(50);
            }

            Canlib.canWrite(
                handle: Instance.dic_CanChanels[NodeId],
                id: 0,
                msg: new byte[] { 0x80, (byte)NodeId },
                dlc: 2,
                //size of msg
                flag: 2                 //we have defined this as const
                );

            Canlib.canBusOff(Instance.dic_CanChanels[NodeId]);
            Canlib.canClose(Instance.dic_CanChanels[NodeId]);
        }
        public static void CloseAllConnections()
        {
            new Thread(
                () => {
                lock (LockCanIdsDic) {
                    foreach (var entry in Instance.dic_CanChanels)
                    {
                        byte[] packet = Utils.makePacket(entry.Key, "CC", 0, false, false, "0");
                        for (int i = 0; i < 3; i++)
                        {
                            Canlib.canWrite(entry.Value, 0x37f, packet, packet.Length, 2);
                            Write(packet);
                            Thread.Sleep(50);
                        }

                        Canlib.canWrite(
                            handle: entry.Value,
                            id: 0,
                            msg: new byte[] { 0x80, (byte)entry.Key },
                            dlc: 2,
                            //size of msg
                            flag: 2     //we have defined this as const
                            );

                        Canlib.canBusOff(entry.Value);
                        Canlib.canClose(entry.Value);
                    }
                }
            }).Start();
        }
Example #4
0
        internal int FWwrite(byte[] buffer2, int id)
        {
            //int id = 888;
            Canlib.canStatus status;
            status = Canlib.canWrite(hcan, id, buffer2, 8, Canlib.canMSG_STD);
            if (status != Canlib.canStatus.canOK)
            {
                send2Terminal("mingi error sõnumi saatmisel");
            }

            //Get ACK response
            byte[] data = new byte[8];
            int    dlc;
            int    flags;
            long   time;

            while (id != 889)
            {
                Canlib.canReadWait(hcan, out id, data, out dlc, out flags, out time, 100);
            }

            if (data[0] == ACK)
            {
                return(ACK);
            }
            else
            {
                return(NACK);
            }
        }
Example #5
0
        /// <summary>
        /// CAN发送一帧数据
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dat"></param>
        /// <param name="dlc"></param>
        /// <param name="time"></param>
        /// <returns></returns>
        public bool WriteData(int id, byte[] dat, int dlc, out long time)
        {
            time = 0;
            Canlib.canStatus canStatus = Canlib.canWrite(canHandler, id, dat, dlc, 0);
            if (canStatus != Canlib.canStatus.canOK)
            {
                return(false);
            }
            int ttime = 0;

            Canlib.kvReadTimer(canHandler, out ttime);
            time = (long)ttime;
            return(true);
        }
Example #6
0
        public FuctionResult SendShortMsg(int id, byte[] data, int dlc)
        {
            if (data.Length != 8)
            {
                return(FuctionResult.ERROR_UNKNOWN);
            }
            string msg = String.Format("{0}  {1}  {2:x2} {3:x2} {4:x2} {5:x2} {6:x2} {7:x2} {8:x2} {9:x2}   to handle {10}",
                                       id, dlc, data[0], data[1], data[2], data[3], data[4],
                                       data[5], data[6], data[7], handle);

            Canlib.canStatus status = Canlib.canWrite(handle, id, data, dlc, flags);
            CheckStatus("Writing message " + msg, status);

            return(FuctionResult.OK);
        }
Example #7
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)
        {
            byte[] msg = a_message.getDataAsByteArray();

            writeStatus = Canlib.canWrite(handleWrite, (int)a_message.getID(), msg, a_message.getLength(), 0);

            if (writeStatus == Canlib.canStatus.canOK)
            {
                return(true);
            }
            else
            {
                logger.Debug(String.Format("tx failed with status {0}", writeStatus));
                return(false);
            }
        }
Example #8
0
        // Not being used since single transmission does not need threading at this time

        /*public void KvaserWrite(CanData can)
         * {
         * // Canlib.canWrite(can.handle, can.id, can.msg, can.dlc, can.flags);
         * // Canlib.canWriteSync(can.handle, 10000);
         * Canlib.canWriteWait(can.handle, can.id, can.msg, can.dlc, can.flags,1000);
         * }*/

        public void KvaserWriteMultiple(CanData can)
        {
            for (int x = 0; x < can.number; x++)
            {
                // MainWindow.ErrorDisplayString("can message: " + CommonUtils.DisplayMsg(can));
                can.status = Canlib.canWrite(can.handle, can.id, can.msg, can.dlc, can.flags);
                // MainWindow.ErrorDisplayString("can status: " + can.status);
                can.status1 = Canlib.canWriteSync(can.handle, 10000);
                //CheckFlags(can);
                System.Threading.Thread.Sleep(can.timeBtw);

                if (can.increment == true)
                {
                    can.id++;
                }
            }
        }
        //Reads message data from user input and writes a message to the channel, sending to the CAN bus.
        void sendMessageButton_Click(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(idBox.Text))
            {
                MessageBox.Show("Tx Failed: CAN message ID has not been specified.");
                return;
            }
            if (String.IsNullOrEmpty(DLCBox.Text))
            {
                MessageBox.Show("Tx Failed: DLC value has not been specified.");
                return;
            }

            string idStr_decimal = Utils.ConvertHexStrToDecStr(idBox.Text);
            int    id_decimal    = Convert.ToInt32(idStr_decimal);

            int dlc = Convert.ToInt32(DLCBox.Text);

            byte[] data = new byte[Defined.MAX_DLC];
            Array.Clear(data, 0, sizeof(byte) * Defined.MAX_DLC);
            for (int i = 0; i < dlc; i++)
            {
                data[i] = canDataBoxes[i].Text == "" ? (byte)0 : Convert.ToByte(canDataBoxes[i].Text);
            }

            int messageOptionFlags = 0;

            if (messageOptionCheckboxPanel.IsVisible)
            {
                foreach (CheckBox box in messageOptionCheckboxPanel.Children)
                {
                    if (box.IsChecked.Value)
                    {
                        messageOptionFlags += Convert.ToInt32(box.Tag);
                    }
                }
            }

            string msgLog = String.Format("0x{0:x3}  {1}  {2:x2} {3:x2} {4:x2} {5:x2} {6:x2} {7:x2} {8:x2} {9:x2}   to handle {10}",
                                          idBox.Text, DLCBox.Text, data[0], data[1], data[2], data[3], data[4],
                                          data[5], data[6], data[7], sendHandle);

            Canlib.canStatus status = Canlib.canWrite(sendHandle, id_decimal, data, dlc, messageOptionFlags);
            LogOutput("[Tx] " + msgLog);
            CheckStatus("[Tx] " + msgLog, status);
        }
Example #10
0
        //Reads message data from user input and writes a message to the channel
        private void sendMessage_Button_Click(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(idBox.Text, 16);

            TextBox[] textBoxes = { dataBox0, dataBox1, dataBox2, dataBox3, dataBox4,
                                    dataBox5, dataBox6, dataBox7 };
            byte[]    data = new byte[8];
            for (int i = 0; i < 8; i++)
            {
                data[i] = textBoxes[i].Text == "" ? (byte)0 : Convert.ToByte(textBoxes[i].Text);
            }

            int flags = Convert.ToInt32(flagsBox.Text);

            int dlc = Convert.ToInt32(DLCBox.Text);

            string msg = String.Format("{0}  {1}  {2:x2} {3:x2} {4:x2} {5:x2} {6:x2} {7:x2} {8:x2} {9:x2}   to handle {10}",
                                       idBox.Text, dlc, data[0], data[1], data[2], data[3], data[4],
                                       data[5], data[6], data[7], handle);

            Canlib.canStatus status = Canlib.canWrite(handle, id, data, dlc, flags);
            CheckStatus("Writing message " + msg, status);
        }
        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;
            }
        }
Example #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);
            }
        }
Example #13
0
        private bool CanShortMsgSend(int id, byte[] data, int datalength, int retrycount, double timeout, ref int EcuID, ref byte[] READDATA, ref string errmsg)
        {
            bool _LoopChk = true;
            bool _Result  = false;
            int  _dlc     = datalength;
            int  _flags   = this.flags;
            int  _channel = this.channel;
            long _time;
            int  _id      = id;
            int  _handle  = this.handle;
            bool _noError = true;

            Canlib.canStatus status;
            string           msg = "";

            byte[]    _ReadData         = new byte[8];
            Stopwatch _stopwatch        = new Stopwatch();
            bool      _OnlyOneReceiveOK = false;

            //Canlib.canBusOn(_handle);
            //status = Canlib.canWrite(_handle, _id, data, _dlc, _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;
             * }
             */
            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}\r",
                                          _id, _dlc, data[0], data[1], data[2], data[3], data[4],
                                          data[5], data[6], data[7], 0);

            CheckStatus("PC->ECU " + sndmsg, Canlib.canStatus.canOK);
            Canlib.canBusOn(_handle);
            status = Canlib.canWrite(_handle, _id, data, _dlc, _flags);
            _stopwatch.Reset();
            _stopwatch.Start();
            while (_LoopChk)
            {
                // TimeOut Check
                long   st            = _stopwatch.ElapsedMilliseconds;
                double _durationtime = st / 1000.0;  // ms -> sec
                if (_durationtime > timeout)
                {
                    // 설정시간안에 메세지 및 처리를 못했을 경우 종료
                    msg      = "timeout error";
                    _LoopChk = false;
                    break;
                }
                // Message Recieve Check
                status = Canlib.canReadWait(_handle, out _id, _ReadData, out _dlc, out _flags, out _time, 100); // 100ms timeout
                if (status == Canlib.canStatus.canOK)
                {
                    if ((_flags & Canlib.canMSG_ERROR_FRAME) == Canlib.canMSG_ERROR_FRAME)
                    {
                        msg = "***ERROR FRAME RECEIVED***";
                    }
                    else
                    {
                        msg = String.Format("ID={0:X4}  {1}  {2:X2} {3:X2} {4:X2} {5:X2} {6:X2} {7:X2} {8:X2} {9:X2}   {10}\r",
                                            _id, _dlc, _ReadData[0], _ReadData[1], _ReadData[2], _ReadData[3], _ReadData[4],
                                            _ReadData[5], _ReadData[6], _ReadData[7], _time);
                        if (_id == 0x07D9)
                        {
                            for (int i = 0; i < 8; i++)
                            {
                                READDATA[i] = _ReadData[i];
                            }
                            _Result           = true;
                            _OnlyOneReceiveOK = true;
                        }
                    }
                }
                else if (status != Canlib.canStatus.canERR_NOMSG)
                {
                    msg = "TimeOut:NO MSG";
                }
                if (_id == 0x7D9)
                {
                    CheckStatus("ECU->PC " + msg, status);
                    Canlib.canBusOff(_handle);
                    _LoopChk = false;
                }
                //onBus = false;
            }
            return(_Result);
        }
Example #14
0
        private bool CanSend_Frame(int id, byte[] data, int datalength, int ReceiveRetryCount, ref int EcuID, ref byte[] READDATA, ref int ReadDataCount, ref string ErrMsg)
        {
            // Real Data Count Only...
            int _handle = this.handle;
            int _flags  = this.flags;

            Canlib.canStatus status;

            byte[] SendData = new byte[8];
            byte[] TempData = new byte[8] {
                0x30, 0x00, 0x02, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA
            };                                                                                 // Flow Control Signal

            int RecvID = 0;

            byte[] RecvData       = new byte[8];
            byte[] RecvDataBuffer = new byte[50];
            int    RecvDataIndex  = 0;
            int    RecvDLC;
            int    RecvFlags;
            long   RecvTime;
            long   RecvSetTimeOut     = 50;
            int    _ReceiveRetryCount = 0;


            Canlib.canBusOn(_handle);
            bool SendAll   = false;
            int  DataIndex = 0;

            while (!SendAll)
            {
                for (int i = 0; i < 8; i++)
                {
                    if (DataIndex < datalength)
                    {
                        SendData[i] = data[DataIndex];
                    }
                    else
                    {
                        SendData[i] = 0x00;
                    }
                    DataIndex++;
                }
                // Data Send
                status = Canlib.canWrite(_handle, id, SendData, 8, _flags);
                CheckStatus("PC->ECU " + MsgConv(id, 8, SendData, 0), status);
                bool MsgReceive = false;
                while (!MsgReceive)
                {
                    status = Canlib.canReadWait(_handle, out RecvID, RecvData, out RecvDLC, out RecvFlags, out RecvTime, RecvSetTimeOut);
                    if ((status == Canlib.canStatus.canOK) && (!((_flags & Canlib.canMSG_ERROR_FRAME) == Canlib.canMSG_ERROR_FRAME)))
                    {
                        if (RecvID == 0x07D9)
                        {
                            CheckStatus("ECU->PC " + MsgConv(RecvID, 8, RecvData, 0), status);
                            if ((RecvData[0] & 0xF0) == 0x30)
                            {
                                for (int i = 0; i < 8; i++)
                                {
                                    RecvDataBuffer[RecvDataIndex] = RecvData[i]; RecvDataIndex++;
                                }
                                MsgReceive = true;
                                break;
                            }
                            if ((RecvData[0] & 0xF0) == 0x10)
                            { // FF Respons
                                status = Canlib.canWrite(_handle, id, TempData, 8, _flags);
                                for (int i = 0; i < 8; i++)
                                {
                                    RecvDataBuffer[RecvDataIndex] = RecvData[i]; RecvDataIndex++;
                                }
                            }
                            if ((RecvData[0] & 0xF0) == 0x20)
                            { // CF Respons
                                for (int i = 0; i < 8; i++)
                                {
                                    RecvDataBuffer[RecvDataIndex] = RecvData[i]; RecvDataIndex++;
                                }
                            }
                            if ((RecvData[0] & 0xF0) == 0x00)
                            { // Single Frame
                                MsgReceive = true;
                                break;
                            }
                        }
                    }
                    if (_ReceiveRetryCount > ReceiveRetryCount)
                    {
                        break;
                    }
                    _ReceiveRetryCount++;
                }
                if (DataIndex > datalength)
                {
                    SendAll = true;
                    break;
                }
            }
            Canlib.canBusOff(_handle);
            if (RecvDataIndex > 0)
            {
                EcuID         = RecvID;
                READDATA      = RecvDataBuffer;
                ReadDataCount = RecvDataIndex;
            }
            else
            {
                EcuID         = RecvID;
                READDATA      = RecvData;
                ReadDataCount = 8;
            }
            return(true);
        }
        private void initLoop()
        {
            //ActiveCanDriver = Static_Utils.ActiveCANDriver;
            //if (ActiveCanDriver==Common.Consts.CAN_DRIVER_KVASER) {
            //    if (runningKvaser) return;
            //    runningKvaser = true;
            int faultedPackage      = 0;
            int serialPortReadBytes = 0;

            Task.Factory.StartNew(
                action: () => {
                while (true)
                {
                    if (ActiveCanDriver == Common.Consts.CAN_DRIVER_KVASER)
                    {
                        if (hasChangeInNodesList)
                        {
                            lock (LockCanIdsDic) {
                                dic_Loop_CanChanels  = dic_CanChanels.ToDictionary(x => x.Key, x => x.Value);
                                hasChangeInNodesList = false;
                            }
                        }

                        if (_writePackage.Count != 0 && sw.ElapsedMilliseconds >= Globals.sleepForRefresh)
                        {
                            lock (SyncRoot) {
                                if (_writePackage[0] == null)
                                {
                                    Canlib.canFlushReceiveQueue(CANHandle);
                                }
                                else if /*_writepackage[0] reference a nodeid that does't exist*/ (
                                    !dic_Loop_CanChanels.ContainsKey(_writePackage[0].getInt(8)))
                                {
                                    if (faultedPackage > 5)
                                    {
                                        _writePackage.RemoveAt(0);
                                        faultedPackage = 0;
                                        continue;
                                    }
                                    else
                                    {
                                        faultedPackage++;
                                        Thread.Sleep(5);
                                        continue;
                                    }
                                }
                                else
                                {
                                    var pckt = _writePackage[0].Where((s, i) => i < 8).ToArray();
                                    Canlib.canWrite(
                                        handle: dic_Loop_CanChanels[_writePackage[0].getInt(8)],
                                        id: FrequencyManager.MAGIC_NUMBER,
                                        msg: pckt,
                                        dlc: 8,
                                        /*size of array*/
                                        flag: 2);
                                }
                                sw = Stopwatch.StartNew();
                                _writePackage.RemoveAt(0);
                            }
                        }

                        foreach (var nodeId_x_handle in dic_Loop_CanChanels)
                        {
                            byte[] msgReceive  = new byte[16];
                            int msgReceiveSize = 8;
                            int flag           = 2;

                            int _id   = 0;   //(idArr[0] << 8) + (idArr[1]);
                            long time = 100;
                            Canlib.canStatus err;
                            //err = Canlib.canRead(CANHandle, out _id, msgReceive, out msgReceiveSize, out flag, out time);
                            err = Canlib.canRead(
                                nodeId_x_handle.Value,
                                out _id,
                                msgReceive,
                                out msgReceiveSize,
                                out flag,
                                out time);
                            if (err != Canlib.canStatus.canOK)
                            {
                                if (_writePackage.Count == 0)
                                {
                                    Thread.Sleep(10);
                                }
                                continue;
                            }
                            /*let everyone know wich nodeId sent this message*/
                            msgReceive.putInt(12, nodeId_x_handle.Key);
                            innerTranmit(msgReceive);
                            //Debug.WriteLine(msgReceive.ToArray());
                        }
                    }
                    else if (ActiveCanDriver == Common.Consts.INTERFACE_RS232)
                    {
                        if (_writePackage.Count != 0 && sw.ElapsedMilliseconds >= Globals.sleepForRefresh)
                        {
                            lock (SyncRoot) {
                            }
                        }
                    }
                }
            });
            //} else if (ActiveCanDriver == Common.Consts.INTERFACE_RS232) { }
        }
Example #16
0
 public void send(int id, int dlc, byte[] data, int flags)
 {
     Canlib.canStatus status = Canlib.canWrite(chanHandle, id, data, dlc, flags);
 }
        public static void Transmitter(CAN_Channel.DataParameters data, int CAN_ID = 1)
        {
            switch (CAN_Channel._INTERFACEs[CAN_ID - 1])
            {
            case CAN_Channel.CAN_INTERFACE.KVASER:

                //write data to the can bus
                switch (data.Extended)
                {
                case true:

                    Canlib.canWrite(canHandle[CAN_ID - 1], Convert.ToInt32(data.Message_ID, 16),
                                    data.CAN_Message, 8, Canlib.canMSG_EXT);

                    break;

                case false:

                    Canlib.canWrite(canHandle[CAN_ID - 1], Convert.ToInt32(data.Message_ID, 16),
                                    data.CAN_Message, 8, 0);

                    break;
                }


                break;

            case CAN_Channel.CAN_INTERFACE.PEAK:


                switch (data.Extended)
                {
                case true:

                    pCANMsg.MSGTYPE = TPCANMessageType.PCAN_MESSAGE_EXTENDED;
                    goto default;

                case false:

                    pCANMsg.MSGTYPE = TPCANMessageType.PCAN_MESSAGE_STANDARD;
                    goto default;

                default:
                    pCANMsg.DATA = data.CAN_Message;
                    pCANMsg.ID   = Convert.ToUInt32(data.Message_ID, 16);
                    pCANMsg.LEN  = Convert.ToByte(data.Message_Length);

                    pCANStatus = PCANBasic.Write((ushort)canHandle[CAN_ID - 1], ref pCANMsg);

                    break;
                }

                //report any failure to the developer
                if (pCANStatus < 0)
                {
                    Console.WriteLine("Writing file failed,  can status: " + pCANStatus +
                                      "\nThe message time is: " + data.Message_Time +
                                      "\nThe message ID is: " + data.Message_ID);
                }

                break;
            }
        }
Example #18
0
 public static void GenericLinTransmit(CanData can)
 {
     can.status = Canlib.canWrite(can.handle, can.id, can.msg, can.dlc, can.flags);
 }