Saturday, January 15, 2011

Automatically discover the com port for smslib

One of the challenging task in smslib is to detect the gsm device has been attached to which usb port as the port name is required during the smslib server initialization.

The manual way to find out the port is "Device Manager" panel of your Windows OS, and double click the item under "Modems" category, the com port name can be found in the "Modem" tab of the popup properties page.

The automatic way must allows the user to determine which port as there might be more than one gsm devices attached. therefore the function should return a set of possible candidate port names. this can be done by downloading the Wmi package from http://www.codeproject.com/KB/cs/EverythingInWmi02.aspx which can be used to discover hardware settings in your machine. The following are the C# code that uses Wmi and SerialPort interface from C# to automatically discover the com port for smslib in C#:


            using System.IO.Ports;
            using baileysoft.Wmi;

            string[] port_names = SerialPort.GetPortNames();
            List<string> possible_ports = new List<string>();

            Connection.ApplicationPath = Application.StartupPath;
            Connection wmiConnection = new Connection();
          
            Win32_POTSModem x = new Win32_POTSModem(wmiConnection);

            foreach (string property in x.GetPropertyValues())
            {
                int split_index = property.IndexOf(": ");
                string property_name = property.Substring(0, split_index);
                string property_value = property.Substring(split_index+2);
                if (property_name == "AttachedTo")
                {
                    foreach (string port_name in port_names)
                    {
                        if (port_name == property_value)
                        {
                            possible_ports.Add(property_value);
                            break;
                        }
                    }
            }

In the above code, the possible ports returns the list of possible ports that might have the gsm devices attached.

No comments:

Post a Comment