Click here to Skip to main content
11,412,833 members (73,996 online)
Click here to Skip to main content

How To Send and Receive SMS using GSM Modem

, 15 Mar 2015 CPOL
Rate this:
Please Sign up or sign in to vote.
SMS Client - Server Software is used for sending, reading, deleting messages. It uses GSM modem for sending SMS. It listens for incoming messages to arrive, processes the read message and takes action accordingly. This SMS software requires GSMComm Library which you can also download.

Screenshot - MainScreen.jpg

Note - As of today (03/15/2015), I am deprecating this article in favor of a reliable way of managing SMS without the need for thirdparty libraries like GSMComm. Please feel free to have a look into the below article.
 

Introduction

SMS client and server is an application software which is used for sending and receiving messages(SMS). It listens for incoming messages to arrive, processes the message if it's in a valid format. Note the processing of arrived messages depends on the application which will be discussed later. I am going to explain the following things:

  1. Communication Port Settings
  2. Receive Incoming Message
  3. Send Messages
  4. Read All Messages (Sent by the users)
  5. Delete Messages (One or All)

I have used the GSMComm Library for Sending and Receiving SMS. You require a GSM modem or phone for sending an SMS.

Using the code

1) Communication Port Settings

Screenshot - CommSettings.jpg

CommSetting class is used for storing comm port settings:

public class CommSetting
{
    public static int Comm_Port=0;
    public static Int64 Comm_BaudRate=0;
    public static Int64 Comm_TimeOut=0;
    public static GsmCommMain comm;

    public CommSetting()
    {
        //
        // TODO: Add constructor logic here
        //
    }
}

Comm is an object of type GsmCommMain which is required for sending and receiving messages. We have to set the Comm port, Baud rate and time out for our comm object of type GsmCommMain. Then try to open with the above settings. We can test the Comm port settings by clicking on the Test button after selecting the Comm port, baud rate and Time out. Sometimes if the comm port is unable to open, you will get a message "No phone connected". This is mainly due to Baud rate settings. Change the baud rate and check again by clicking the Test button until you get a message "Successfully connected to the phone."

Before creating a GSMComm object with settings, we need to validate the port number, baud rate and Timeout.

The EnterNewSettings() does validation, returns true if valid, and will invoke SetData(port,baud,timeout) for comm setting.

The following block of code will try to connect. If any problem occurs "Phone not connected" message appears and you can either retry by clicking on the Retry button or else Cancel.

GsmCommMain comm = new GsmCommMain(port, baudRate, timeout);
try
{
        comm.Open();
        while (!comm.IsConnected())
        {
            Cursor.Current = Cursors.Default;
            if (MessageBox.Show(this, "No phone connected.",
               "Connection setup", MessageBoxButtons.RetryCancel,
                 MessageBoxIcon.Exclamation) == DialogResult.Cancel)
            {
                comm.Close();
                return;
            }
            Cursor.Current = Cursors.WaitCursor;
        }

        // Close Comm port connection (Since it's just for testing
        // connection)
        comm.Close();
}
catch(Exception ex)
{
    MessageBox.Show(this, "Connection error: " + ex.Message,
    "Connection setup", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    return;
}

// display message if connection is a success.
MessageBox.Show(this, "Successfully connected to the phone.",
"Connection setup", MessageBoxButtons.OK, MessageBoxIcon.Information);

Screenshot - SucessfullyConnected.jpg

2) Receive Incoming Message

We are going to register the following events for GSMComm object comm.

  1. PhoneConnected
    This event is invoked when you try to open the Comm port. The event handler for Phone connected is comm_PhoneConnected which will invoke OnPhoneConnectionChange(bool connected) with the help of Delegate ConnectedHandler.
  2. MessageReceived
    This event is invoked when a message arrives at the GSM phone. We will register with MessageReceivedEventHandler. When the incoming message arrives, the comm_MessageReceived method will be invoked which in turn calls the MessageReceived() method in order to process the unread message. GSMComm object comm has a method ReadMessages which will be used for reading messages. It accepts the following parameters phone status (All, ReceivedRead, ReceivedUnread, StoredSent, and StoredUnsent) and storage type: SIM memory or Phone memory.
private void MessageReceived()
{
    Cursor.Current = Cursors.WaitCursor;
    string storage = GetMessageStorage();
    DecodedShortMessage[] messages = CommSetting.comm.ReadMessages
                   (PhoneMessageStatus.ReceivedUnread, storage);
    foreach(DecodedShortMessage message in messages)
    {
         Output(string.Format("Message status = {0},
     Location =  {1}/{2}",
         StatusToString(message.Status),
         message.Storage, message.Index));
         ShowMessage(message.Data);
         Output("");
    }

    Output(string.Format("{0,9} messages read.",
                messages.Length.ToString()));
    Output("");
}   

The above code will read all unread messages from SIM memory. The method ShowMessage is used for displaying the read message. The message may be a status report, stored message sent/un sent, or a received message.

3) Send Message

Screenshot - SendSMS.jpg

You can send an SMS by keying in the destination phone number and text message.

If you want to send a message in your native language (Unicode), you need to check in Send as Unicode(UCS2). GSMComm object comm has a SendMessage method which will be used for sending SMS to any phone. Create a PDU for sending messages. We can create a PDU in straight forward version as:

SmsSubmitPdu pdu = new SmsSubmitPdu
        (txt_message.Text,txt_destination_numbers.Text,"");

An extended version of PDU is used when you are sending a message in Unicode.

 try
{
    // Send an SMS message
    SmsSubmitPdu pdu;
    bool alert = chkAlert.Checked;
    bool unicode = chkUnicode.Checked;

    if (!alert && !unicode)
    {
        // The straightforward version
        pdu = new SmsSubmitPdu
        (txt_message.Text, txt_destination_numbers.Text,"");
    }
    else
    {
        // The extended version with dcs
        byte dcs;
        if (!alert && unicode)
            dcs = DataCodingScheme.NoClass_16Bit;
        else
        if (alert && !unicode)
            dcs = DataCodingScheme.Class0_7Bit;
        else
        if (alert && unicode)
            dcs = DataCodingScheme.Class0_16Bit;
        else
            dcs = DataCodingScheme.NoClass_7Bit;

        pdu = new SmsSubmitPdu
        (txt_message.Text, txt_destination_numbers.Text, "", dcs);
    }

    // Send the same message multiple times if this is set
        int times = chkMultipleTimes.Checked ?
                int.Parse(txtSendTimes.Text) : 1;

    // Send the message the specified number of times
    for (int i=0;i<times;i++)
    {
        CommSetting.comm.SendMessage(pdu);
        Output("Message {0} of {1} sent.", i+1, times);
        Output("");
    }
}
catch(Exception ex)
{
    MessageBox.Show(ex.Message);
}

Cursor.Current = Cursors.Default;

4) Read All Messages

Screenshot - ReadAllMessages.jpg

You can read all messages from the phone memory of SIM memory. Just click on "Read All Messages" button. The message details such as sender, date-time, text message will be displayed on the Data Grid. Create a new row for each read message, add to Data table and assign the Data table to datagrid's source

private void BindGrid(SmsPdu pdu)
{
    DataRow dr=dt.NewRow();
    SmsDeliverPdu data = (SmsDeliverPdu)pdu;

    dr[0]=data.OriginatingAddress.ToString();
    dr[1]=data.SCTimestamp.ToString();
    dr[2]=data.UserDataText;
    dt.Rows.Add(dr);

    dataGrid1.DataSource=dt;
}

The above code will read all unread messages from SIM memory. The method ShowMessage is used for displaying the read message. The message may be a status report, stored message sent/un sent, or a received message. The only change in processing Received message and Read message is the first parameter.

For received message

DecodedShortMessage[] messages =
  CommSetting.comm.ReadMessages(PhoneMessageStatus.ReceivedUnread, storage);

For read all messages

DecodedShortMessage[] messages =
   CommSetting.comm.ReadMessages(PhoneMessageStatus.All, storage);

5) Delete Messages (One or All)

Screenshot - DeleteMessage.jpg

All messages which are sent by the users will be stored in SIM memory and we are going to display them in the Data grid. We can delete a single message by specifying the message index number. We can delete all messages from SIM memory by clicking on "Delete All" button. Messages are deleted based on the index. Every message will be stored in memory with a unique index.

The following code will delete a message based on index:

// Delete the message with the specified index from storage
CommSetting.comm.DeleteMessage(index, storage);

To delete all messages from memory( SIM/Phone)

// Delete all messages from phone memory
CommSetting.comm.DeleteMessages(DeleteScope.All, storage); 

The DeleteScope is an Enum which contains:

  1. All
  2. Read
  3. ReadAndSent
  4. ReadSentAndUnsent

Applications

Here are some interesting applications where you can use and modify this software.

1) Pre paid Electricity

Scenario (Customer)

The customer has agreed for pre paid electricity recharges with the help of recharge coupons. The coupon is made available at shops. The customer will first buy the coupons from shops; every coupon consists of Coupon PIN which will be masked, the customer needs to scratch to view the PIN number. The customer will send an SMS to the SMS Server with a specified message format for recharging.

Message Format for Recharging:
RECHARGE <Coupon No> <Customer ID>

Scenario (Server Database)

On the Server, the Database consists of Customer information along with his telephone number, there will a field named Amount which will be used and updated when the customer recharged with some amount. This application becomes somewhat complex, an automatic meter reading software along with hardware needs to be integrated with this. Automatic meter reading systems will read all meter readings and calculate the amount to be deducted for the customer.

2) Astrology

You can implement as astrology software. The user will send an SMS with his zodiac sign. The SMS server will maintain an Astrology Database with zodiac sign and a text description which contains a message for the day. The Database is required to be updated daily for all zodiac signs.

Message Format which will be used by the user to get message of the day:
Zodiac Sign

3) Remote Controlling System

We can implement a remote controlling system, for example you need to:

  1. Shutdown
  2. Restart
  3. Log off system

You can send an SMS. The SMS server will listen and then process the message. Based on the message format sent by the user we can take action.
Example if message format is:
SHUTDOWN
Send to SMS phone number.

Conclusion

This project wouldn't be completed unless I thank the GSMComm Lib developer "Stefan Mayr". I customized my application using this Library. You can download the sample project, library from the web link which I provided under the Reference section.

Reference

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ranjan.D
Web Developer
United States United States
Profile

Around 10 years of professional software development experience in analysis, design, development, testing and implementation of enterprise web applications for healthcare domain with good exposure to object-oriented design, software architectures, design patterns, test-driven development and agile practices.

In Brief

Analyse and create High Level , Detailed Design documents.
Use UML Modelling and create Use Cases , Class Diagram , Component Model , Deployment Diagram, Sequence Diagram in HLD.

Area of Working : Dedicated to Microsoft .NET Technologies
Experience with : C# , J2EE , J2ME, Windows Phone 8, Windows Store App
Proficient in: C# , XML , XHTML, XML, HTML5, Javascript, Jquery, CSS, SQL, LINQ, EF

Software Development

Database: Microsoft SQL Server, FoxPro
Development Frameworks: Microsoft .NET 1.1, 2.0, 3.5, 4.5
UI: Windows Forms, Windows Presentation Foundation, ASP.NET Web Forms and ASP.NET MVC3, MVC4
Coding: WinForm , Web Development, Windows Phone, WinRT Programming, WCF, WebAPI

Healthcare Domain Experience

CCD, CCR, QRDA, HIE, HL7 V3, Healthcare Interoperability

Education

B.E (Computer Science)

CodeProject Contest So Far:

1. Windows Azure Developer Contest - HealthReunion - A Windows Azure based healthcare product , link - http://www.codeproject.com/Articles/582535/HealthReunion-A-Windows-Azure-based-healthcare-pro

2. DnB Developer Contest - DNB Business Lookup and Analytics , link - http://www.codeproject.com/Articles/618344/DNB-Business-Lookup-and-Analytics

3. Intel Ultrabook Contest - Journey from development, code signing to publishing my App to Intel AppUp , link - http://www.codeproject.com/Articles/517482/Journey-from-development-code-signing-to-publishin

4. Intel App Innovation Contest 2013 - eHealthCare

5. Grand Prize Winner of CodeProject HTML5 &CSS3 Article Contest 2014

6. Grand Prize Winner of CodeProject Android Article Contest 2014

7. Grand Prize Winner of IOT on Azure Contest 2015

Comments and Discussions

 
Questionerror Pin
KanavKathuria at 11-Jul-13 22:55
memberKanavKathuria11-Jul-13 22:55 
Questionmessage service error 331 Pin
SoftMise at 7-Jul-13 6:38
memberSoftMise7-Jul-13 6:38 
QuestionCMS error 500 Pin
Le@rner at 2-May-13 2:45
memberLe@rner2-May-13 2:45 
QuestionConnection error Pin
Nallu Kumarappan at 28-Apr-13 23:21
memberNallu Kumarappan28-Apr-13 23:21 
QuestionNo phone connected Pin
Nallu Kumarappan at 28-Apr-13 21:24
memberNallu Kumarappan28-Apr-13 21:24 
AnswerRe: No phone connected Pin
Rabee3-F1.787545 at 7-Aug-13 22:10
memberRabee3-F1.7875457-Aug-13 22:10 
BugRe: No phone connected Pin
Member 7999118 at 24-Nov-13 22:59
memberMember 799911824-Nov-13 22:59 
Questioncan't send long arabic sms. Pin
hafez at 28-Apr-13 3:38
memberhafez28-Apr-13 3:38 
QuestionMessage service error 500 occurred - Error Pin
Member 9966833 at 13-Apr-13 1:37
memberMember 996683313-Apr-13 1:37 
QuestionGsmcomm library Pin
vinod.kande at 3-Apr-13 23:20
membervinod.kande3-Apr-13 23:20 
AnswerRe: Gsmcomm library Pin
Ranjan.D at 4-Apr-13 2:32
memberRanjan.D4-Apr-13 2:32 
GeneralRe: Gsmcomm library Pin
vinod.kande at 4-Apr-13 3:16
membervinod.kande4-Apr-13 3:16 
GeneralRe: Gsmcomm library Pin
Pritesh Aryan at 8-Mar-14 0:08
memberPritesh Aryan8-Mar-14 0:08 
QuestionNo SIM Pin
balong41 at 31-Mar-13 17:06
memberbalong4131-Mar-13 17:06 
How can we make a test if SIM is present. When it executes the get signal function, it goes out to retrieve the correct response from the device but obviously it won't come because there is no SIM card present. It will report after 30000 ms. How can we adjust that time and ouput the correct error like "SIM card Error";

thanks
Questionhow send more than 160 character with smartmessagefactory or show me an example ? Pin
Farhadman at 26-Feb-13 0:16
memberFarhadman26-Feb-13 0:16 
QuestionQuestion Pin
naq_ninetwo92 at 21-Feb-13 15:07
membernaq_ninetwo9221-Feb-13 15:07 
QuestionHelp! Pin
NainudhiN at 17-Feb-13 21:20
memberNainudhiN17-Feb-13 21:20 
Questionsms gsmcomm lib Pin
pranavjeet at 11-Feb-13 6:46
memberpranavjeet11-Feb-13 6:46 
AnswerRe: sms gsmcomm lib Pin
Ranjan.D at 4-Apr-13 2:35
memberRanjan.D4-Apr-13 2:35 
GeneralRe: sms gsmcomm lib Pin
Member 4212559 at 13-Jun-13 1:58
memberMember 421255913-Jun-13 1:58 
Questionabout my project Pin
mitali patil at 11-Feb-13 1:42
membermitali patil11-Feb-13 1:42 
AnswerRe: about my project Pin
Ranjan.D at 11-Feb-13 2:25
memberRanjan.D11-Feb-13 2:25 
GeneralMy vote of 1 Pin
hitesh bhatt at 29-Jan-13 2:54
memberhitesh bhatt29-Jan-13 2:54 
QuestionMessage notification does not work using a Huawei E372 3G/GSM/USB Modem Pin
Member 9715744 at 22-Jan-13 5:31
memberMember 971574422-Jan-13 5:31 
QuestionHOW TO SEND A MESSAGE THAT IS MORE THAN 160 CHARACTERS ? PLS HELP THANKS IN ADVANCE Pin
ehmjhay at 10-Jan-13 23:20
memberehmjhay10-Jan-13 23:20 
AnswerRe: HOW TO SEND A MESSAGE THAT IS MORE THAN 160 CHARACTERS ? PLS HELP THANKS IN ADVANCE Pin
hafez at 8-Feb-13 2:59
memberhafez8-Feb-13 2:59 
QuestionNo Phone's Connected Pin
Leo Mark Delos Santos at 19-Dec-12 0:16
memberLeo Mark Delos Santos19-Dec-12 0:16 
SuggestionProblems/Resolutions for this project Pin
Ranjan.D at 18-Dec-12 17:47
memberRanjan.D18-Dec-12 17:47 
QuestionPhone Not Connected Pin
palesha at 20-Nov-12 4:28
memberpalesha20-Nov-12 4:28 
AnswerRe: Phone Not Connected Pin
ehmjhay at 10-Feb-13 17:11
memberehmjhay10-Feb-13 17:11 
GeneralRe: Phone Not Connected Pin
RashmitaS at 4-Apr-13 10:19
memberRashmitaS4-Apr-13 10:19 
GeneralRe: Phone Not Connected Pin
J.Mañago at 10-Apr-13 20:24
memberJ.Mañago10-Apr-13 20:24 
QuestionHow to sent sms via xls sheet Pin
Member 9588700 at 10-Nov-12 4:44
memberMember 958870010-Nov-12 4:44 
AnswerRe: How to sent sms via xls sheet Pin
Ranjan.D at 18-Dec-12 17:55
memberRanjan.D18-Dec-12 17:55 
AnswerRe: How to sent sms via xls sheet Pin
Fahad Rafiq at 20-Aug-13 9:21
memberFahad Rafiq20-Aug-13 9:21 
Questionsend many sms Pin
bongdem1903 at 8-Nov-12 2:37
memberbongdem19038-Nov-12 2:37 
AnswerRe: send many sms Pin
Ranjan.D at 8-Nov-12 2:46
memberRanjan.D8-Nov-12 2:46 
GeneralMy vote of 5 Pin
Pavan 8077682 at 30-Oct-12 8:46
memberPavan 807768230-Oct-12 8:46 
GeneralRe: My vote of 5 Pin
Ranjan.D at 30-Oct-12 9:10
memberRanjan.D30-Oct-12 9:10 
QuestionPhone Connected but 0 messages read ??? Pin
munawersheikh at 9-Oct-12 19:19
membermunawersheikh9-Oct-12 19:19 
AnswerRe: Phone Connected but 0 messages read ??? Pin
Ranjan.D at 9-Oct-12 20:13
memberRanjan.D9-Oct-12 20:13 
GeneralRe: Phone Connected but 0 messages read ??? Pin
munawersheikh at 10-Oct-12 1:43
membermunawersheikh10-Oct-12 1:43 
GeneralRe: Phone Connected but 0 messages read ??? Pin
ehmjhay at 10-Feb-13 17:18
memberehmjhay10-Feb-13 17:18 
GeneralRe: Phone Connected but 0 messages read ??? Pin
Glendonz at 18-Dec-12 14:58
memberGlendonz18-Dec-12 14:58 
GeneralMy vote of 5 Pin
ask.sagaram at 3-Oct-12 9:38
memberask.sagaram3-Oct-12 9:38 
Questionvb.net vesion Pin
jeleostephen at 2-Oct-12 2:09
memberjeleostephen2-Oct-12 2:09 
AnswerRe: vb.net vesion Pin
Ranjan.D at 4-Oct-12 3:57
memberRanjan.D4-Oct-12 3:57 
Questiongsm module Pin
trixie tiglao at 29-Sep-12 23:13
membertrixie tiglao29-Sep-12 23:13 
AnswerRe: gsm module Pin
Ranjan.D at 4-Oct-12 3:57
memberRanjan.D4-Oct-12 3:57 
Questioncheck port is used or not Pin
danar_kalari at 24-Sep-12 3:28
memberdanar_kalari24-Sep-12 3:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150427.1 | Last Updated 16 Mar 2015
Article Copyright 2007 by Ranjan.D
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid