Code:
public class ArduinoConnection 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
"COM3", // Windows
};
/** the maximum number of previous datapoints to store in memory */
private static final int MAX_DATAPOINTS = 500;
/** The delimiter used between milliseconds and units */
private static final String SERIAL_DELIMITER = ":";
/** 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;
/** Reference to main window's serial data display **/
private JTextArea ta_dataText;
/** Array to temporarily hold incoming serial data **/
private byte[] b_tempData;
/** current position of data being read into b_tempData **/
private int i_tempDataPos;
/** Array to hold data points **/
private String[] s_dataStore;
/** Temporarily hold String Array data for splitting string **/
private String[] s_temp;
/** stores the current data point position in the array **/
private int i_dataPos;
/** stores the last read data point array position **/
private int i_lastRead;
public ArduinoConnection(JTextArea ta) {
ta_dataText = ta;
b_tempData = new byte[50];
i_tempDataPos = 0;
//initialize position and array size for data points
s_dataStore = new String[MAX_DATAPOINTS];
i_dataPos = 0;
i_lastRead = 0;
}
public void open() {
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;
}
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);
System.out.println("ArduinoConnection | Connected to Serial");
} 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();
System.out.println("ArduinoConnection | Disconnected from Serial");
}
}
/**
* Handle an event on the serial port. Read the data and store it.
*/
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
int available = input.available();
final byte chunk[] = new byte[available];
int numRead = input.read(chunk, 0, available);
//copy this chunk onto the end of temp data store
System.arraycopy(chunk, 0, this.b_tempData, this.i_tempDataPos, numRead);
//move temp data position
this.i_tempDataPos += numRead;
String currentData = new String(b_tempData);
//If end of line has been reached save this data point and reset to read next point
if(currentData.contains("\r\n")) {
s_temp = currentData.split("\r\n");
//store data
this.s_dataStore[this.i_dataPos] = s_temp[0];
System.out.println("Data Point Stored = " + this.s_dataStore[this.i_dataPos]);
//increment data point
this.i_dataPos++;
//shift any characters after the \r\n in tempData to the beginning and set new position
if(s_temp.length>1) {
//remove any whitespace before checking length of overflow chars
s_temp[1] = s_temp[1].trim();
if(s_temp[1].length()>0) {
for(int x = 0; x< s_temp[1].length(); x++) {
this.b_tempData[x] = (byte)(s_temp[1].charAt(x));
}
//set buffer position
this.i_tempDataPos = s_temp[1].length();
} else {
//reset buffer data
this.resetBuffer();
}
} else {
//reset buffer
this.resetBuffer();
}
}
//avoid gui synchronization issues on the data area update
try {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
//Append data to textarea on main app window
ta_dataText.append(new String(chunk)+"|");
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
System.err.println("Err:"+e.toString());
}
}
}
/** reset the b_tempData buffer array **/
private void resetBuffer() {
this.i_tempDataPos = 0;
this.b_tempData = new byte[MAX_DATAPOINTS];
}
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
"COM3", // Windows
};
/** the maximum number of previous datapoints to store in memory */
private static final int MAX_DATAPOINTS = 500;
/** The delimiter used between milliseconds and units */
private static final String SERIAL_DELIMITER = ":";
/** 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;
/** Reference to main window's serial data display **/
private JTextArea ta_dataText;
/** Array to temporarily hold incoming serial data **/
private byte[] b_tempData;
/** current position of data being read into b_tempData **/
private int i_tempDataPos;
/** Array to hold data points **/
private String[] s_dataStore;
/** Temporarily hold String Array data for splitting string **/
private String[] s_temp;
/** stores the current data point position in the array **/
private int i_dataPos;
/** stores the last read data point array position **/
private int i_lastRead;
public ArduinoConnection(JTextArea ta) {
ta_dataText = ta;
b_tempData = new byte[50];
i_tempDataPos = 0;
//initialize position and array size for data points
s_dataStore = new String[MAX_DATAPOINTS];
i_dataPos = 0;
i_lastRead = 0;
}
public void open() {
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;
}
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);
System.out.println("ArduinoConnection | Connected to Serial");
} 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();
System.out.println("ArduinoConnection | Disconnected from Serial");
}
}
/**
* Handle an event on the serial port. Read the data and store it.
*/
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
int available = input.available();
final byte chunk[] = new byte[available];
int numRead = input.read(chunk, 0, available);
//copy this chunk onto the end of temp data store
System.arraycopy(chunk, 0, this.b_tempData, this.i_tempDataPos, numRead);
//move temp data position
this.i_tempDataPos += numRead;
String currentData = new String(b_tempData);
//If end of line has been reached save this data point and reset to read next point
if(currentData.contains("\r\n")) {
s_temp = currentData.split("\r\n");
//store data
this.s_dataStore[this.i_dataPos] = s_temp[0];
System.out.println("Data Point Stored = " + this.s_dataStore[this.i_dataPos]);
//increment data point
this.i_dataPos++;
//shift any characters after the \r\n in tempData to the beginning and set new position
if(s_temp.length>1) {
//remove any whitespace before checking length of overflow chars
s_temp[1] = s_temp[1].trim();
if(s_temp[1].length()>0) {
for(int x = 0; x< s_temp[1].length(); x++) {
this.b_tempData[x] = (byte)(s_temp[1].charAt(x));
}
//set buffer position
this.i_tempDataPos = s_temp[1].length();
} else {
//reset buffer data
this.resetBuffer();
}
} else {
//reset buffer
this.resetBuffer();
}
}
//avoid gui synchronization issues on the data area update
try {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
//Append data to textarea on main app window
ta_dataText.append(new String(chunk)+"|");
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
System.err.println("Err:"+e.toString());
}
}
}
/** reset the b_tempData buffer array **/
private void resetBuffer() {
this.i_tempDataPos = 0;
this.b_tempData = new byte[MAX_DATAPOINTS];
}