Operation of the serial port in Java to achieve SMS collection __java

Source: Internet
Author: User
Tags getmessage sendmsg stringbuffer
1. Configure Comm.jar.

Comm.jar is a sub implementation of the low-level interface of the API, call the local DLL file, because Java itself does not have the ability to directly access hardware settings, are implemented by invoking the local method. It can be downloaded from the official website of Java. After downloading, the Comm.jar package is imported into the engineering classpath. Put the other two very important documents Javax.comm.properties and Win32com.dll into your engineering directory, that is, Java.user.

2. Open the serial port.

To load the Win32com.dll first before opening the string, because we did not put it under the JRE path, we had to load it ourselves explicitly.



String drivername = "Com.sun.comm.Win32Driver";
Commdriver driver = null;

Try ... {
System.loadlibrary ("win32com");
Driver = (commdriver) class.forname (drivername). newinstance ();
Driver.initialize ();
catch (instantiationexception E1) ... {
Logger.error ("1:" + e1.getmessage ());

catch (illegalaccessexception E1) ... {
Logger.error ("2:" + e1.getmessage ());

catch (ClassNotFoundException E1) ... {
Logger.error (E1.getmessage ());
}



And then get the port you specified:



After successfully opening the port, set the relevant parameters of the port, such as baud rate, data bit, parity bit and so on. This is related to the specific device, but generally the baud rate is 9600, the data bit is 8, the stop bit is 1, the parity is 0, and the flow control is off:



if (sport!= null) ... {
Logger.debug ("Serial name is:" + sport.getname ());
Try ... {
Set the parameters of the serial port
Sport.setserialportparams (9600,//baud rate
serialport.databits_8,//Number of data bits
Serialport.stopbits_1,//Stop bit
Serialport.parity_none);/parity bit
catch (Unsupportedcommoperationexception e) ... {
E.printstacktrace ();
Logger.error (E.getmessage ());
}
}


3. Initialize the port

Before you receive or send data, you also have to set some parameters. The important thing is:

At+cmgf=0 (Set modem transceiver using PDU mode, 1 for text mode.) Some modem may be just the opposite, specific reference to the modem's at instruction description)

at+cnmi=2,2,0,0,0 (Set modem automatic receive, at instruction instructions to the definition is a new short message instructions, that is to say that there is a new short message, how to give you a hint.) This setting is a message that will be automatically displayed without the need for a card reader operation. See a very online example are 1, 1, so you have to read the card operation to get a short message, very inconvenient, but also reduce the life of the SIM card

at+csmp=17,167,0,240 (Sets the short message text mode parameter.) 17 refers to the Sms-submit decimal integer expression, which is submitted, 167 refers to the integer expression of the validity period, and 0 refers to the decimal integer representation of the Protocol identity. The first three parameters are the default values for this command. The last 1240 refers to the encoding scheme, which is normally set to 240 in the text mode under the English and PDU modes. If you want to send Chinese in text mode, have more modem to set to 8.

The above initialization work on the port can be set directly in the HyperTerminal terminal. But it is best to write it in the program, the program after the start of this work, to avoid the trouble of manual operation.

To initialize the modem, you must output the above command to the modem port, but also to see if its back value is OK. To get the return value, you will be listening on the COM port. So the initialization work has three steps:

First, the Listening port


Sport.addeventlistener (this);
Sport.notifyondataavailable (TRUE);

Second, the input output stream is established, and the initialization command is exported to the COM port of modem



Initializing modem with configuration parameters
msg = Conf.initparam ();
if (msg!= null) ... {
if (Conf.modemmode ()!= null && conf.modemmode (). Equals ("0"))
if (Ispdumode)
msg = "at+cmgf=0;" + msg;
Else
msg = "at+cmgf=1;" + msg;
Sendmsg (Msg.getbytes (), sport);
Sendokflag = true;
}


Send a short message through the data cat
private void Sendmsg (byte[] msg, SerialPort Sport) ... {

DataOutputStream PW;
if (msg!= null && sport!= NULL)
Try ... {

PW = new DataOutputStream (Sport.getoutputstream ());
Pw.write (msg);

Pw.flush ();
Pw.close ();
Logger.debug ("MSG has been send from modemn:");

catch (IOException e) ... {
Logger.error (E.getmessage ());
E.printstacktrace ();
}
}

Handling serial port events heard by the listener
Public synchronized void serialevent (serialportevent ev) ... {

DataInputStream in;
int c = 0;
StringBuffer SB = null;
If a serial port event occurs
if (ev.geteventtype () = = serialportevent.data_available) ... {

Try ... {
in = new DataInputStream (Sport.getinputstream ());
SB = new StringBuffer ();
while ((c = in.read ())!=-1) ... {
Sb.append ((char) c);

System.out.println (SB);
if (Handlerecdata (SB)) ... {
Logger.debug ("Data received from Modem" + SB);
SB = new StringBuffer ();

}

}

}//try
catch (IOException e) ... {
Logger.error (E.getmessage ());
E.printstacktrace ();
}
}
}



The Serialevent event is the part that you want to work after you just added the listener. If you have written the interface program, this will be more familiar. Once the modem responds to the data, this event triggers. After we send the initialization command, we receive the data from this event to see if we can receive OK. If it is received, the initialization succeeds.

4. Send data

After successful initialization, you can send and receive normal data. We use the PDU in this way to explain, text way is a lot of modem or mobile phone do not support, two is also relatively simple, in the last mention.

First we can put the data to send in the Send buffer list, to the data one by one to send. Because the modem does not support asynchrony (my own experience), we can only send one after the other, and then send the second one. The principle of sending is the same as sending initialization commands, but it is important to note that the sending content is first PDU encoded and sent in the following format:

AT+CMGS=&LT;LENGTH&GT;&LT;CR&GT;PDU data<ctrl-z>

The length of the encoded PDU data is minus 18 and divided by 2, as for why, you can refer to the AT command manual. Some modem support directly to the above as a complete packet sent to the past (such as: Falcom series), some are very stupid (for example: Siemens tc35i), it requires that the previous at command must be sent, and so on after receiving the response ">" symbol, then send PDU DATA, Very troublesome, a bit not for our developers think: (, I just eat in this loss.) Do it by the way you used to, but you can't send it out.

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.