Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find gsm modem port in c#

Tags:

c#

port

I want to loop through the available ports: System.IO.Ports.SerialPort.GetPortNames() to find if a port is used by a gsm modem. Any idea please.

like image 857
Dohamsg Avatar asked Aug 21 '11 14:08

Dohamsg


1 Answers

What I did in my application for one similar task:

  1. To check that a modem is connected to particular port you can send AT command into this port. This function below returns true if we found a modem on the current COM port:

    private bool CheckExistingModemOnComPort(SerialPort serialPort)
    {
        if ((serialPort == null) || !serialPort.IsOpen)
            return false;
    
        // Commands for modem checking
        string[] modemCommands = new string[] { "AT",       // Check connected modem. After 'AT' command some modems autobaud their speed.
                                                "ATQ0" };   // Switch on confirmations
        serialPort.DtrEnable = true;    // Set Data Terminal Ready (DTR) signal 
        serialPort.RtsEnable = true;    // Set Request to Send (RTS) signal
    
        string answer = "";
        bool retOk = false;
        for (int rtsInd = 0; rtsInd < 2; rtsInd++)
        {
            foreach (string command in modemCommands)
            {
                serialPort.Write(command + serialPort.NewLine);
                retOk = false;
                answer = "";
                int timeout = (command == "AT") ? 10 : 20;
    
                // Waiting for response 1-2 sec
                for (int i = 0; i < timeout; i++)
                {
                    Thread.Sleep(100);
                    answer += serialPort.ReadExisting();
                    if (answer.IndexOf("OK") >= 0)
                    {
                        retOk = true;
                        break;
                    }
                }
            }
            // If got responses, we found a modem
            if (retOk)
                return true;
    
            // Trying to execute the commands without RTS
            serialPort.RtsEnable = false;
        }
        return false;
    }
    
  2. On the next stage we can collect some data from the modem. I used the following commands:

    • ATQ0 - switch on confirmations (receive OK on each request)
    • ATE0 - switch on echo
    • ATI - get modem details
    • ATI3 - get extended modem details (not all modems supports this command)
like image 160
Alex Klaus Avatar answered Nov 09 '22 05:11

Alex Klaus