Java Serial Communication Instance-

Source: Internet
Author: User
Package Com.yuan;


Import Gnu.io.CommPortIdentifier;
Import gnu.io.NoSuchPortException;
Import Gnu.io.SerialPort;
Import gnu.io.SerialPortEvent;
Import Gnu.io.SerialPortEventListener;


Import Java.io.DataInputStream;
Import java.io.IOException;
Import Java.io.OutputStream;
Import Java.text.SimpleDateFormat;
Import java.util.TooManyListenersException;


public class Serialcomm implements Serialporteventlistener, Runnable {
Public final static String Port_ower = "Monitorapp";
Private Boolean IsOpen;
Private Boolean Isstart;
Private Boolean Issave;
Private Boolean isprint;
Private Thread Readthread;
Private String PortName;
Private String portaddress;
Private Commportidentifier Portid;
Private SerialPort SerialPort;
Private DataInputStream InputStream;
Private OutputStream OutputStream;
Private SimpleDateFormat formatter;
Private String Dataprotocol;
Private Object Readewritelock = new Object ();
Public Serialcomm () {
This.isopen = false;
This.isstart = false;
This.issave = true;
This.isprint = false;
Formatter = new SimpleDateFormat ("[Yyyy-mm-dd hh:mm:ss,sss]");
PortName = "COM1";
portaddress = "local";
Dataprotocol = "Gooseli";
}
public void Init (String port,string protocol) throws exception{
This.portname = port;
this.portaddress = PortName;
This.dataprotocol = protocol;
Init ();
}
public void init (String port,string address,string protocol) throws exception{
This.portname = port;
this.portaddress = address;
This.dataprotocol = protocol;
}
public void Init () throws ioexception,exception{
if (IsOpen) {
Close ();
}
try{
Portid = Commportidentifier.getportidentifier (portname);
SerialPort = (serialPort) portid.open (port_ower,2000);
InputStream = new DataInputStream (Serialport.getinputstream ());
OutputStream = Serialport.getoutputstream ();
IsOpen = true;
}catch (Nosuchportexception ex) {
throw new Exception (ex.tostring ());
}
}
public void Start () throws exception{
if (!isopen) {
throw new Exception (PortName + "has not bean opened!");
}
try{
Readthread = new Thread (this);
Readthread.start ();
Serialport.notifyondataavailable (TRUE);
Serialport.addeventlistener (this);
Isstart = true;
catch (Toomanylistenersexception ex) {
throw new Exception (ex.tostring ());
}
}
private void Close () {
Stop ();
if (IsOpen) {
try{
Inputstream.close ();
Outputstream.close ();
Serialport.close ();
IsOpen = false;
}catch (IOException ex) {
}
}
}
public void Serialevent (Serialportevent event) {
Switch (Event.geteventtype ()) {
Case SERIALPORTEVENT.BI:
Case Serialportevent.oe:
Case SERIALPORTEVENT.FE:
Case SERIALPORTEVENT.PE:
Case SERIALPORTEVENT.CD:
Case Serialportevent.cts:
Case SERIALPORTEVENT.DSR:
Case Serialportevent.ri:
Case Serialportevent.output_buffer_empty:
Break
Case serialportevent.data_available://reads data when there is data available and returns data to the serial port
Readcomm ();
/*byte[] Readbuffer = new BYTE[20];
try {
while (inputstream.available () > 0) {
System.out.println (Inputstream.available ());
int numbytes = Inputstream.read (Readbuffer);
System.out.println (numbytes);
}
data = new String (readbuffer). Trim ();
System.out.println (New String (Readbuffer). Trim ());
catch (IOException e) {
E.fillinstacktrace ();
}*/
Break
Default:break;
}

}


private void Readcomm () {
byte[] Readbuffer = new BYTE[20];
try {
while (inputstream.available () > 0) {
System.out.println (Inputstream.available ());
int numbytes = Inputstream.read (Readbuffer);
}
data = new String (readbuffer). Trim ();
System.out.println (New String (Readbuffer). Trim ());
catch (IOException e) {
E.fillinstacktrace ();
}
/*stringbuffer Readbuffer = new StringBuffer ();
String scannedinput = "";
Date currenttime = null;
String TimeStamp = "";
int C;
Char A;
try {
InputStreamReader fis = new InputStreamReader (InputStream, "utf-8");
while ((C=fis.read ())!=-1) {
Readbuffer.append ((char) c);
}
Scannedinput = readbuffer.tostring (). Trim ();
CurrentTime = new Date ();
TimeStamp = Formatter.format (currenttime);
catch (IOException ex) {
Ex.printstacktrace ();
catch (Exception Exx) {
Exx.printstacktrace ();
}*/
}
public void Run () {
/*while (True) {
try {
Thread.Sleep (2000);
catch (Interruptedexception e) {
E.printstacktrace ();
}
String at = "Test";
Writecomm (at);
Isprint = true;
}*/
/*string at = "at^hcmgr=1\r";
String strtemp = at+ (char) integer.parseint ("la") + "Z";
Writecomm (strtemp);
}
private void Writecomm (String outstring) {
Synchronized (Readewritelock) {
try{
Outputstream.write (Outstring.getbytes ());
catch (IOException ex) {
Ex.printstacktrace ();
}
}
}
public void Stop () {
if (Isstart) {
Serialport.notifyondataavailable (FALSE);
Serialport.removeeventlistener ();
Isstart =false;
}
}
public static void Main (string[] args) {
Serialcomm Serialcomm = new Serialcomm ();
try {
Serialcomm.init ("COM2", "Air");
Serialcomm.start ();
catch (Exception e) {
E.printstacktrace ();
}
}
}
Related Article

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.