// ***********************
        // Filter List
        //************************

        // Returns a string array of the Cars
        public static string[] ReturnCarTypes()
        {
            // The variable length List for returning the string array
            List <string> cartypes = new List <string>();

            try
            {
                XDocument doc = XDocument.Load(ConfigFiles.Settings1.Default.filterURI);

                // Searches for the elements named CarName
                var cars = doc.Descendants("CarName");

                foreach (var car in cars)
                {
                    cartypes.Add(car.Value);
                }

                string[] array = cartypes.ToArray();
                return(array);
            }
            //catch (FileNotFoundException)
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Filter", "URI filename not found");
                return(null);
            }
        }
Beispiel #2
0
        } // End KvaserCanRateReturn

        // ***************************************
        // DetectCanInterfaces
        // Pulls all of the available adapters for the CAN bus
        // ***************************************
        public static void DetectCanInterfaces()
        {
            // Detect Process for Kvaser CAN devices
            try
            {
                int    nrOfChannels;
                object o = new object();

                Canlib.canInitializeLibrary();

                //List available channels
                Canlib.canGetNumberOfChannels(out nrOfChannels);

                for (int i = 0; i < nrOfChannels; i++)
                {
                    Canlib.canGetChannelData(i, Canlib.canCHANNELDATA_CHANNEL_NAME, out o);
                    //  Display of data in ListView as follows
                    // Network; Type; Mfg; Channel; Status; canHandle
                    BusInterface.AddInterface("CAN;" + o.ToString() + ";" + "Kvaser" + ";" + i, -1);
                    ErrorLog.NewLogEntry("CAN", "Detect CAN: " + o.ToString());
                }
            }
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Adapter", "Kvaser library not found");
            }
        } // End DetectCanInterfaces
        // CAN return rate
        public static string CanRateReturn(string canInterface)
        {
            try
            {
                string   hardwareString0  = canInterface.Replace(" ", "");
                string[] msgOutput        = hardwareString0.Split(';');
                ECOMLibrary.DeviceInfo di = new ECOMLibrary.DeviceInfo();

                // ECom can return
                // NOTE: ECom API does not have a bus parameter call
                if (msgOutput[2] == "ECom")
                {
                    // Finds the open ECom Adapters
                    UInt32 deviceSearch = ECOMLibrary.StartDeviceSearch(ECOMLibrary.FIND_OPEN);

                    while (deviceSearch != 0 && ECOMLibrary.FindNextDevice(deviceSearch, ref di) == ECOMLibrary.ECI_NO_ERROR)
                    {
                        if (di.CANOpen != 0)
                        {
                            return(Convert.ToString(di.SerialNumber));
                        }
                    }
                    ECOMLibrary.CloseDeviceSearch(deviceSearch);
                }

                return(null);
            }
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Adapter", "ECom library not found");
                return(null);
            }
        } // End GenericCanRateReturn
        public static void RenameVehicle(string cartype, string carname)
        {
            try{
                // Loads the XML file
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(ConfigFiles.Settings1.Default.filterURI);

                // Searches for the node with the CarName and then deletes the parent node
                //var matchingElement = (from s in xmlDoc.Elements("Cars")
                //                       where CarType.Element("CarName").Value == cartype
                //                       select s).FirstOrDefault();
                XmlNode node = xmlDoc.SelectSingleNode(String.Format("/Cars/CarType[CarName = '{0}']", cartype));
                //node.ParentNode.ReplaceChild(
                node["CarName"].InnerText = carname;
                //InnerText = cartype;
                //node.ParentNode.RemoveChild(node);
                // xmlDoc.Element("Cars").Add(new XElement("CarType", new XElement("CarName", cartype)));

                // Saves the XML file
                xmlDoc.Save(ConfigFiles.Settings1.Default.filterURI);
            }

            //catch (FileNotFoundException)
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Filter", "URI filename not found");
            }
        }
        // Searches for the message of the cartype
        public static string ReturnMsg(string cartype, string stringmsg)
        {
            try
            {
                XElement carElement = XElement.Load(ConfigFiles.Settings1.Default.filterURI);

                // Error Checking -- very clunky; needs revisions
                if (carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(cartype)).FirstOrDefault() == null)
                {
                    return("??");
                }
                var cartypeElement = carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(cartype)).FirstOrDefault();

                if (cartypeElement.Elements("MSG").Where(e3 => e3.Element("Message").Value.Equals(stringmsg)).FirstOrDefault() == null)
                {
                    return("??");
                }
                var msgElement = cartypeElement.Elements("MSG").Where(e3 => e3.Element("Message").Value.Equals(stringmsg)).FirstOrDefault();

                if (msgElement.Element("Name").Value == null)
                {
                    return("??");
                }

                var nameElement = msgElement.Element("Name").Value;
                return(nameElement.ToString());
            }
            //catch (FileNotFoundException)
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Filter", "URI filename not found");
                return(null);
            }
        }
Beispiel #6
0
        } // End GenericCanRateReturn

        // ***************************************
        // DetectCanInterfaces
        // Pulls all of the available adapters for the CAN bus
        // ***************************************
        public static void DetectCanInterfaces()
        {
            try
            {
                KvaserCanBus.DetectCanInterfaces();
            }
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Adapter", "Kvaser library not found");
            }

            try
            {
                IntrepidCanBus.DetectCanInterfaces();
            }
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Adapter", "Intrepid library not found");
            }

            try
            {
                ECOMCanBus.DetectCanInterfaces();
            }
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Adapter", "ECom library not found");
            }
        } // End DetectCanInterfaces
        } // End GenericCanInitilize

        // ***************************************
        // DetectCanInterfaces
        // Pulls all of the available adapters for the CAN bus
        // ***************************************
        public static void DetectCanInterfaces()
        {
            // Detect Process for Intrepid devices
            try
            {
                int iResult;
                neoCSNet2003.NeoDevice ndNeoToOpen = new neoCSNet2003.NeoDevice(); //Struct holding detected hardware information
                int    iNumberOfDevices;                                           //Number of hardware devices to look for
                string neoDevice;

                //Set the number of devices to find
                iNumberOfDevices = 1;

                // Revision needed to search for multiple devices
                //Search for connected hardware
                iResult = neoCSNet2003.icsNeoDll.icsneoFindNeoDevices(65535, ref ndNeoToOpen, ref iNumberOfDevices);

                // Obtain the name of the Interpid device -- Device names from Intrepid Sample code
                switch (ndNeoToOpen.DeviceType)
                {
                case 1:
                    neoDevice = "neoVI Blue SN " + Convert.ToString(ndNeoToOpen.SerialNumber);
                    break;

                case 4:
                    neoDevice = "Value CAN 2 SN " + Convert.ToString(ndNeoToOpen.SerialNumber);
                    break;

                case 8:
                    neoDevice = "neoVI FIRE SN " + Convert.ToString(ndNeoToOpen.SerialNumber);
                    break;

                case 16:
                    neoDevice = "ValueCAN 3 SN " + Convert.ToString(ndNeoToOpen.SerialNumber);
                    break;

                default:
                    neoDevice = "Unknown neoVI SN " + Convert.ToString(ndNeoToOpen.SerialNumber);
                    break;
                }

                if (iNumberOfDevices < 1 || iResult == 0)
                {
                    ErrorLog.NewLogEntry("CAN", "Detect CAN: No Intrepid devices detected ");
                }
                else
                {
                    BusInterface.AddInterface("CAN;" + neoDevice + ";" + "Intrepid" + ";" + 0, -1);
                    ErrorLog.NewLogEntry("CAN", "Detect CAN: " + neoDevice);
                }
            }
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Adapter", "Intrepid library not found");
            }
        } // End DetectCanInterfaces
        // **********************
        // Turns canInterface off
        // **********************
        public static void CanBusOff(string canInterface)
        {
            string hardwareString0 = canInterface.Replace(" ", "");

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

            // Need Error Checking to ensure that device closes
            ECOMLibrary.CloseDevice((UInt32)BusInterface.ReturnHandle(canInterface));
            ErrorLog.NewLogEntry("CAN", "Bus Off Success/Failed: " + msgOutput[1]);
        }
        } // 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(';');

            Byte   ReturnError = 0; //This will be used for all error return status codes
            UInt32 EcomHandle;      //This will be the HANDLE to our ECOM device used for all function calls
            byte   EComCANBitrate = ECOMLibrary.CAN_BAUD_500K;

            ECOMLibrary.DeviceInfo di = new ECOMLibrary.DeviceInfo();

            // Assigns settings for the adapter
            if (bitRateSetting == "1M")
            {
                EComCANBitrate = ECOMLibrary.CAN_BAUD_1MB;
            }
            else if (bitRateSetting == "500K")
            {
                EComCANBitrate = ECOMLibrary.CAN_BAUD_500K;
            }
            else if (bitRateSetting == "250K")
            {
                EComCANBitrate = ECOMLibrary.CAN_BAUD_250K;
            }
            else if (bitRateSetting == "125K")
            {
                EComCANBitrate = ECOMLibrary.CAN_BAUD_125K;
            }
            else if (bitRateSetting == "100K" || msgOutput[4] == "62K" || msgOutput[4] == "50K" || msgOutput[4] == "33K")
            {
                MainWindow.ErrorDisplayString("ECom Adapter does not support low speed CAN (100K, 62K, 50K, 33K)");
                return(-1);
            }

            EcomHandle = ECOMLibrary.CANOpen(Convert.ToUInt32(msgOutput[3]), EComCANBitrate, ref ReturnError);
            //MainWindow.ErrorDisplayString("ECom Handle: " + Convert.ToString(EcomHandle));
            BusInterface.AddHandle(canInterface, (int)EcomHandle);

            if (EcomHandle == 0 || ReturnError != 0)
            {
                StringBuilder ErrMsg = new StringBuilder(400);
                ECOMLibrary.GetFriendlyErrorMessage(ReturnError, ErrMsg, 400);
                MainWindow.ErrorDisplayString("CANOpen failed with error message: " + ErrMsg);
                return(-1);
            }

            ECOMLibrary.GetDeviceInfo(EcomHandle, ref di);
            ErrorLog.NewLogEntry("CAN", "Bus On: " + di.SerialNumber);
            return(1);
        }
        public static string[] ReturnPackets(string carname)
        {
            try
            {
                XElement      carElement = XElement.Load(ConfigFiles.Settings1.Default.filterURI);
                List <string> packets    = new List <string>();

                // Error Checking -- very clunky; revisions needed
                if (carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(carname, StringComparison.OrdinalIgnoreCase)).FirstOrDefault() == null)
                {
                    return(null);
                }

                var cartypeElement = carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(carname, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();


                // For the Packet Types
                //var cars = cartypeElement.Descendants("Packet");
                var cars = cartypeElement.Elements("Packet");
                foreach (var car in cars)
                {
                    packets.Add((string)car.Element("Name") + "; Packet");
                }

                // For the Sequence Types
                cars = cartypeElement.Elements("Sequence");
                foreach (var car in cars)
                {
                    packets.Add((string)car.Element("Name") + "; Sequence");
                }

                // For the IF THEN Types
                cars = cartypeElement.Elements("IFTHEN");
                foreach (var car in cars)
                {
                    packets.Add((string)car.Element("Name") + "; If Then");
                }

                return(packets.ToArray());
            }

            //catch (FileNotFoundException)
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Filter", "URI filename not found");
                return(null);
            }
        }
        // Returns Data for the selected packet from the xml file
        public static string ReturnPacketDataSequence(int count, string cartype, string packetname)
        {
            // return string --> 0=id; 1=dlc; 2=flag; 3=message
            try
            {
                XElement      carElement = XElement.Load(ConfigFiles.Settings1.Default.filterURI);
                List <string> packets    = new List <string>();

                // Error Checking -- very clunky; needs revisions
                if (carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(cartype)).FirstOrDefault() == null)
                {
                    return("??");
                }
                var cartypeElement = carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(cartype)).FirstOrDefault();

                //  MainWindow.ErrorDisplayString("Level One:" + cartypeElement.ToString());

                // Error Checking -- very clunky; needs revisions
                if (cartypeElement.Elements("Sequence").Where(e3 => e3.Element("Name").Value.Equals(packetname, StringComparison.OrdinalIgnoreCase)).FirstOrDefault() != null)
                {
                    var sequencetypeElements = cartypeElement.Elements("Sequence").Where(e3 => e3.Element("Name").Value.Equals(packetname, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

                    // MainWindow.ErrorDisplayString("Level Two:" + sequencetypeElements.ToString());

                    // Error Checking -- very clunky; needs revisions
                    if (sequencetypeElements.Elements("Packet").Where(e3 => e3.Element("Number").Value.Equals(Convert.ToString(count), StringComparison.OrdinalIgnoreCase)).FirstOrDefault() != null)
                    {
                        var car = sequencetypeElements.Elements("Packet").Where(e3 => e3.Element("Number").Value.Equals(Convert.ToString(count), StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

                        // MainWindow.ErrorDisplayString("Level Three:" + car.ToString());

                        return((string)car.Element("ID") + ";"
                               + (string)car.Element("DLC") + ";"
                               + (string)car.Element("Flag") + ";"
                               + (string)car.Element("Message"));
                    }
                }

                return("??");
            }

            //catch (FileNotFoundException)
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Filter", "URI filename not found");
                return(null);
            }
        }
        // Searches for the ID of the carType
        public static string ReturnID(string cartype, int id)
        {
            // Puts the id into a hex format for comparison to the XML file
            string stringid = String.Format("{0:X}", id);

            try
            {
                XElement carElement = XElement.Load(ConfigFiles.Settings1.Default.filterURI);

                // Error Checking -- very clunky; revisions needed; returns ?? if the CarName does not exist
                if (carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(cartype)).FirstOrDefault() == null)
                {
                    return("??");
                }
                var cartypeElement = carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(cartype)).FirstOrDefault();


                //if (cartypeElement.Elements("ECU").Where(e3 => e3.Element("ID").Value.Contains("?")) != null)
                //     || e3.Element("ID").Value.Contains("*") || e3.Element("ID").Value.Contains("[")) != null)
                //    return "wildcard";


                if (cartypeElement.Elements("ECU").Where(e3 => e3.Element("ID").Value.Equals(stringid)).FirstOrDefault() == null)
                {
                    return("??");
                }
                var ecuElement = cartypeElement.Elements("ECU").Where(e3 => e3.Element("ID").Value.Equals(stringid)).FirstOrDefault();

                if (ecuElement.Element("Name").Value == null)
                {
                    return("??");
                }
                var nameElement = ecuElement.Element("Name").Value;

                return(nameElement.ToString());
            }
            //catch (FileNotFoundException)
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Filter", "URI filename not found");
                return(null);
            }
        }
        // Returns Data for the selected packet from the xml file
        public static string ReturnPacketDataDisplay(string cartype, string packetname)
        {
            try
            {
                XElement      carElement = XElement.Load(ConfigFiles.Settings1.Default.filterURI);
                List <string> packets    = new List <string>();

                // Error Checking -- very clunky; needs revisions
                if (carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(cartype)).FirstOrDefault() == null)
                {
                    return("??");
                }
                var cartypeElement = carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(cartype)).FirstOrDefault();


                // Error Checking -- very clunky; needs revisions
                if (cartypeElement.Elements("Packet").Where(e3 => e3.Element("Name").Value.Equals(packetname, StringComparison.OrdinalIgnoreCase)).FirstOrDefault() != null)
                {
                    return(cartypeElement.Elements("Packet").Where(e3 => e3.Element("Name").Value.Equals(packetname, StringComparison.OrdinalIgnoreCase)).FirstOrDefault().ToString());
                }
                // Looping through the types; Needs revisions to pull all elements
                else if (cartypeElement.Elements("Sequence").Where(e3 => e3.Element("Name").Value.Equals(packetname, StringComparison.OrdinalIgnoreCase)).FirstOrDefault() != null)
                {
                    return(cartypeElement.Elements("Sequence").Where(e3 => e3.Element("Name").Value.Equals(packetname, StringComparison.OrdinalIgnoreCase)).FirstOrDefault().ToString());
                }
                else if (cartypeElement.Elements("IFTHEN").Where(e3 => e3.Element("Name").Value.Equals(packetname, StringComparison.OrdinalIgnoreCase)).FirstOrDefault() != null)
                {
                    return(cartypeElement.Elements("IFTHEN").Where(e3 => e3.Element("Name").Value.Equals(packetname, StringComparison.OrdinalIgnoreCase)).FirstOrDefault().ToString());
                }
                else
                {
                    return("??");
                }
            }

            //catch (FileNotFoundException)
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Filter", "URI filename not found");
                return("??");
            }
        }
        // Returns Data for the selected packet from the xml file
        public static string ReturnPacketDataTransmit(string cartype, string packetname)
        {
            // return string --> 0=id; 1=dlc; 2=flag; 3=message
            try
            {
                XElement      carElement = XElement.Load(ConfigFiles.Settings1.Default.filterURI);
                List <string> packets    = new List <string>();

                // Error Checking -- very clunky; needs revisions
                if (carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(cartype)).FirstOrDefault() == null)
                {
                    return("??");
                }
                var cartypeElement = carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(cartype)).FirstOrDefault();


                // Error Checking -- very clunky; needs revisions
                if (cartypeElement.Elements("Packet").Where(e3 => e3.Element("Name").Value.Equals(packetname, StringComparison.OrdinalIgnoreCase)).FirstOrDefault() != null)
                {
                    var car = cartypeElement.Elements("Packet").Where(e3 => e3.Element("Name").Value.Equals(packetname, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

                    //return (string)car.Element("Name") + ";"
                    return((string)car.Element("ID") + ";"
                           + (string)car.Element("DLC") + ";"
                           + (string)car.Element("Flag") + ";"
                           + (string)car.Element("Message") + ";"
                           + (string)car.Element("Count") + ";"
                           + (string)car.Element("TimeBetween"));
                }
                else
                {
                    return("??");
                }
            }

            //catch (FileNotFoundException)
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Filter", "URI filename not found");
                return(null);
            }
        }
        /*
         * // Searches for the if then packet of the cartype
         * public static void CheckIfThen(string cartype, int id, string stringmsg)
         * {
         *  string stringid = String.Format("{0:X}", id);
         *
         *  try
         *  {
         *      XElement carElement = XElement.Load(ConfigFiles.Settings1.Default.filterURI);
         *
         *      // Error Checking -- very clunky; needs revisions
         *      if (carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(cartype)).FirstOrDefault() == null)
         *          return;
         *      var cartypeElement = carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(cartype)).FirstOrDefault();
         *
         *      var cars = cartypeElement.Elements("IFTHEN");
         *      foreach (var car in cars)
         *      {
         *          if (car.Elements("Packet").Where(e3 => e3.Element("Message").Value.Equals(stringmsg, StringComparison.OrdinalIgnoreCase)
         * && e3.Element("ID").Value.Equals(stringid, StringComparison.OrdinalIgnoreCase)).FirstOrDefault() != null)
         *          {
         *              var msgElement = car.Elements("Packet").Where(e3 => e3.Element("Message").Value.Equals(stringmsg, StringComparison.OrdinalIgnoreCase)
         *                  && e3.Element("ID").Value.Equals(stringid, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
         *          }
         *      }
         *
         *
         *      if (cartypeElement.Elements("IFTHEN").Where(e3 => e3.Element("Name").Value.Equals(packetname, StringComparison.OrdinalIgnoreCase)).FirstOrDefault() != null)
         *          return cartypeElement.Elements("IFTHEN").Where(e3 => e3.Element("Name").Value.Equals(packetname, StringComparison.OrdinalIgnoreCase)).FirstOrDefault().ToString();
         *
         *      if (cartypeElement.Elements("Packet").Where(e3 => e3.Element("Message").Value.Equals(stringmsg, StringComparison.OrdinalIgnoreCase)
         *          && e3.Element("ID").Value.Equals(stringid, StringComparison.OrdinalIgnoreCase)).FirstOrDefault() == null)
         *          return;
         *      var msgElement = cartypeElement.Elements("Packet").Where(e3 => e3.Element("Message").Value.Equals(stringmsg, StringComparison.OrdinalIgnoreCase)
         *      && e3.Element("ID").Value.Equals(stringid, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
         *
         *      if (msgElement.Element("Name").Value == null)
         *          return;
         *      var nameElement = msgElement.Element("Name").Value;
         *
         *
         *      return;
         *  }
         *  //catch (FileNotFoundException)
         *  catch (Exception)
         *  {
         *      ErrorLog.NewLogEntry("Filter", "URI filename not found");
         *      return;
         *  }
         * }
         *
         */

        // Adds a Cartype to the XML
        public static void AddVehicle(string cartype)
        {
            try
            {
                // Loads the XML file
                XDocument xmlDoc = XDocument.Load(ConfigFiles.Settings1.Default.filterURI);

                // Adds the new cartype to the loaded XML
                xmlDoc.Element("Cars").Add(new XElement("CarType", new XElement("CarName", cartype)));

                // Saves the XML file
                xmlDoc.Save(ConfigFiles.Settings1.Default.filterURI);
            }

            //catch (FileNotFoundException)
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Filter", "URI filename not found");
            }
        }
        // **********************
        // Turns canInterface off
        // **********************
        public static void CanBusOff(string canInterface)
        {
            string hardwareString0 = canInterface.Replace(" ", "");

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

            int iResult;
            int iNumberOfErrors = 0;

            iResult = neoCSNet2003.icsNeoDll.icsneoClosePort(BusInterface.ReturnHandle(canInterface), ref iNumberOfErrors);

            if (iResult == 1)
            {
                ErrorLog.NewLogEntry("CAN", "Bus Off Success: " + msgOutput[1]);
            }
            else
            {
                ErrorLog.NewLogEntry("CAN", "Bus Off Failed: " + msgOutput[1]);
            }
        }
        } // End GenericCanRateReturn

        // ***************************************
        // DetectCanInterfaces
        // Pulls all of the available adapters for the CAN bus
        // ***************************************
        public static void DetectCanInterfaces()
        {
            // Detect Process for ECom devices
            try
            {
                ECOMLibrary.DeviceInfo di = new ECOMLibrary.DeviceInfo();
                UInt32 deviceSearch       = ECOMLibrary.StartDeviceSearch(ECOMLibrary.FIND_ALL);

                while (deviceSearch != 0 && ECOMLibrary.FindNextDevice(deviceSearch, ref di) == ECOMLibrary.ECI_NO_ERROR)
                {
                    BusInterface.AddInterface("CAN;" + "CANCapture" + ";" + "ECom" + ";" + di.SerialNumber, -1);
                    ErrorLog.NewLogEntry("CAN", "Detect CAN: " + di.SerialNumber);
                }

                ECOMLibrary.CloseDeviceSearch(deviceSearch);
            }
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Adapter", "ECom library not found");
            }
        } // End DetectCanInterfaces
        // Searches for the packet of the cartype
        public static string ReturnPacketIdentifier(string cartype, int id, string stringmsg)
        {
            string stringid = String.Format("{0:X}", id);

            try
            {
                XElement carElement = XElement.Load(ConfigFiles.Settings1.Default.filterURI);

                // Error Checking -- very clunky; needs revisions
                if (carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(cartype)).FirstOrDefault() == null)
                {
                    return("??");
                }
                var cartypeElement = carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(cartype)).FirstOrDefault();


                if (cartypeElement.Elements("Packet").Where(e3 => e3.Element("Message").Value.Equals(stringmsg, StringComparison.OrdinalIgnoreCase) &&
                                                            e3.Element("ID").Value.Equals(stringid, StringComparison.OrdinalIgnoreCase)).FirstOrDefault() == null)
                {
                    return("??");
                }
                var msgElement = cartypeElement.Elements("Packet").Where(e3 => e3.Element("Message").Value.Equals(stringmsg, StringComparison.OrdinalIgnoreCase) &&
                                                                         e3.Element("ID").Value.Equals(stringid, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

                if (msgElement.Element("Name").Value == null)
                {
                    return("??");
                }
                var nameElement = msgElement.Element("Name").Value;

                return(nameElement.ToString());
            }
            //catch (FileNotFoundException)
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Filter", "URI filename not found");
                return(null);
            }
        }
        // Deletes a Cartype to the XML
        public static void DeleteVehicle(string cartype)
        {
            try
            {
                // Loads the XML file
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(ConfigFiles.Settings1.Default.filterURI);

                // Searches for the node with the CarName and then deletes the parent node
                XmlNode node = xmlDoc.SelectSingleNode(String.Format("/Cars/CarType[CarName = '{0}']", cartype));
                node.ParentNode.RemoveChild(node);

                // Saves the XML file
                xmlDoc.Save(ConfigFiles.Settings1.Default.filterURI);
            }

            //catch (FileNotFoundException)
            catch (Exception)
            {
                ErrorLog.NewLogEntry("Filter", "URI filename not found");
            }
        }
Beispiel #20
0
        // **********************
        // Turns canInterface off
        // **********************
        public static void CanBusOff(string canInterface)
        {
            string hardwareString0 = canInterface.Replace(" ", "");

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

            Canlib.canStatus status;
            // MainWindow.ErrorDisplayString("Bus Off - BusInterface: " + canInterface + " ; Handle: " + BusInterface.ReturnHandle(canInterface));
            // Canlib.canClose(BusInterface.ReturnHandle(canInterface));
            // status = Canlib.canBusOff(BusInterface.ReturnHandle(canInterface));

            Canlib.canClose(Convert.ToInt32(msgOutput[3]));
            status = Canlib.canBusOff(Convert.ToInt32(msgOutput[3]));

            if (status < 0)
            {
                ErrorLog.NewLogEntry("CAN", "Bus Off Failed: " + msgOutput[1]);
            }
            else
            {
                ErrorLog.NewLogEntry("CAN", "Bus Off Success: " + msgOutput[1]);
            }
        }
Beispiel #21
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);
        }
        }  // End GenericCanTransmitMultiple

        // CAN Receive
        public static bool CanReceive(CanData can)
        {
            Byte ReturnError = 0;

            ECOMLibrary.SFFMessage RxMessage = new ECOMLibrary.SFFMessage();
            ECOMLibrary.EFFMessage ExMessage = new ECOMLibrary.EFFMessage();

            try
            {
                //ECOM library call to get a standard message
                ReturnError = ECOMLibrary.CANReceiveMessage((UInt32)BusInterface.ReturnHandle(can.hardware), ref RxMessage);
            }
            catch {
                ErrorLog.NewLogEntry("ECOM", Convert.ToString(ReturnError));
            }

            if (ReturnError == 0)
            {
                // Converts the ID low and ID high
                can.id   = Convert.ToInt32(RxMessage.IDL + RxMessage.IDH);
                can.dlc  = Convert.ToInt32(RxMessage.DataLength);
                can.time = Convert.ToInt64(RxMessage.TimeStamp);

                // Puts the individual bytes into the can.msg byte array
                if (can.dlc > 0)
                {
                    can.msg[0] = RxMessage.data1;
                }
                if (can.dlc > 1)
                {
                    can.msg[1] = RxMessage.data2;
                }
                if (can.dlc > 2)
                {
                    can.msg[2] = RxMessage.data3;
                }
                if (can.dlc > 3)
                {
                    can.msg[3] = RxMessage.data4;
                }
                if (can.dlc > 4)
                {
                    can.msg[4] = RxMessage.data5;
                }
                if (can.dlc > 5)
                {
                    can.msg[5] = RxMessage.data6;
                }
                if (can.dlc > 6)
                {
                    can.msg[6] = RxMessage.data7;
                }
                if (can.dlc > 7)
                {
                    can.msg[7] = RxMessage.data8;
                }

                // Revisions Needed -- Need to pull flag information
                can.flags = Convert.ToInt32(RxMessage.options);

                //MainWindow.ErrorDisplayString(Convert.ToString(can.flags));

                // For error testing
                // MainWindow.ErrorDisplayByteArray(can.msg);
                //MainWindow.ErrorDisplayString(Convert.ToString(can.dlc));
            }
            else
            {
                ReturnError = ECOMLibrary.CANReceiveMessageEx((UInt32)BusInterface.ReturnHandle(can.hardware), ref ExMessage);

                can.id   = Convert.ToInt32(ExMessage.ID);
                can.dlc  = Convert.ToInt32(ExMessage.DataLength);
                can.time = Convert.ToInt64(ExMessage.TimeStamp);

                // Puts the individual bytes into the can.msg byte array
                if (can.dlc > 0)
                {
                    can.msg[0] = ExMessage.data1;
                }
                if (can.dlc > 1)
                {
                    can.msg[1] = ExMessage.data2;
                }
                if (can.dlc > 2)
                {
                    can.msg[2] = ExMessage.data3;
                }
                if (can.dlc > 3)
                {
                    can.msg[3] = ExMessage.data4;
                }
                if (can.dlc > 4)
                {
                    can.msg[4] = ExMessage.data5;
                }
                if (can.dlc > 5)
                {
                    can.msg[5] = ExMessage.data6;
                }
                if (can.dlc > 6)
                {
                    can.msg[6] = ExMessage.data7;
                }
                if (can.dlc > 7)
                {
                    can.msg[7] = ExMessage.data8;
                }

                // Revisions Needed -- Need to pull flag information
                can.flags = Convert.ToInt32(ExMessage.options);

                // For error testing
                //  MainWindow.ErrorDisplayByteArray(can.msg);
            }

            if (ReturnError != 0)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        } // End Read
        // ***********************
        // Converts an input string into the message format for the CAN library
        // ***********************
        public static void ConvertStringtoCAN(CanData can, string msgInput)
        {
            // msgInput --> 0=id; 1=dlc; 2=flag; 3=message
            string[] output = msgInput.Split(';');

            if (output.Count() < 0)
            {
                ErrorLog.NewLogEntry("Convert Error:", msgInput);
                return;
            }

            // Needs input checking; revisions needed
            if (output[1] != "")
            {
                can.dlc = Convert.ToInt32(output[1]);
            }

            if (can.format == "hex")
            {
                // Converts the id to hex with the 16 (Chris please check I think it converts hex to int PNB)
                if (output[0] != "")
                {
                    can.id = Convert.ToInt32(output[0], 16);
                }

                // Need error checking to ensure that flag is an int
                if (!string.IsNullOrEmpty(output[2]))
                {
                    switch (output[2].ToLower())
                    {
                    case "x":
                        output[2] = "4";     //Extended Packet
                        break;

                    case "r":
                        output[2] = "1";      // Remote Packet
                        break;

                    case "e":
                        output[2] = "20";      // Error Packet
                        break;

                    default:
                        output[2] = "2";      // Standard Packet
                        break;
                    }

                    can.flags = Convert.ToInt32(output[2], 16);
                }

                if (output[3] != "")
                {
                    string msgString0 = output[3].Replace("-", "");
                    string msgString1 = msgString0.Replace(" ", "");
                    can.msg = HexStringToByteArray(msgString1);
                }
            }
            // if not hex assume decimal
            else
            {
                if (output[0] != "")
                {
                    can.id = Convert.ToInt32(output[0]);
                }
                if (output[2] != "")
                {
                    can.flags = Convert.ToInt32(output[2]);
                }

                if (output[3] != "")
                {
                    string   msgString0 = output[3].Replace("-", " ");
                    string[] msgString1 = msgString0.Split(' ');

                    // first part is blank
                    for (int i = 1; i < 9; i++)
                    {
                        if (i < can.dlc)
                        {
                            can.msg[i] = Convert.ToByte(msgString1[i]);
                        }
                    }
                }
            }
        }
        //****************************
        // Transmit Settings Tab
        // Written by Parnian Najafi Borazjani
        //****************************
        private void TransmitPacket_Click(object sender, EventArgs e)
        {
            CanData can             = new CanData();
            int     number_messages = 1;
            string  msgOutput       = "";
            string  flag;

            //if (Transmit_dlc.Value>8)
            //    MessageBox.Show("Messages can have a maximum of 8");
            // For the various flags
            // Need to implement an enumerated keyword to replace these numbers
            // These numbers are from the Kvaser library documentation and may not work on other CAN systems
            if (Flag_Ext.Checked == true)
            {
                flag = "X";                     // Extended
            }
            else if (Flag_Err.Checked == true)
            {
                flag = "E";                     // Error
            }
            else if (Flag_Rtr.Checked == true)
            {
                flag = "R";                     // Remote
            }
            else
            {
                flag = "S";                     // Standard
            }
            if (InputTests.IsStringNumeric(Transmit_NoMsg.Text) == true)
            {
                number_messages = Convert.ToInt32(Transmit_NoMsg.Text);
            }
            else
            {
                MessageBox.Show("Error: Number of Messages is not Numeric", "Error", MessageBoxButtons.OK);
            }

            msgOutput = Transmit_id.Text + ";" + Transmit_dlc.Text + ";" + flag + ";" + Transmit_msg0.Text + "-" + Transmit_msg1.Text + "-" + Transmit_msg2.Text + "-" + Transmit_msg3.Text + "-" + Transmit_msg4.Text + "-" + Transmit_msg5.Text + "-" + Transmit_msg6.Text + "-" + Transmit_msg7.Text;

            if (Transmit_Hex.Checked == true)
            {
                can.format = "hex";
            }
            else
            {
                can.format = "decimal";
            }

            CommonUtils.ConvertStringtoCAN(can, msgOutput);

            can.number  = number_messages;
            can.timeBtw = 0;
            try
            {
                can.hardware = TransmitInterfaceBox.SelectedItem.ToString();

                if (IncrementIdentifier.Checked == true)
                {
                    can.increment = true;
                }

                GenericCanBus.GenericCanTransmitMultiple(can);
                //bgTransmit.RunWorkerAsync(can);

                toolStripStatusLabel2.Text = CommonUtils.ErrorMsg("Transmit Message", can.status);
                ErrorLog.NewLogEntry("CAN", "Transmit Message: " + can.status);

                if (VerboseTransmit.Checked == true)
                {
                    MessageBox.Show(CommonUtils.DisplayMsg(can));
                }
            }
            catch
            {
                MessageBox.Show("No interface is turned on, please turn on the interfaces from \"Advanced Bus Control\" Window");
                this.Close();
                BusControl form = (BusControl)CommonUtils.GetOpenedForm <BusControl>();
                if (form == null)
                {
                    form = new BusControl();
                    form.Show();
                }
                else
                {
                    form.Select();
                }
            }
        }