C # principles and methods for developing terminal text messages

Source: Internet
Author: User

From: http://blog.csdn.net/gztoby/archive/2004/09/21/112041.aspx

I learned a lot after reading it.

Introduction

Young people who have never sent text messages must belong to a protected rare animal. Today's well-developed text messages have become an important means for people to communicate, which also contains huge market and economic benefits, the talents who master text message technology are also sought after by major companies and are currently a shining star in the workplace. This article introduces the principles and implementation methods of text messages, focuses on the encoding method, at command of text messages, and serial communication method using C.

Preface

Currently, there are three ways to send text messages:

1. Gateway: it applies to the local telecommunications department and does not require additional equipment. It is applicable to large communication companies such as Huawei, aotian, ZTE, and Asiainfo.

2. Terminal Mode: connect to the computer through a data cable to send text messages using settings such as GSM Modem (mobile phones supporting AT commands can also, this method is applicable to small and individual users. To implement this method, you must understand serial communication, at command, SMS encoding, and decoding, which is also the focus of this article.

3. Some websites are used for implementation. The method is simple. However, website dependencies are too high and network requirements are high, which is not suitable for project development.

Read navigation
terminal Short Message connection
principles SMS encoding
at command
serial communication
practice
FAQs
download Source Code
encoding test file

Terminal Short Message connection


Principles

SMS code

In terms of sending and receiving text messages, there are three modes generated successively by Time: block mode, text mode based on AT command, PDU Modem Based on at command, text mode is relatively simple, multiple Nokia mobile phones support this mode. Most Siemens mobile phones only support the PDU mode. The PDU mode is a method for sending or receiving SMS messages from mobile phones. The text of Short Messages is transmitted after hexadecimal encoding. Currently, PDU has replaced block mode because we mainly discuss the transmission of PDU mode. Take the Siemens 3508 mobile phone as an example.

SMS is a specification developed by ETSI (GSM 03.40 and GSM 03.38 ). When 7-bits encoding is used, it can send a maximum of 160 characters. However, it is 8-bit encoded and can send a maximum of 140 characters, which is usually not displayed on a mobile phone; it can contain up to 70 characters in 16-bit encoding and is used to display Unicode (ucs2) text information, which can be displayed on most mobile phones. We are talking about ucs2 encoding today. That is to say, a maximum of 70 characters can be sent, whether in English or Chinese.

For example, we want to send the following message to my mobile phone 13715342642. "Hello, hello! ". Before sending the email, you must be clear that the SMS center number in the SIM card's location is not the SMS center number in your current location. For example, if I am in Shenzhen, the SMS center number in Shenzhen is 8613800755000, even if I am outside China, the SMS center number is still in Shenzhen. We get the following information from the above:

Received mobile phone number: 13715342642
SMS center No.: 8613800755000
Text message content: Hello, hello!

In actual use, the above information is not executed by the mobile phone, and will be executed only when the mobile phone is encoded. Check the encoded information first:

Bytes

Let me explain it:

08-refers to the length of the SMS center number, that is, the length of (91) + (683104705500f0)

91-indicates the short message center number type. 91 indicates that ton/NPI complies with the international/e.164 standard and requires the plus sign (+) before the number. In addition, there are other values, but 91 is the most commonly used.

68310000705500f0-SMS center number. The actual number should be 8613800731500 (the letter F indicates the length minus 1) because the location is slightly processed ). This needs to be modified based on different regions. The preceding (08) + (91) + (6830000705500f0) actually forms a part of the entire text message, which is called the address of the SMSC ).

11-File Header bytes

00-information type (TP-message-Reference)

0d-length of the callednumber

91-called Number Type

In practice, we usually write 11000d91ProgramBecause in China, the data will not change.

683117352446f2-called number. After displacement processing, the actual number is "8613715342642 ". The above (00) + (0d) + (91) + (683117352446f2) constitutes the second part of the destination address (TP-destination-address) of the entire text message ).

00-Protocol Identification TP-PID, which is generally 00

08-data encoding scheme TP-DCS (TP-data-coding-scheme), using the previously mentioned USC2 (16bit) Data Encoding

00-period TP-VP (TP-valid-period)

12-length TP-UDL (TP-user-data-length), that is, 4f60597dff0c00480065006c006c length 36/2 = 18 hexadecimal 12

4f60597dff0c00480065006c006c 006f0021-here is the text message content. The actual content is: "Hello, hello! "Program implementation, please refer to thisArticlePdudecoding. CS.

At command

When talking about at commands, there is a thick book, which is beyond the scope of our discussion today. Here I will only discuss the several AT commands necessary to send text messages.

The GSM at commands (from gsm07.05) related to SMS are shown in table 1:

At command Merit
At + cmgc Send an SMS command (send a short message command)
At + cmgd Delete SMS message (Short Message for deleting SIM card memory)
At + cmgf Select SMS message formate (select the Short Message format: 0-pdu; 1-text)
At + cmgl List SMS message from preferred store (list the short message PDU/Text: 0/"rec unread"-unread, 1/"rec read"-read, 2/"Sto unsent"-to be sent, 3/"Sto sent"-sent, 4/"all"-All)
At + cmgr Read SMS message)
At + cmgs Send SMS message)
At + cmgw Write SMS message to memory (write a short message to the sim memory)
At + CMSS Send SMS message from storage (send short messages from sin | M memory)
At + cnmi New SMS message indications (displays new short messages)
At + CPMS Preferred SMS message storage (select Short Message Memory)
At + csca SMS service center address (Short Message Center address)
At + CSCB Select Cell Broadcast messages (select cellular broadcast message)
At + CSMP Set SMS text mode parameters (Set Short Message text mode parameters)
At + CSMs Select Message Service (select short message service)

Table 1: Related GSM at commands

The following example shows how to use these commands:

Connect your mobile phone to your computer's serial port with the mobile phone data cable and set the baud rate of the serial port to 19200.

1. First, test whether your connection and mobile phone support the AT command. In your serial port debugging program, enter:

At <press enter>

If "OK" is returned on the screen, it indicates that the computer is connected to the mobile phone normally, so that we can test other AT commands.

2. Set the text message sending format

At + cmgf = 1 <press enter>

If "OK" is returned on the screen, the current message sending method is PDU. If it is set to text, at + cmgf = 0 <press enter>

3. send text messages

The sent content and manual number are still the same as those in the encoding. After encoding, the data to be sent is as follows:

Bytes

We use the following command to send

At + cmgs = 33 <press enter>

If ">" is returned, enter the encoded data above and end with Ctrl + Z. Wait a moment and you will see that the return result is OK.

Let's explain why at + cmgs = 33 is like this:

11000d91683117352446f2000800124f60597d002c00480065006c006c006f0021

The result is obtained by dividing the length of this string by 2. The above string, the SMS center number, and the text message content are obtained. For details, refer to the Decoding Section.

In our previous discussion, a complete text message is sent, as long as three at commands are executed, at, at + cmgs =? , At + cmgs =? You can. Due to the length, I can only mention so much here. If you want to learn more, you can ask mobile phone manufacturers for the AT Instruction White Paper, which is very detailed.

As mentioned above, we can only prepare for the actual situation. We also need a transmission channel. Based on our needs, we choose to invest the least to achieve convenient serial communication. Note: The serial port is connected to the mobile phone through the data cable, and the AT command is used to send text messages. When we select the data cable, we recommend that you purchase the original factory configuration instead of the original factory configuration. during use, some problems often occur. For example, if the screen of the mobile phone is black, the mobile phone always prompts that the battery is insufficient.

Serial Communication

Many people are overwhelmed to implement serial communication in C, on the forum, we often see problems such as "How to Use MSComm to implement serial communication" and "how to connect devices through serial ports. As a matter of fact, foreign netizens have long listed these items in the FAQ.

Generally, there are four methods to implement serial communication in C:

First, the MSComm control is the simplest and most convenient method. It is difficult to control the functions. At the same time, this control is not included in the system, so it has to be registered. It is not covered in this article. Can access http://www.devhood.com/tutorials/tutorial_details.aspx? Tutorial_id = 320. The author was very enthusiastic about the tutorial written by a foreign netizen. I sent an email to him and soon replied.

Second: Microsoft launched a new serial control in. Net Based on. NET's P/invoke call method.

Third: third-party controls are used, but payment is generally required. They are not practical and are not considered.

Fourth, it is difficult to write Serial Communication Using APIs, but it is convenient for us to implement various functions we want.

In this article, we use the fourth method to implement serial communication, but we did not write it by ourselves. We use a library already encapsulated by a foreign user. However, the function is simple and it is enough for us.

During the SMS operation on the terminal, only four functions are used for communication with the serial port to enable, write, read, and disable the serial port. The class library defines these four functions:

Open the serial port:

Function prototype: Public void open ()

Note: Open the preset Port

Example:

Using justinio;

Static justinio. comatrix ORT ss_port = new justinio. comatrix ORT ();
Ss_port.portnum = COM1; // port number
Ss_port.baudrate = 19200; // The baud rate of serial communication.
Ss_port.bytesize = 8; // data bit
Ss_port.parity = 0; // parity
Ss_port.stopbits = 1; // stop bit
Ss_port.readtimeout = 1000; // read timeout
Try
{
If (ss_port.opened)
{
Ss_port.close ();
Ss_port.open (); // open the serial port
}
Else
{
Ss_port.open (); // open the serial port
}
Return true;
}
Catch (exception E)
{
MessageBox. Show ("error:" + E. Message );
Return false;
}

Serial Port writing:

Function prototype: Public void write (byte [] writebytes)

Writebytes is the byte you write. Note that strings must be converted to byte Arrays for communication.

Example:

Ss_port.write (encoding. ASCII. getbytes ("at + cgmi \ r"); // obtain the mobile phone brand

Read Serial Port:

Function prototype: Public byte [] Read (INT numbytes)

Numbytes read cache count. Note that the byte array is read and character conversion is required in actual applications.

Example:

String response = encoding. ASCII. getstring (ss_port.read (128); // read 128 bytes of Cache

Close the serial port:

Function prototype: ss_port.close ()

Example:

Ss_port.close ();

I will only talk about this here because of its wide range of space and serial communication.

We have already learned about the various primitive technologies required by terminal text messages. It is time to try it out.

Practice

At the beginning, you should prepare the following software and hardware:

Hardware: One Siemens 3508 or C35 Series Mobile Phone
One Siemens mobile phone communication data line
Software: vs. Net (C #)
SMS encoding class library (pdudecoding. CS)
Serial Communication Library (justinio. CS)

When the required software and hardware are ready, we can officially start. The following describes my test cases in detail.

Everything should be planned. Although our test cases are simple, we still draw a simple flowchart:

With the flow chart, you just understand how the program runs and then look at the interface, it will make you more exciting.


Figure 2. Text message Terminal C # page

If you don't start again, someone will scold me. The development environment I am talking about is in vs. Net (C. Come go, go...

Step 1. Open vs. net, create a project, and select Visual C # project> Windows application. Enter your project name in the name. My name is smsforcsharp.

Step 2: design your program interface by referring to the interface diagram above. The following lists the main attributes of each control in my program.

Control name Control name attribute description
textbox targetnumber receive mobile phone number
textbox centernumber SMS center No.
textbox smsstate the message returned after the SMS is sent. Note: Set the control to multiple rows.
textbox smscontent text message content. Similarly, set as multiple lines
ComboBox connectport the port connecting to the mobile phone, for example, COM1 \ com2
ComboBox connectbaudrate the baud rate of the serial port connection, which is important in serial communication
button btnsend send button
button btnconnect connection button, mainly used for program initialization
button btnexit exit

Step 3. Set pdudecoding. CS and justinio. CS mounts to the new project directory, open solution Resource Manager, right-click to add existing items, select two files, and then open the Class View. Is there two more classes in it, justinio and SMS. 3. If no, try again.


Figure 3: Class View after adding a class

Step 4. Reference The namespaceCodeOpen form1.cs (this is based on my computer. If you have changed it, please refer to your computer), add

Using justinio;
Using SMS;
Using system. IO;
Using system. text;

Step 5: In the smsformcsharp class, add two fields ss_port and SMS, which are respectively justinio and SMS objects, as shown below:

Step 6. Add the serial port initialization Code as follows:

/// <Summary>
/// Initialize the serial port
/// </Summary>
Public bool initcom (string m_port, int m_baudrate)
{
Ss_port.portnum = m_port; // serial number
Ss_port.baudrate = m_baudrate; // baud rate
Ss_port.bytesize = 8; // data bit
Ss_port.parity = 0 ;//
Ss_port.stopbits = 1; // stop bit
Ss_port.readtimeout = 1000; // read timeout
Try
{
If (ss_port.opened)
{
Ss_port.close ();
Ss_port.open ();
}
Else
{
Ss_port.open (); // open the serial port
}
Return true;
}
Catch (exception E)
{
MessageBox. Show ("error:" + E. Message );
Return false;
}
}

Directly merge the above Code into your program, and ensure that it is added after the main function, press F5, debugging should be no problem, but there is no actual visible function above, just open the serial port.

Step 7. After opening the serial port, we should initialize the program, obtain the brand name, model, and SMS Center Number of the mobile phone, double-click the connection button, and paste the following code into the program:

/// <Summary>
/// Initialize the code and obtain mobile phone information
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "E"> </param>
Private void btnconnect_click (Object sender, system. eventargs E)
{
Bool opened = initcom (connectport. selecteditem. tostring (), convert. toint32 (connectbaudrate. selecteditem. tostring (); // open and initialize the serial port
Bool connected = false;
If (opened)
{
Ss_port.write (encoding. ASCII. getbytes ("at + cgmi \ r"); // obtain the mobile phone brand
String response = encoding. ASCII. getstring (ss_port.read (128 ));
If (response. length> 0)
{
Connectstate. Text = response. substring (10, 7 );
Connected = true;
}
Else
{
Connectstate. Text = "unable to connect to the mobile phone ";
Connected = false;
}
Ss_port.write (encoding. ASCII. getbytes ("at + cgmm \ r"); // obtain the mobile phone model
Response = encoding. ASCII. getstring (ss_port.read (128 ));
If (response. length> 0)
{
Connectstate. Text = connectstate. Text + "" + response. substring (10, 5) + "Connecting ......";
Connected = true;
}
Else
{
Connectstate. Text = "unable to connect to the mobile phone ";
Connected = false;
}
Ss_port.write (encoding. ASCII. getbytes ("at + csca? \ R "); // obtain the SMS center number
Response = encoding. ASCII. getstring (ss_port.read (128 ));
If (response. length> 0)
{
Centernumber. Text = response. substring (20, 13 );
Connected = true;
}
Else
{
Connected = false;
}
If (connected = true)
{
Btnconnect. Enabled = false;
Btnsend. Enabled = true;
}
Else
{
Btnconnect. Enabled = true;
Btnsend. Enabled = false;
}
}
}

At this point, you can press F5 to compile and debug it. After making sure that your phone is connected to your computer, click the connect button to see if it is like mine, the phone model and SMS center number are displayed normally.


Figure 4. Program Interface after connection

Step 8: Do you feel like you are very close to successfully sending text messages when you see the above results? It takes a lot of time to read such a long article and I am sorry for the text message.

Double-click the send button and paste the following code into the program.

///
// send a text message
///
///
//
private void btnsend_click (Object sender, system. eventargs e)
{< br> string decodedsms = SMS. smsdecodedsms (centernumber. text, targetnumber. text, smscontent. text);
byte [] Buf = encoding. ASCII. getbytes (string. format ("at + cmgs = {0} \ r", SMS. nlength);
ss_port.write (BUF);
strin G response = encoding. ASCII. getstring (ss_port.read (128);
string sendstate = "";
If (response. length> 0 & response. endswith (">")
{< br> ss_port.write (encoding. ASCII. getbytes (string. format ("{0} \ x01a", decodedsms);
sendstate = "sent successfully! ";
}< br> else
{< br> sendstate =" failed to send ";
}< P>

string result = string. format ("{0}, {1}, {2}, \ n \ r", targetnumber. text, smscontent. text, sendstate);
smsstate. text + = result;
}

Press F5! God, come on! You can send text messages now. Make sure that your phone can connect to your computer. Press connect, enter the target mobile phone number you want to send, and add the content you want to send to the content. Send it! Successful! The success is like this! Are you the same as mine?


Figure 5. Sent successfully

Remember to add and exit code. Double-click to exit and add the following code:

/// <Summary>
/// Close the serial port and exit the program
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "E"> </param>
Private void btnexit_click (Object sender, system. eventargs E)
{
Ss_port.close ();
Application. Exit ();
}

A paragraph is reported here, and all functions are completed! However, as this is only a demo case, there are still a lot of issues that have not been considered, such as serial communication, in the actual operation can not be such an operation, should be processed with multithreading, a dedicated to reading the serial port, A dedicated serial port for writing. There are also a lot of Error-proof codes in the program that have not been added, and I hope some friends can add them and publish them. This is what I hope to see in this article. Please do not directly use this program in practice. We sincerely remind you!

I have finally finished writing, and I have relaxed a lot. I should have done it for a long time. For some personal reasons, I have not finished writing it in time, sorry, I hope you will continue to support me!

Debugging environment:

Windows 2000 Professional, Visual Studio. NET, Siemens 3508 mobile phone, Siemens dedicated data cable.

FAQs:

First, the mobile phone brand, because the mobile phones of different manufacturers have different support for AT commands, so please select the AT command that suits your mobile phone. For Nokia, you can only use AT commands in text mode.

Second, the data line, where the most problems occur, is the data. If your mobile phone is displayed as a black screen after the data line is connected, we recommend that you change the data line.

Third, set the SMS center number on the SIM card of your mobile phone. Make sure that you can send text messages on your mobile phone.

Fourth, use the serial port debugging tool to debug the connection between your mobile phone and your computer. This guarantees your work.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.