Serial Communication in java

Unknown | 2:23 AM |

import javax.comm.*;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

public class SerialComm implements SerialPortEventListener
{
CommPort thePort;
SerialPort myPort;
CommPortIdentifier cpi;
InputStream in;
OutputStream out;
String req,index,res1,sql,no;
String res=" ";

String s[]=new String[10];
int z=0;
public SerialComm() throws IOException
{
try
{
cpi = CommPortIdentifier.getPortIdentifier("COM36");
}
catch (NoSuchPortException e)
{
System.out.println("CPI");
}
try
{
thePort=cpi.open("mobile",30000);
myPort=(SerialPort)thePort;
}
catch (PortInUseException e)
{
System.out.println("mobile");
}
try
{
myPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
}
catch (UnsupportedCommOperationException e)
{
System.out.println("SetParam");
}
try
{
in=thePort.getInputStream();
}
catch (Exception e)
{
myPort.close();
System.out.println("InputStream");
}
try
{
out=thePort.getOutputStream();
}
catch (Exception e)
{
myPort.close();
System.out.println("outputStream");

}
try
{
myPort.notifyOnDataAvailable(true);
myPort.notifyOnBreakInterrupt(true);
}
catch (Exception e)
{
System.out.println("DATA avail");
}
try
{
myPort.enableReceiveTimeout(30);
}
catch (UnsupportedCommOperationException e)
{
System.out.println("enable receive");
}
try
{
myPort.addEventListener(this);
}
catch (Exception e)
{
System.out.println("ADD EVENT LISTEN");
}

System.out.println("Opened COM1");

}

public void serialEvent(SerialPortEvent ev)
{

StringBuffer inputBuffer = new StringBuffer();
int newData = 0;
int c=0,dat=0;
char h=0;

switch(ev.getEventType())
{
case SerialPortEvent.DATA_AVAILABLE:
try
{
byte[] b2 = new byte[9];
in.read(b2);

dat = in.read();

dat = dat << 8;

dat += in.read();




closePort();

System.out.println("Closed");

}catch (Exception e)
{
System.out.println("NEWDATA");
System.out.println(e);
return;
}
break;
case SerialPortEvent.BI:System.out.println(" Received Break ");
break;
}
}


class CloseThread extends Thread
{
@Override
public void run()
{
myPort.removeEventListener();
myPort.close();
}
}


public void closePort()
{

try
{
if (myPort != null)
{

myPort.getInputStream().close();
myPort.getOutputStream().close();
new CloseThread().start();

}

}
catch (Exception e) {}
}

}

Category:

About http://dotnetvisual.blogspot.in/:
DOT NET TO ASP.NET is a web application framework marketed by Microsoft that programmers can use to build dynamic web sites, web applications and web services. It is part of Microsoft's .NET platform and is the successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Runtime, allowing programmers to write ASP.NET code using any Microsoft .NET language. create an application very easily ....