0

I'm trying to make an SMS Application using AT Command. What I want to know is that how can I get the port of GSM Modem instead of hard coding it?

Below is my sample of my code.

private void SendSMSTo(string cnum)
    {
        SerialPort _serialPort;

        _serialPort = new SerialPort("COM9", 115200);
        //instead of hard coding the port COM9 I want to get the port from GSM Modem

        Thread.Sleep(1000);

        _serialPort.Open();

        Thread.Sleep(1000);

        _serialPort.Write("AT+CMGF=1\r");

        Thread.Sleep(1000);

        _serialPort.Write("AT+CMGS=\"" + cnum + "\"\r\n");

        Thread.Sleep(1000);

        _serialPort.Write(computation() + "\x1A");

        Thread.Sleep(1000);

        _serialPort.Close();
    }
cuttyflam
  • 31
  • 1
  • 5
  • 1
    Possible duplicate of [C# check if a COM (Serial) port is already open](https://stackoverflow.com/questions/195483/c-sharp-check-if-a-com-serial-port-is-already-open) – l'L'l Mar 18 '19 at 07:29
  • What do you mean by `I want to get the port from GSM Modem`?, the `COM` port you use for comm is a PC side issue, and modem is not aware of – hessam hedieh Mar 18 '19 at 07:46
  • What I mean is, is there another possible way to find the GSM Modem COM port through code? Because I don't to hard code it. – cuttyflam Mar 18 '19 at 07:56
  • You should [**never use Thread.Sleep like that**](https://stackoverflow.com/a/46064206/23118). And you need to [wait properly](https://stackoverflow.com/a/15591673/23118) before sending the sms payload, – hlovdal Mar 19 '19 at 18:28

1 Answers1

0

I'm not a Windows guy, but I don't think your question is really tight to Windows.

As said by @Hessam, you cannot ask the modem to tell you the port it is connected to as you can't discuss with the modem because you don't know the port...

What I would try is to test all possible ports to detect the right one and only then send your SMS. For that, you may loop from COM1 up to COMXXX (I don't know the limit but put it big enough...) and try to send an AT command for which you know the reply. If you get the expected reply, you got the right port; if not, try the next one. If I remember well the AT command AT just replies OK. That would be the simplest option. Otherwise, you may choose ATI which provide full information about the modem, or one of AT+GMI, AT+GMM or AT+GMR, etc which provide partial information.

So you would have two functions:

  • detectModemPort() that would reply with the port number (or port name) if found or with an error
  • SendSMSTo(string port, string cnum) which will first open a serial connection on port port (which exists because we just detected it) and then send the SMS to cnum.

You may also want to have a look at this question/answer on SuperUser. It looks like there is a devcon.exe command to discover devices connected to a computer, but I don't have a Windows bon to try it.

mszmurlo
  • 1,250
  • 1
  • 13
  • 28