InputStream printing weird character - java

I am try to receive data from my Arduino using an InputStream but for some reason I get this as the output.
ààà à àà ààà a ààà à àà ààààà àààààà à àà ààà à ààà à àà ààààà àààààà à àà ààà à
This is my code for receiving data:
package midistep;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.BufferedReader;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class TwoWaySerialComm
{
public OutputStream out1;
public TwoWaySerialComm()
{
super();
}
void connect ( String portName ) throws Exception
{
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if ( portIdentifier.isCurrentlyOwned() )
{
System.out.println("Error: Port is currently in use");
}
else
{
CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
if ( commPort instanceof SerialPort )
{
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
out1=out;
(new Thread(new SerialReader(in))).start();
(new Thread(new SerialWriter(out))).start();
}
else
{
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
/** */
public static class SerialReader implements Runnable
{
InputStream in;
public SerialReader ( InputStream in )
{
this.in = in;
}
public void run ()
{
byte[] buffer = new byte[1024];
int len = -1;
try
{
while ( ( len = this.in.read(buffer)) > -1 )
{
System.out.print(new String(buffer,0,len));
}
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
/** */
public static class SerialWriter implements Runnable
{
public OutputStream out;
public SerialWriter ( OutputStream out )
{
this.out = out;
}
public void run ()
{
try
{
int c = 0;
while ( ( c = System.in.read()) > -1 )
{
this.out.write(c);
}
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
public void writetoport(int Steps) {
try {
out1.write(Steps);
out1.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main ( String[] args )
{
try
{
(new TwoWaySerialComm()).connect("COM3");
}
catch ( Exception e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And my Arduino code:
int received = 0;
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
delay(1000);
Serial.println("Hello world");
if (Serial.available() > 0) {
received = Serial.read();
if (received > 1000) {
int speed = received;
String tempstring = String(speed);
tempstring.substring(1);
speed = tempstring.toInt();
Serial.println("gotit" + speed);
}
else if (received = 1) {
Serial.print("I received something >");
Serial.print(received);
Serial.println("<");
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
digitalWrite(LED_BUILTIN, LOW);
}
}
}
Hopefully this is a simple problem. Thank you

You have set the wrong baud rate. You Java code has
serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
but in your Arduino sketch you have
Serial.begin(9600);
The baud rates must be identical else you'll get transmission errors.

Related

Read Data from PCB board Through a Serial Cable with java

Using eclipse and java how to read the data from the pcb board with a serial cable, because the data of the pcb board arrive via cable in binary format. How to save the data that will be displayed in the compiler?
Someone help me please.
Below is the code I am writing to do this, but it does not detect any port when I plug in the serial cable
import gnu.io.*;
import java.awt.Color;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.TooManyListenersException;
public class SimpleRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
public static void main(String[] args) {
boolean portFound = false;
String defaultPort ="COM 1" ;
if (args.length > 0) {
defaultPort = args[0];
}
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(defaultPort)) {
System.out.println("Found port: "+defaultPort);
portFound = true;
SimpleRead reader = new SimpleRead();
}
}
}
if (!portFound) {
System.out.println("port " + defaultPort + " not found.");
}
}
public SimpleRead() {
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException 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];
try {
while (inputStream.available() > 0)
{
int numBytes = inputStream.read(readBuffer);
System.out.print("The Read Bytes from SerialPort are");
System.out.write(readBuffer);
System.out.println();
}
System.out.print(new String(readBuffer));
} catch (IOException e) {}
break;
}
}
}
Log Result:
port COM 1 not found.
The port names don't have spaces in them. Try changing:
String defaultPort ="COM 1" ;
to:
String defaultPort ="COM1" ;

Serial Data Event Listener Java

I would be really grateful if someone could point me in the right direction
How would i go about triggering an event that is called when no data is received from the serial communication example below?
Thank you,
Maria.
public void connect(String portName) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
} else {
CommPort commPort = portIdentifier.open(this.getClass().getName(),
2000);
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
theSerialWriter = new SerialWriter(this, out);
new Thread(theSerialWriter).start();
serialPort.addEventListener(new SerialReader(this, in));
serialPort.notifyOnDataAvailable(true);
} else {
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
public void serialEvent(SerialPortEvent arg0) {
int data;
// boolean setFlagDoorLock = false ;
// if(arg0= 1){}
try {
int len = 0;
while ((data = in.read()) > -1) {
if (data == '\n') {
break;
}
buffer[len++] = (byte) data;
asHexStr = DatatypeConverter.printHexBinary(buffer);
if (asHexStr.contains("FB1")) {
// Thread.sleep(1000);
ActivateSystem = true;
if ((asHexStr.contains("FB1") && (ActivateSystem == true))) {
ActivateSystem = false;
asHexStr = "";
} else {
System.out.println("Here2");
}
}
}
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
System.out.println("Received");
}
}
public static class SerialWriter implements Runnable {
OutputStream out;
SerialPortConnector main = null;
public SerialWriter(SerialPortConnector twoWaySerialComm,
OutputStream out) {
main = twoWaySerialComm;
this.out = out;
}
public void send(String stringToSend) {
try {
int intToSend = Integer.parseInt(stringToSend);
this.out.write(intToSend);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
try {
int c = 0;
Thread.sleep(1000);
if (asHexStr == "") {
System.out.println("Here");
// ActivateSystem = false;
}
}
// catch ( IOException e )
catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}
public static void main(String[] args) {
try {
(new SerialPortConnector()).connect("COM12");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You have stated this in a comment:
I need to be able to detect that the id has stopped and after a
timeout(or after it not detecting the id a few times in a row) then
send a url call( i already have a class to send the call)-this should
only be sent once.while it is reading the id however another url call
should be sent again-once only
If I understand this right then you need to check for two different things:
The device stops at sending the ID.
The device sends a number of empty ID's.
This requirement is a kind of tricky. As I've said if no data arrives to the serial port then no serial port event will be fired. I think you can use a Timer to check the timeout and use a counter to register the number of empty ID's arrived. Something like this:
int numberOfEmptyIds = 0;
int maxNumberOfAttempts = 5;
boolean urlSent = false;
long timeoutInMillis = 10000; // let's say 10000 millis, equivalent to 10 seconds
Timer timer = null;
public void connect(String portName) throws Exception {
...
scheduleTimer();
}
public void serialEvent(SerialPortEvent evt) {
if(evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
while(in.read(buffer) > -1) {
String asHexStr = DatatypeConverter.printHexBinary(buffer);
if(asHexStr.contains("FB1")) {
scheduleTimer();
numberOfEmptyIds = 0;
} else {
numberOfEmtyIds++;
if(numberOfEmptyIds == maxNumberOfAttempts && !urlSent) {
// send the url here
}
}
}
} catch (IOException ex) {
// Log the exception here
}
}
}
private void scheduleTimer() {
if(timer != null) {
timer.cancel();
}
timer = new Timer("Timeout");
TimerTask task = new TimerTask() {
#Override
public void run() {
if(!urlSent) {
// send the url here
}
}
};
timer.schedule(task, timeoutInMillis);
}
I don't know if this is exactly what you need but hope it be helpful.

Unable to send data to XBee on Arduino

I have an XBee-PRO S1 on Arduino Uno R3 which acts like a transmitter to send data to another XBee which is acting like a receiver to turn on the LEDs connected to it. Here is what I'm doing:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import gnu.io.CommPortIdentifier;
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.OutputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;
public class NewClass implements SerialPortEventListener {
SerialPort serialPort;
OutputStream out;
private static final String PORT_NAME = "COM10"; //(XBee Transmitter)
private BufferedReader input;
private static final int TIME_OUT = 2000;
private static final int DATA_RATE = 9600;
// End of input chars
//private static final byte EOIC = 3;
public void initialize() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
//First, find an instance of serial port as set in PORT_NAME.
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
if (currPortId.getName().equals(PORT_NAME)) {
portId = currPortId;
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}
try {
serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);
serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
// Open the input stream
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
serialPort.setEndOfInputChar((byte) 3);
}
catch (PortInUseException | UnsupportedCommOperationException | IOException | TooManyListenersException e) {
System.err.println(e.toString());
}
}
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
#Override
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
char inputLine;
//dat = new ArrayList<Character>();
if (input.ready()) {
inputLine = (char) input.read();
Thread.sleep(1500);
sendChar();
}
}
catch (Exception e) {
System.err.println(e.toString());
System.out.println("Error reading");
}
}
// Ignore all the other eventTypes, but you should consider the other ones.
}
public synchronized void sendChar() {
try {
Thread.sleep(1500);
out = serialPort.getOutputStream();
System.out.println("out is not null");
for (int i = 0; i <= 900; i++) {
Thread.sleep(1500);
out.write((char) 'A');
out.flush();
System.out.println(i+") written-> A"); //For debugging
}
}
catch (InterruptedException | IOException e) {
}
}
public synchronized void cRead(char data) {
if (data != ' ') {
System.out.print(data);
//getTimestamp();
}
}
public static void main(String[] args) throws Exception {
NewClass main = new NewClass();
main.initialize();
Thread t = new Thread() {
#Override
public void run() {
//The following line will keep this application alive for 12 hours,
//waiting for events to occur and responding to them (printing
//incoming messages to console).
try {
Thread.sleep(43200000);
}
catch (InterruptedException ie) {
}
}
};
t.start();
System.out.println("Started");
}
}
One problem with this code is that, when I get some incoming signal at the COM port then only the sendChar() is called which is due to the condition if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE). Also the data is not being sent. I don't know what other event types are there because of lack of proper documentation.
What I want is to send data to Arduino without receiving anything. What am I doing wrong or missing?

Android webserver shows html pages as text

I am developing a android app which turns the android device into a multithreaded web server the code which i use do not have any error but runs fine and it can be seen through web browser but it shows the source of html file as text rather than full gui.
this is my code..
Jhtts class:
package dolphin.developers.com;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import dolphin.devlopers.com.R;
public class JHTTS extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.server);
try {
String IndexFileName = "index.htm";
File documentRootDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/");
JHTTP j = new JHTTP(documentRootDirectory, 9001, IndexFileName);
j.start();
Toast.makeText(getApplicationContext(), "Server Started!!", 5).show();
Log.d("Server Rooot", "" + documentRootDirectory);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Jhttp class:
package dolphin.developers.com;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class JHTTP extends Thread {
private File documentRootDirectory;
private String indexFileName = "index.htm";
private ServerSocket server;
private int numThreads = 50;
public JHTTP(File documentRootDirectory, int port, String indexFileName) throws IOException {
if (!documentRootDirectory.isDirectory()) {
throw new IOException(documentRootDirectory
+ " does not exist as a directory");
}
this.documentRootDirectory = documentRootDirectory;
this.indexFileName = indexFileName;
this.server = new ServerSocket(port);
}
public JHTTP(File documentRootDirectory, int port) throws IOException {
this(documentRootDirectory, port, "index.htm");
}
public JHTTP(File documentRootDirectory) throws IOException {
this(documentRootDirectory, 9001, "index.htm");
}
public void run() {
for (int i = 0; i < numThreads; i++) {
Thread t = new Thread(new RequestProcessor(documentRootDirectory, indexFileName));
t.start();
}
System.out.println("Accepting connections on port " + server.getLocalPort());
System.out.println("Document Root: " + documentRootDirectory);
while (true) {
try {
Socket request = server.accept();
request.setReuseAddress(true);
RequestProcessor.processRequest(request);
} catch (SocketException ex) {
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
RequestProcessor:
package dolphin.developers.com;
import java.net.*;
import java.io.*;
import java.util.*;
public class RequestProcessor implements Runnable {
#SuppressWarnings("rawtypes")
private static List pool = new LinkedList( );
private File documentRootDirectory;
private String indexFileName = "index.html";
public RequestProcessor(File documentRootDirectory,
String indexFileName) {
if (documentRootDirectory.isFile( )) {
throw new IllegalArgumentException(
"documentRootDirectory must be a directory, not a file");
}
this.documentRootDirectory = documentRootDirectory;
try {
this.documentRootDirectory
= documentRootDirectory.getCanonicalFile( );
}
catch (IOException ex) {
}
if (indexFileName != null) this.indexFileName = indexFileName;
}
#SuppressWarnings("unchecked")
public static void processRequest(Socket request) {
synchronized (pool) {
pool.add(pool.size( ), request);
pool.notifyAll( );
}
}
public void run( ) {
// for security checks
String root = documentRootDirectory.getPath( );
while (true) {
Socket connection;
synchronized (pool) {
while (pool.isEmpty( )) {
try {
pool.wait( );
}
catch (InterruptedException ex) {
}
}
connection = (Socket) pool.remove(0);
}
try {
String filename;
String contentType;
OutputStream raw = new BufferedOutputStream(
connection.getOutputStream( )
);
Writer out = new OutputStreamWriter(raw);
Reader in = new InputStreamReader(
new BufferedInputStream(
connection.getInputStream( )
),"ASCII"
);
StringBuffer requestLine = new StringBuffer( );
int c;
while (true) {
c = in.read( );
if (c == '\r' || c == '\n') break;
requestLine.append((char) c);
}
String get = requestLine.toString( );
// log the request
System.out.println(get);
StringTokenizer st = new StringTokenizer(get);
String method = st.nextToken( );
String version = "";
if (method.equals("GET")) {
filename = st.nextToken( );
if (filename.endsWith("/")) filename += indexFileName;
contentType = guessContentTypeFromName(filename);
if (st.hasMoreTokens( )) {
version = st.nextToken( );
}
File theFile = new File(documentRootDirectory,
filename.substring(1,filename.length( )));
if (theFile.canRead( )
// Don't let clients outside the document root
&& theFile.getCanonicalPath( ).startsWith(root)) {
DataInputStream fis = new DataInputStream(
new BufferedInputStream(
new FileInputStream(theFile)
)
);
byte[] theData = new byte[(int) theFile.length( )];
fis.readFully(theData);
fis.close( );
if (version.startsWith("HTTP ")) { // send a MIME header
out.write("HTTP/1.0 200 OK\r\n");
Date now = new Date( );
out.write("Date: " + now + "\r\n");
out.write("Server: JHTTP/1.0\r\n");
out.write("Content-length: " + theData.length + "\r\n");
out.write("Content-type: " + contentType + "\r\n\r\n");
out.flush( );
} // end if
// send the file; it may be an image or other binary data
// so use the underlying output stream
// instead of the writer
raw.write(theData);
raw.flush( );
} // end if
else { // can't find the file
if (version.startsWith("HTTP ")) { // send a MIME header
out.write("HTTP/1.0 404 File Not Found\r\n");
Date now = new Date( );
out.write("Date: " + now + "\r\n");
out.write("Server: JHTTP/1.0\r\n");
out.write("Content-type: text/html\r\n\r\n");
}
out.write("<HTML>\r\n");
out.write("<HEAD><TITLE>File Not Found</TITLE>\r\n");
out.write("</HEAD>\r\n");
out.write("<BODY>");
out.write("<H1>HTTP Error 404: File Not Found</H1>\r\n");
out.write("</BODY></HTML>\r\n");
out.flush( );
}
}
else { // method does not equal "GET"
if (version.startsWith("HTTP ")) { // send a MIME header
out.write("HTTP/1.0 501 Not Implemented\r\n");
Date now = new Date( );
out.write("Date: " + now + "\r\n");
out.write("Server: JHTTP 1.0\r\n");
out.write("Content-type: text/html\r\n\r\n");
}
out.write("<HTML>\r\n");
out.write("<HEAD><TITLE>Not Implemented</TITLE>\r\n");
out.write("</HEAD>\r\n");
out.write("<BODY>");
out.write("<H1>HTTP Error 501: Not Implemented</H1>\r\n");
out.write("</BODY></HTML>\r\n");
out.flush( );
}
}
catch (IOException ex) {
}
finally {
try {
connection.close( );
}
catch (IOException ex) {}
}
} // end while
} // end run
public static String guessContentTypeFromName(String name) {
if (name.endsWith(".html") || name.endsWith(".htm")) {
return "text/html";
}
else if (name.endsWith(".txt") || name.endsWith(".java")) {
return "text/plain";
}
else if (name.endsWith(".gif")) {
return "image/gif";
}
else if (name.endsWith(".class")) {
return "application/octet-stream";
}
else if (name.endsWith(".jpg") || name.endsWith(".jpeg")) {
return "image/jpeg";
}
else if (name.endsWith(".png") ) {
return "image/png";
}
else if (name.endsWith(".js")) {
return "text/javascript";
}
else if (name.endsWith(".js")) {
return "text/javascript";
}
else if (name.endsWith(".css")) {
return "text/css";
}
else return "text/plain";
}
} // end RequestProcessor
Please Help...

Issue writing to serial port from Java [duplicate]

This question already has answers here:
Closed 13 years ago.
Duplicate of Implementation of Xmodem Protocol in Java
I've got to implement the xmodem protocol to receive a file from a target device. For that, I have to request the file, then for every 128-byte packet received, I have to send an acknowledgment. My problem is when I open an outputstream to request the file, it will write but after that I can't write again to the outputstream. What is the problem I'm not getting?
package writeToPort;
import java.awt.Toolkit;
import java.io.*;
import java.util.*;
import javax.comm.*;
import javax.swing.JOptionPane;
import constants.Constants;
public class Flashwriter implements Runnable, SerialPortEventListener {
Enumeration portList;
CommPortIdentifier portId;
String messageString = "\r\nFLASH\r\n";
SerialPort serialPort;
OutputStream outputStream,outputStream2;
InputStream inputStream;
//Thread readThread;
String one, two;
String test = "ONLINE";
String[] dispArray = new String[1];
int i = 0;
Thread readThread;
byte[] readBufferArray;
int numBytes;
String response;
FileOutputStream out;
final int FLASH = 1, FILENAME = 2;
int number;
File winFile;
public static void main(String[] args) throws IOException {
Flashwriter sm = new Flashwriter();
sm.FlashWriteMethod();
}
public void FlashWriteMethod() throws IOException {
portList = CommPortIdentifier.getPortIdentifiers();
winFile = new File("D:\\testing\\out.FLS");
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM2")) {
// if (portId.getName().equals("/dev/term/a")) {
try {
serialPort = (SerialPort) portId.open("SimpleWriteApp",
1000);
} catch (PortInUseException e) {
}
try {
outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream();
System.out.println(" Input Stream... " + inputStream);
} catch (IOException e) {
System.out.println("IO Exception");
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
System.out.println("Tooo many Listener exception");
}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort
.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
// serialPort.disableReceiveTimeout();
// outputStream.write(messageString.getBytes());
// sendRequest("/r/n26-02-08.FLS/r/n");
number = FLASH;
sendRequest(number);
} catch (UnsupportedCommOperationException e) {
}
}
}
}
}
public void serialEvent(SerialPortEvent event) {
SerialPort port = (SerialPort) event.getSource();
switch (event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
try {
while (inputStream.available() > 0) {
numBytes = inputStream.available();
readBufferArray = new byte[numBytes];
// int readtheBytes = (int) inputStream.skip(2);
int readBytes = inputStream.read(readBufferArray);
one = new String(readBufferArray);
System.out.println("readBytes " + one);
if (one.indexOf("FLASH_") > -1 & !(one.indexOf("FLASH_F") > -1)) {
System.out.println("got message");
response = "FLASH_OK";
// JOptionPane.showMessageDialog(null,
// "ONLINE",
// "Online Dump",
// JOptionPane.INFORMATION_MESSAGE);
// Toolkit.getDefaultToolkit().beep();
// outputStream.write("\r\nONLINEr\n".getBytes());
// outputStream.flush();
// outputStream.write("/r/n26-02-08.FLS/r/n".getBytes());
number = FILENAME;
sendRequest(number);
}
out = new FileOutputStream(winFile, true);
out.write(readBufferArray);
out.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
readBufferArray = null;
// break;
}
// try {
// int c;
// while((c = inputStream.read()) != -1) {
// out.write(c);
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// // readBufferArray=null;
// break;
// }
// if (inputStream != null)
// try {
// inputStream.close();
// if (port != null) port.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
//
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
System.out.println("In run() function ");
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted Exception in run() method");
}
}
public void dispPacket(String packet) {
if (response == "FLASH_OK") {
System.out.println("disppacket " + packet);
} else {
System.out.println("No resust");
}
}
public void sendRequest(int num) {
switch (num) {
case FLASH:
try {
// outputStream = serialPort.getOutputStream();
outputStream.write("AT".getBytes());
// outputStream.write("\r\n26-02-08.FLS\r\n".getBytes());
System.out.println("Flash switch");
// outputStream.close();
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
break;
case FILENAME:
try {
//outputStream =(serialPort.getOutputStream());
outputStream.write("\r\nSUNSHINE\\06-03-09.FLS\r\n".getBytes());
System.out.println("File name");
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
Perhaps the streams are blocking.
Java nio has channels that do not block. Try using one of those.
Here's a sample of reading a file with nio. I'm not sure if the same applies for you or not.
I hope it helps.

Categories