RXTX - Useful functions.
As of today March-14-2014 I've stopped using the RXTX library because we acquired a PCDuino.
Its like a small computer or tablet capable of running an OS and acting like an embedded system at the same time. I'll be using the OTG library which is contained in the GPIO to access the ports directly from the application without having to worry about serial communication problems.
Still, I found the RXTX library useful for many projects before and given that not everybody has the chance or the resources to acquire a Raspberry, PcDuino, Beaglebone or similar, I'll leave the functions used in my applications so that they can be useful for those working with RXTX and Java.
NOTE: BTW they're not mine :P
Its like a small computer or tablet capable of running an OS and acting like an embedded system at the same time. I'll be using the OTG library which is contained in the GPIO to access the ports directly from the application without having to worry about serial communication problems.
Still, I found the RXTX library useful for many projects before and given that not everybody has the chance or the resources to acquire a Raspberry, PcDuino, Beaglebone or similar, I'll leave the functions used in my applications so that they can be useful for those working with RXTX and Java.
NOTE: BTW they're not mine :P
/*
* Class uses the RXTX Library for Serial Communication
* to send, receive and encode Strings from an Arduino
*
* done by Laurid Meyer
* 28.04.2012
*
* http://www.lauridmeyer.com
*/
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import org.jfree.ui.RefineryUtilities;
public class RXTX implements SerialPortEventListener{
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyUSB0", // Linux
"COM11", // Windows
};
/** Buffered input stream from the port */
private InputStream input;
/** The output stream to the port */
private OutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private static final int DATA_RATE = 9600;
private String inputBuffer="";
public String data="";
public void initialize() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
// iterate through, looking for the port
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}else{
System.out.println("Found your Port");
}
try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(),TIME_OUT);
// set port parameters
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
// open the streams
input = serialPort.getInputStream();
output = serialPort.getOutputStream();
// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}
/**
* This should be called when you stop using the port.
* This will prevent port locking on platforms like Linux.
*/
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
/**
* This Method can be called to print a String
* to the serial connection
*/
public synchronized void sendString(String msg){
try {
msg+='\n';//add a newline character
output.write(msg.getBytes());//write it to the serial
output.flush();//refresh the serial
System.out.print("<- "+msg);//output for debugging
} catch (Exception e) {
System.err.println(e.toString());
}
}
/**
* This Method is called when a command is recieved
* and needs to be encoded
*/
private synchronized void encodeCommand(String com){
if(com.indexOf("s:")==0){//checks if the String starts with s for set
String id=com.substring(com.indexOf("s:")+2, com.indexOf(","));//remove the s, and store the "p1"
String value=com.substring(com.indexOf(",")+1, com.length());//store everything after the ","
if(id.equals("p1") && !value.equals("")){//if it's my poti1 and it sends a value
String myValue="s:s1,"+value;//set the value to my servo1
sendString(myValue);//and send it via the serial
}else{
System.out.println("not correct values");
}
}
}
/**
* This Method is called when Serialdata is recieved
*/
public synchronized void serialEvent (SerialPortEvent oEvent) {
/*if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
int available = input.available();
for(int i=0;i<available;i++){//read all incoming characters
int receivedVal=input.read();//store it into an int (because of the input.read method
if(receivedVal!=10 && receivedVal!=13){//if the character is not a new line "\n" and not a carriage return
inputBuffer+=(char)receivedVal;//store the new character into a buffer
}else if(receivedVal==10){//if it's a new line character
data = inputBuffer;
encodeCommand(inputBuffer);//call the method to encode the recieved command
inputBuffer="";//clear the buffer
}
}
} catch (Exception e) {
System.err.println(e.toString());
}
}*/
}
private class ReadThread implements Runnable {
public void run() {
while(true) {
serialRead();
}
}
}
public void setSerialListener() {
new Thread(new ReadThread()).start();
}
public void serialRead()
{
try {
int available = input.available();
for(int i=0;i<available;i++){//read all incoming characters
int receivedVal=input.read();//store it into an int (because of the input.read method
if(receivedVal!=10 && receivedVal!=13){//if the character is not a new line "\n" and not a carriage return
inputBuffer+=(char)receivedVal;//store the new character into a buffer
}else if(receivedVal==10){//if it's a new line character
System.out.println("SerialRead initiated.");
data = "";
data = inputBuffer;
System.out.println(data);
encodeCommand(inputBuffer);//call the method to encode the recieved command
inputBuffer="";//clear the buffer
}
}
} catch (Exception e) {
System.err.println(e.toString());
}
}
public static void main(String[] args) throws Exception {
RXTX main = new RXTX();
main.initialize();
System.out.println("Started");
}
}
* Class uses the RXTX Library for Serial Communication
* to send, receive and encode Strings from an Arduino
*
* done by Laurid Meyer
* 28.04.2012
*
* http://www.lauridmeyer.com
*/
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import org.jfree.ui.RefineryUtilities;
public class RXTX implements SerialPortEventListener{
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyUSB0", // Linux
"COM11", // Windows
};
/** Buffered input stream from the port */
private InputStream input;
/** The output stream to the port */
private OutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private static final int DATA_RATE = 9600;
private String inputBuffer="";
public String data="";
public void initialize() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
// iterate through, looking for the port
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}else{
System.out.println("Found your Port");
}
try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(),TIME_OUT);
// set port parameters
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
// open the streams
input = serialPort.getInputStream();
output = serialPort.getOutputStream();
// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}
/**
* This should be called when you stop using the port.
* This will prevent port locking on platforms like Linux.
*/
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
/**
* This Method can be called to print a String
* to the serial connection
*/
public synchronized void sendString(String msg){
try {
msg+='\n';//add a newline character
output.write(msg.getBytes());//write it to the serial
output.flush();//refresh the serial
System.out.print("<- "+msg);//output for debugging
} catch (Exception e) {
System.err.println(e.toString());
}
}
/**
* This Method is called when a command is recieved
* and needs to be encoded
*/
private synchronized void encodeCommand(String com){
if(com.indexOf("s:")==0){//checks if the String starts with s for set
String id=com.substring(com.indexOf("s:")+2, com.indexOf(","));//remove the s, and store the "p1"
String value=com.substring(com.indexOf(",")+1, com.length());//store everything after the ","
if(id.equals("p1") && !value.equals("")){//if it's my poti1 and it sends a value
String myValue="s:s1,"+value;//set the value to my servo1
sendString(myValue);//and send it via the serial
}else{
System.out.println("not correct values");
}
}
}
/**
* This Method is called when Serialdata is recieved
*/
public synchronized void serialEvent (SerialPortEvent oEvent) {
/*if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
int available = input.available();
for(int i=0;i<available;i++){//read all incoming characters
int receivedVal=input.read();//store it into an int (because of the input.read method
if(receivedVal!=10 && receivedVal!=13){//if the character is not a new line "\n" and not a carriage return
inputBuffer+=(char)receivedVal;//store the new character into a buffer
}else if(receivedVal==10){//if it's a new line character
data = inputBuffer;
encodeCommand(inputBuffer);//call the method to encode the recieved command
inputBuffer="";//clear the buffer
}
}
} catch (Exception e) {
System.err.println(e.toString());
}
}*/
}
private class ReadThread implements Runnable {
public void run() {
while(true) {
serialRead();
}
}
}
public void setSerialListener() {
new Thread(new ReadThread()).start();
}
public void serialRead()
{
try {
int available = input.available();
for(int i=0;i<available;i++){//read all incoming characters
int receivedVal=input.read();//store it into an int (because of the input.read method
if(receivedVal!=10 && receivedVal!=13){//if the character is not a new line "\n" and not a carriage return
inputBuffer+=(char)receivedVal;//store the new character into a buffer
}else if(receivedVal==10){//if it's a new line character
System.out.println("SerialRead initiated.");
data = "";
data = inputBuffer;
System.out.println(data);
encodeCommand(inputBuffer);//call the method to encode the recieved command
inputBuffer="";//clear the buffer
}
}
} catch (Exception e) {
System.err.println(e.toString());
}
}
public static void main(String[] args) throws Exception {
RXTX main = new RXTX();
main.initialize();
System.out.println("Started");
}
}