Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- import gnu.io.*;
- import java.sql.*;
- public class trying5 implements Runnable, SerialPortEventListener {
- static Enumeration portList;
- static CommPortIdentifier portId;
- SerialPort serialPort;
- InputStream inputStream;
- Thread readThread;
- Connection con;
- public static void main(String[] args) {
- portList = CommPortIdentifier.getPortIdentifiers();
- while (portList.hasMoreElements()) {
- portId = (CommPortIdentifier) portList.nextElement();
- if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
- if (portId.getName().equals("COM3")) {
- trying5 reader = new trying5();
- }
- }
- }
- }
- public trying5() {
- try {
- serialPort = (SerialPort) portId.open("trying5Application", 2000);
- }
- catch (PortInUseException e)
- {
- System.out.println(e);
- }
- try {
- inputStream = serialPort.getInputStream();
- }
- catch (IOException e)
- {
- System.out.println(e);
- }
- try {
- serialPort.addEventListener(this);
- }
- catch (TooManyListenersException e)
- {
- System.out.println(e);
- }
- serialPort.notifyOnDataAvailable(true);
- try {
- serialPort.setSerialPortParams(9600,
- SerialPort.DATABITS_8,
- SerialPort.STOPBITS_1,
- SerialPort.PARITY_NONE);
- }
- catch (UnsupportedCommOperationException e)
- {
- System.out.println(e);
- }
- readThread = new Thread(this);
- readThread.start();
- }
- public void run() {
- try {
- Thread.sleep(20000);
- }
- catch (InterruptedException e)
- {
- System.out.println(e);
- }
- }
- 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:
- byte[] readBuffer = new byte[20];
- // print to console
- try {
- while (inputStream.available() > 0) {
- int numBytes = inputStream.read(readBuffer);
- }
- String newtuple = new String(readBuffer);
- usercon newcon = new usercon(con, newtuple);
- System.out.print(newtuple + "n");
- } catch (IOException e)
- {
- System.out.println(e);
- }
- break;
- }
- }
- }
- System.out.print(newtuple + "n");
- while (inputStream.available() > 0) {
- int numBytes = inputStream.read(readBuffer);
- }
- byte[] buf = new byte[12];
- int len = is.read(buf,0,buf.length);
- if (len != buf.length ) {
- throw new RuntimeException("the stream is closed and i failed to read enough data");
- }
Add Comment
Please, Sign In to add comment