Embedded Freaks..

August 29, 2008

RXTX Loopback Test Program(2)

Filed under: java — Tags: , — kunilkuda @ 5:56 pm

This second loopback program is to test RXTX’s serial event (data available event). Note that you need serial loopback to use this source code.

import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.TooManyListenersException;

public class LoopbackEventTest {

private SerialPort serialPort;
private OutputStream outStream;
private InputStream inStream;

public void connect(String portName) throws IOException {
try {
// Obtain a CommPortIdentifier object for the port you want to open
CommPortIdentifier portId =
CommPortIdentifier.getPortIdentifier(portName);

// Get the port’s ownership
serialPort =
(SerialPort) portId.open(“Demo application”, 5000);

// Set the parameters of the connection.
setSerialPortParameters();

// Open the input and output streams for the connection.
// If they won’t open, close the port before throwing an
// exception.
outStream = serialPort.getOutputStream();
inStream = serialPort.getInputStream();
} catch (NoSuchPortException e) {
throw new IOException(e.getMessage());
} catch (PortInUseException e) {
throw new IOException(e.getMessage());
} catch (IOException e) {
serialPort.close();
throw e;
}
}

/**
* Get the serial port input stream
* @return The serial port input stream
*/
public InputStream getSerialInputStream() {
return inStream;
}

/**
* Get the serial port output stream
* @return The serial port output stream
*/
public OutputStream getSerialOutputStream() {
return outStream;
}

/**
* Register event handler for data available event
*
* @param eventHandler Event handler
*/
public void addDataAvailableEventHandler(
SerialPortEventListener eventHandler) {
try {
// Add the serial port event listener
serialPort.addEventListener(eventHandler);
serialPort.notifyOnDataAvailable(true);
} catch (TooManyListenersException ex) {
System.err.println(ex.getMessage());
}
}

/**
* Disconnect the serial port
*/
public void disconnect() {
if (serialPort != null) {
try {
// close the i/o streams.
outStream.close();
inStream.close();
} catch (IOException ex) {
// don’t care
}
// Close the port.
serialPort.close();
}
}

/**
* Sets the serial port parameters to 57600bps-8N1
*/
private void setSerialPortParameters() throws IOException {
int baudRate = 57600; // 57600bps

try {
// Set serial port to 57600bps-8N1..my favourite
serialPort.setSerialPortParams(
baudRate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);

serialPort.setFlowControlMode(
SerialPort.FLOWCONTROL_NONE);
} catch (UnsupportedCommOperationException ex) {
throw new IOException(“Unsupported serial port parameter”);
}
}

public static class SerialEventHandler implements SerialPortEventListener {

private InputStream inStream;
private int readBufferLen;
private int readBufferOffset;
private byte[] readBuffer;

public SerialEventHandler(InputStream inStream, int readBufferLen) {
this.inStream = inStream;
this.readBufferLen = readBufferLen;
readBuffer = new byte[readBufferLen];
}

public boolean isBufferFull() {
return (readBufferOffset == readBufferLen);
}

public String getReadBuffer() {
return new String(readBuffer);
}

public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
readSerial();
break;
}
}

private void readSerial() {
try {
int availableBytes = inStream.available();
if (availableBytes > 0) {
// Read the serial port
readBufferOffset +=
inStream.read(readBuffer, readBufferOffset,
availableBytes);
}
} catch (IOException e) {
}
}

public static void main(String[] args) {
// Timeout = 1s
final int TIMEOUT_VALUE = 10000;

LoopbackTest loopbackTest = new LoopbackTest();
try {
// Open serial port
loopbackTest.connect(“/dev/ttyUSB0”);

// Register the serial event handler
String testString = “The quick brown fox jumps over ” +
“the lazy dog”;
InputStream inStream =
loopbackTest.getSerialInputStream();

SerialEventHandler serialEventHandler =
new SerialEventHandler(inStream, testString.length());
loopbackTest.addDataAvailableEventHandler(serialEventHandler);

// Send the testing string
OutputStream outStream =
loopbackTest.getSerialOutputStream();
outStream.write(testString.getBytes());

// Wait until all the data is received
long startTime = System.currentTimeMillis();
long elapsedTime;
do {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
elapsedTime = System.currentTimeMillis() – startTime;
} while ((elapsedTime < TIMEOUT_VALUE) && (!serialEventHandler.isBufferFull())); // Check the data if not TIMEOUT if (elapsedTime < TIMEOUT_VALUE) { if (testString.equals(serialEventHandler.getReadBuffer())) { System.out.println("All data is received successfully"); } else { System.out.println("Test failed"); System.out.println("Sent:" + testString); System.out.println("Received:" + serialEventHandler.getReadBuffer()); } } else { System.err.println("Timeout"); } System.out.println("Test done"); loopbackTest.disconnect(); } catch (IOException ex) { System.err.println(ex.getMessage()); } } } } [/sourcecode] If everything is okay, the data that's received should be the same as the data that's sent (“The quick brown fox jumps over the lazy dog”). If it’s jumbled than it’s not okay.

For me, using Linux 2.6 SuSE SLED 10, Java 5, and RXTX 2.1.7, everything is normal (the data is not jumbled). Please post comment if it doesn’t work for you.

Advertisements

4 Comments »

  1. Hi, thanks for the example,
    I’ve tried this on windows XP and the test fail, it’s giving timeout, I’ve tried to increase the time for waiting but the same, thanks for any help.

    Comment by Lorin — December 16, 2008 @ 8:47 pm

  2. Sorry, I’m not familiar with Windows environment, but I think you should check the port (Is it the correct port ? Is the port name in the program is correct ? Coz Windows don’t use /dev/ttyXX). Check with hyperterminal first to see whether your loopback works and your serial port is correct.

    Comment by kunilkuda — December 17, 2008 @ 9:44 am

  3. 3 years later still works (using windows xp). Thank you very much, god bless you!
    greetings from catalonia 😉
    Martí

    Comment by Martí — December 14, 2011 @ 6:21 pm

  4. Thanks Marti. I’m no longer using this blog, but thanks a lot for your wish. Have a blessed week too =)

    Comment by kunilkuda — December 15, 2011 @ 10:06 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: