• No results found

How to Send and Receive SMS Using GSM Modem

N/A
N/A
Protected

Academic year: 2021

Share "How to Send and Receive SMS Using GSM Modem"

Copied!
10
0
0

Loading.... (view fulltext now)

Full text

(1)

How To Send and Receive SMS using GSM

How To Send and Receive SMS using GSM

Modem

Modem

By

ByRanjan.DRanjan.D,,10 Sep 200710 Sep 2007

4.88 (84 votes)

4.88 (84 votes)

 Download source files - 295.1 KBDownload source files - 295.1 KB

Introduction

Introduction

SMS client and server is

SMS client and server is an application software which is used for sending and receivingan application software which is used for sending and receiving messages(SMS). It listens for incoming messages to arrive, processes the message if it's

messages(SMS). It listens for incoming messages to arrive, processes the message if it's in a validin a valid format. Note the processing of arrived messages depends on the

format. Note the processing of arrived messages depends on the application which will be discussedapplication which will be discussed later. I am going to

later. I am going to explain the following things:explain the following things: 1.

1. Communication Port SettingsCommunication Port Settings 2.

2. Receive Incoming MessageReceive Incoming Message 3.

(2)

4. Read All Messages (Sent by the users) 5. Delete Messages (One or All)

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

Using the code

1) Communication Port Settings

CommSettingclass is used for storing comm port settings:

Collapse | Copy Code 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  // 

} }

Commis an object of type GsmCommMainwhich is required for sending and receiving messages. We have to set theCommport, Baud rate and time out for ourcommobject of typeGsmCommMain. 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."

(3)

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

The EnterNewSettings() does validation, returnstrueif 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.

Collapse | Copy Code 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);

(4)

We are going to register the following events forGSMComm objectcomm. 1. PhoneConnected

This event is invoked when you try to open the Comm port. The event handler for Phone connected iscomm_PhoneConnectedwhich will invokeOnPhoneConnectionChange( 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 withMessageReceivedEventHandler. When the incoming message arrives, thecomm_MessageReceivedmethod will be invoked which in turn calls theMessageReceived()method in order to process the unread

message.GSMCommobjectcommhas a method ReadMessageswhich will be used for reading messages. It accepts the following parameters phone status

(All,ReceivedRead,ReceivedUnread,StoredSent, andStoredUnsent) and storage type: SIM memory or Phone memory.

Collapse | Copy Code 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 ShowMessageis used for displaying the read message. The message may be a status report, stored message sent/un sent, or a received message.

(5)

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).GSMCommobject comm has aSendMessagemethod 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:

Collapse | Copy Code 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.

Collapse | Copy Code try

{

 // Send an SMS message SmsSubmitPdu pdu;

(6)

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;

(7)

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

Collapse | Copy Code 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,

(8)

or a received message. The only change in processing Received message and Read message is the first parameter.

For received message

Collapse | Copy Code DecodedShortMessage[] messages =

CommSetting.comm.ReadMessages(PhoneMessageStatus.ReceivedUnread, storage);

For read all messages

Collapse | Copy Code DecodedShortMessage[] messages =

CommSetting.comm.ReadMessages(PhoneMessageStatus.All, storage);

5) Delete Messages (One or All)

All messages which are sent by the users will be stored in SIM memory and we are going t o display them in the Data grid. We can delete a single message by specifying the message index number. We

(9)

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:

Collapse | Copy Code  // Delete the message with the specified index from storage

CommSetting.comm.DeleteMessage(index, storage);

To delete all messages from memory( SIM/Phone)

Collapse | Copy Code  // Delete all messages from phone memory

CommSetting.comm.DeleteMessages(DeleteScope.All, storage);

The DeleteScopeis anEnum 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 Amountwhich will be used and updated when the customer recharged with some amount. This application becomes somewhat complex, an automatic meter reading software

(10)

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 f or 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

References

Related documents

Finally they gave a comparison of the original protocol, group based protocol and proposed protocol and stated that their proposed scheme provides better results in

• If the path is not empty the program checks if the folder does not contain Word documents, if so an error message appears and program ends. • If folder does

It is clear, however, that entanglement with anthro- pogenic plastic materials such as discarded fishing gear and land-based sources is an under-reported and under-researched threat

Preservice teachers may have a variety of beliefs about their role as moral educators, which may be affected by their moral beliefs and past experiences. These beliefs may range from

In this paper, the author concentrates on the effect of the share of youth population on the unemployment and labour force participation rates of different age groups leaving out

This paper combines social network analysis and multilevel analysis to estimate the relative share of variation of risky and protective health behaviours at different levels of

Esta nova conceção obrigou o repensar, de um modo diferente a intervenção educativa de crianças com Necessidades Educativas, em vários países do mundo. Mais tarde e já

• power generation automation systems • explosion proof medium voltage motors. medium voltage asynchronous modular and slip-ring motors •