Development of Short Message application based on VC ++ serial Programming
Source: Internet
Author: User
Text message application development for VC ++ serial programming-Linux general technology-Linux programming and kernel information. The following is a detailed description. We have explained the hardware principles, DOS platform control, and serial Programming Based on WIN32 APIs, controls, and third-party classes for a long time. As the last serialization of this series of articles, this chapter will provide a typical application example: Serial Port Control of the Siemens SMS service module TC35.
1. SMS control terminal
As a Short Message Service (SMS) family, you must have the following experience: it is inconvenient and error-prone to edit Short messages on your mobile phone, and the modification takes a long time, it is much easier to use computers to send and receive text messages. Note: The use of computers to send and receive text messages does not mean that messages are sent and received over the Internet through methods such as "Netease SMS King". Instead, they are directly sent and received by using computers to control the short message terminals running the GSM communication system, therefore, the principle of sending and receiving text messages is essentially the same as that of mobile phones.
In fact, a lot of spam messages are sent from such short message terminals!
We will introduce a GSM module, TC35 of Siemens, which consists of GSM baseband processor, dedicated Integrated Circuit for power supply, RF circuit and flash memory, processes the audio, data, and signals in GSM cellular devices. The embedded software partially implements the application interface and all GSM protocol stack functions. TC35 supports Chinese Short Messages and works in the EGSM900 and GSM1800 dual-band. The power supply range is 3.3 ~ 5.5 V, capable of transmitting voice and data signals, consuming 2 W and 1 W in EGSM900 (class 4) and GSM 1800 (class 1), respectively, connect the SIM card reader and antenna respectively through the Interface connector and antenna connector. The data interface (CMOS level) of TC35 can transmit commands and data in two directions through the AT command. The optional baud rate is bit/s ~ 115 kbit/s, the automatic baud rate is 1.2k ~ 115 kbit/s. It supports text and PDU formats, and can be restarted and restored through AT command or Shutdown signal.
We need to use the TC35 module as the main hardware to form a TC35 terminal device, and the computer through the RS-232C serial port is connected, and self-compiled on the PC running short message receiving and receiving software, to form an SMS receiving and receiving system. Shows the TC35 terminal circuit:
The TC35 control mainly includes the following commands:
(1) initialization command
Set the short message sending format AT + CMGF = 1. Set 1 to PDU mode, which is the carriage return symbol, that is, 0x0d. If the command is correct, the module returns OK, which is the carriage return line break symbol.
(2) Set/read short message center
The short message center number is provided by the mobile operator.
Set the Command Format of the short message center:
AT + CSCA = "+ 8613800531500" (Short Message Center)
If the setting is correct, the module returns OK.
To read the short message service center, run the following command:
AT + CSCA =?
The TC35 module should return:
+ CSCA: "8613800531500 ″.
(3) set an automatic prompt for arrival of Short Messages
The command format for setting the prompt for the arrival of a short message is as follows:
AT + CNMI =, 1
If the settings are correct, the TC35 module returns:
OK.
Set this command so that the module sends the command to the serial port after the short message arrives:
+ CMTI: "SM", INDEX (information storage location ).
The method for sending short messages through TC35 is:
The control software on the PC sends and receives data in the PDU format. The short message content can be Chinese or other characters. In PDU mode, if a short message is sent, the length of the short message data is sent first:
AT + CMGS =
When the TC35 module returns the ASCII character ">", the PDU data can be input, and the PDU data (that is, 0x1a) is used as the Terminator. The short message is sent successfully, and the module returns:
OK
The method for receiving short messages through TC35 is:
After the short message arrives, the command is received on the serial port.
+ CMTI: "SM", INDEX (information storage location)
The control software on the PC reads the AT command of PDU data.
AT + CMGR = INDEX
Read the short message content in PDU format in the TC35 module. If + CMGL is used instead of + CMGR, all short messages can be read at one time.
The method for deleting short messages through TC35 is:
After receiving a short message and processing it, the control software on the PC needs to delete it from the SIM card to prevent saturation of the SIM card. The command to delete a short message is:
AT + CMGD = INDEX
Module return after deletion
OK
2. program instance
Because the purpose of this article is to explain the serial communication, we shield the details of the graphic user interface and create a simple text message sending and receiving software, which contains all the serial communication content that controls the SMS terminal. In fact, an ideal text message sending and receiving software interface should be similar to Outlook or Foxmail, including inbox, sender, and sent text message box, however, these items have nothing to do with the serial communication we want to introduce. Therefore, although the following software interface is "out of the box", it can still be called "Jinyu ":
The control on the interface is described as follows:
Thanks to bhw98, author of "sending and receiving short messages via serial port", he wrote several C functions independent of the operating system platform for us, so that we can directly call these functions in the application. These functions are also fully utilized in this control software.
The following describes the main data structures and core functions of the routine software:
Data Structure
// User information encoding method
# Define GSM_7BIT 0
# Define GSM_8BIT 4
# Define GSM_UCS2 8
// Short Message Parameter structure, shared encoding/Decoding
// The string ends with 0.
Typedef struct
{
Char SCA [16]; // Short Message Service Center number (SMSC address)
Char TPA [16]; // target number or reply number (TP-DA or TP-RA)
Char TP_PID; // User Information Protocol identifier (TP-PID)
Char TP_DCS; // user information encoding method (TP-DCS)
Char TP_SCTS [16]; // service timestamp string (TP_SCTS), used for receiving
Char TP_UD [161]; // original user information (TP-UD before or after decoding)
Char index; // Short Message serial number, used for reading
} SM_PARAM;
Send Short Message
The function corresponding to the send button is CSMSControlDlg: OnSendButton. It reads the user's output and forms the content of SM_PARAM (source PDU parameter) based on the target phone number and short message content, and then sends it:
Void CSMSControlDlg: OnSendButton ()
{
// TODO: Add your control notification handler code here
// Obtain user input
CString desPhoneNum;
CString smsContent;
GetDlgItemText (IDC_PHONENUM_EDIT, desPhoneNum );
GetDlgItemText (IDC_SMSCONTENT_EDIT, smsContent );
// Fill in the content of the SM_PARAM struct
SM_PARAM smParam;
SmParam = CreateSMPARAMStruct (desPhoneNum, smsContent );
// Send Short Message
GsmSendMessage (smParam );
}
The call of the gsmSendMessage function reflects the core content of serial communication. It sends short messages according to the serial control process of short messages sent by the GSM module described in section 1st:
BOOL gsmSendMessage (const SM_PARAM * pSrc // pSrc: Source PDU parameter pointer)
{
Int nPduLength; // PDU String Length
Unsigned char nSmscLength; // SMSC String Length
Int nLength; // The length of data received by the serial port
Char cmd [16]; // command string
Char pdu [512]; // PDU string
Char ans [128]; // response string
NPduLength = gsmEncodePdu (pSrc, pdu); // encode the PDU string according to the PDU Parameter
Strcat (pdu, "\ x01a"); // end with Ctrl-Z
GsmString2Bytes (pdu, & nSmscLength, 2); // obtain the length of SMSC information in the PDU string
NSmscLength ++; // Add the Length Byte itself
// The length in the command, excluding the length of SMSC information, measured in bytes
Sprintf (cmd, "AT + CMGS = % d \ r", nPduLength/2-nSmscLength); // generate a command
WriteComm (cmd, strlen (cmd); // output the command string first
NLength = ReadComm (ans, 128); // read response data
// Determine whether a success is successful based on whether "\ r \ n>" can be found.
If (nLength = 4 & strncmp (ans, "\ r \ n>", 4) = 0)
{
WriteComm (pdu, strlen (pdu); // get a positive response and continue to output the PDU string
NLength = ReadComm (ans, 128); // read response data
// Determine whether the task is successful based on whether the "+ cms error" can be found.
If (nLength> 0 & strncmp (ans, "+ cms error", 10 )! = 0)
{
Return TRUE;
}
}
Return FALSE;
}
Read short messages
Click "receive" to obtain all short messages through the call of the gsmReadMessage function, and then display all messages in the list control:
Void CSMSControlDlg: OnRecvButton ()
{
// TODO: Add your control notification handler code here
SM_PARAM smParam [100]; // SMS Buffer
Int smsNum; // number of messages
SmsNum = gsmReadMessage (smParam); // read SMS
// Display text message
For (int I = 0; I
{
M_recvlist.AddString (CString (smsNum . TPA) + smsNum. TP_UD );
}
}
The gsmReadMessage function is called to complete the core short message receiving function. It receives short messages according to the serial control process of the GSM module described in section 1st:
// Parameter: pMsg short message buffer, which must be large enough
// Return: Number of Short Messages
Int gsmReadMessage (SM_PARAM * pMsg)
{
Int nLength; // The length of data received by the serial port
Int nMsg; // Short Message count value
Char * ptr; // Internal Data Pointer
Char cmd [16]; // command string
Char ans [1024]; // response string
NMsg = 0;
Ptr = ans;
Sprintf (cmd, "AT + CMGL \ r"); // generate a command to read all short messages AT a time using + CMGL
WriteComm (cmd, strlen (cmd); // output command string
NLength = ReadComm (ans, 1024); // read response data
// Determine whether the task is successful based on whether the "+ cms error" can be found.
If (nLength> 0 & strncmp (ans, "+ cms error", 10 )! = 0)
{
// Read each Short Message cyclically, starting with "+ CMGL :"
While (ptr = strstr (ptr, "+ CMGL :"))! = NULL)
{
Ptr + = 6; // skip "+ CMGL :"
Sscanf (ptr, "% d", & pMsg-> index); // read the serial number
Ptr = strstr (ptr, "\ r \ n"); // locate the next row
Ptr + = 2; // skip "\ r \ n"
GsmDecodePdu (ptr, pMsg); // PDU string Decoding
PMsg ++; // prepare to read the next short message
NMsg ++; // Add 1 to the Short Message count
}
}
Return nMsg;
}
Delete Short Message
After reading all the messages, we can call the gsmemessage function to delete the messages that have been received on the PC in the GSM module, it deletes short messages according to the serial port control process of the GSM module described in section 1st:
// Index: Short Message number, starting from 1
BOOL gsmDeleteMessage (const int index)
{
Int nLength; // The length of data received by the serial port
Char cmd [16]; // command string
Char ans [128]; // response string
Sprintf (cmd, "AT + CMGD = % d \ r", index); // generate a command
// Read the response data
NLength = ReadComm (ans, 128 );
// Determine whether the task is successful based on whether the "+ cms error" can be found.
If (nLength> 0 & strncmp (ans, "+ cms error", 10 )! = 0)
{
Return TRUE;
}
Return FALSE;
}
In the SMS list box of the PC control software, the function of deleting the "clear" button for all short messages is as follows:
Void CSMSControlDlg: OnDeleteallButton ()
{
// TODO: Add your control notification handler code here
M_recvlist.ResetContent ();
}
Set/read/write serial port
Serial port-related functions widely used in the startup and exit of applications and the functions of gsmSendMessage, gsmReadMessage, and gsmDeleteMessage are implemented using WIN32 APIs:
// Serial device handle
HANDLE hComm;
// Open the serial port
// PPort: Serial Port name or device path, which can be "COM1" or "\. \ COM1". The latter is recommended.
// NBaudRate: baud rate
// NParity: parity
// NByteSize: Data byte width
// NStopBits: Stop bit
BOOL OpenComm (const char * pPort, int nBaudRate, int nParity, int nByteSize, int
NStopBits)
{
DCB dcb; // serial control block
COMMTIMEOUTS timeouts =
{
// Serial port timeout Control Parameters
100, // read character interval Timeout: 100 MS
1, // time per character during read operation: 1 MS (n characters total n MS)
500, // basic (additional) read Timeout: 500 MS
1, // time of each character when writing: 1 MS (n characters total n MS)
100
}; // Basic (additional) Write Timeout: 100 MS
HComm = CreateFile (pPort, // serial port name or device path
GENERIC_READ | GENERIC_WRITE, // read/write Method
0, // share mode: exclusive
NULL, // Default Security Descriptor
OPEN_EXISTING, // Creation Method
0, // file attributes do not need to be set
NULL); // you do not need to refer to the template file.
If (hComm = INVALID_HANDLE_VALUE)
Return FALSE;
// Failed to open the serial port
SetupComm (hComm, 4096,102 4); // you can specify the size of the input/output buffer.
SetCommTimeouts (hComm, & timeouts); // set timeout
Return TRUE;
}
// Close the serial port
BOOL CloseComm ()
{
Return CloseHandle (hComm );
}
// Write the serial port
// PData: the buffer pointer of the data to be written.
// NLength: the length of the data to be written.
Void WriteComm (void * pData, int nLength)
{
DWORD dwNumWrite; // The Data Length sent by the serial port
WriteFile (hComm, pData, (DWORD) nLength, & dwNumWrite, NULL );
}
// Read the serial port
// PData: The data buffer pointer to be read
// NLength: maximum data length to be read
// Return: the actual length of data read.
Int ReadComm (void * pData, int nLength)
{
DWORD dwNumRead; // The length of data received by the serial port
ReadFile (hComm, pData, (DWORD) nLength, & dwNumRead, NULL );
Return (int) dwNumRead;
}
Edit/decode GSM Short Messages
This article only provides the prototype of the codec function. For details, see the GSM standard and the text "sending and receiving short messages through serial port.
// Return the string length after UCS2 Decoding
Int gsmDecodeUcs2 (const unsigned char * pSrc, // source encoding string pointer
Char * pDst, // pDst: Target string pointer
Int nsclength // nsclength: source encoding String Length
);
// Printable string converted to byte data return: Target Data Length
// For example, "C8329BFD0E01" --> {0xC8, 0x32, 0x9B, 0xFD, 0x0E, 0x01}
Int gsmString2Bytes (const char * pSrc, // pSrc: Source string pointer
Unsigned char * pDst, // pDst: Target Data Pointer
Int nsclength // nsclength: Source String Length
);
// Convert byte data to printable string. Return: Target String Length.
// For example, {0xC8, 0x32, 0x9B, 0xFD, 0x0E, 0x01} --> "C8329BFD0E01"
Int gsmBytes2String (const unsigned char * pSrc, // pSrc: Source Data Pointer
Char * pDst, // pDst: Target string pointer
Int nsclength // nsclength: Source Data Length
);
3. Summary
The core of serial programming lies in the control of the serial communication mode (sending, receiving, and handshaking), while the specific application field is secondary. Once you have mastered the fundamental principles, you can flexibly apply them to any field. The example "Short Message control terminal" in an integrated instance is just the tip of the iceberg.
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