Serialport read write in java - java

I have an application where i need to write some data to the serial port and get the response from it. Now the sequence is as follows:
Send a message to the serial port.
wait for the response
Once the response is received i have to process the message and until then nothing should happen to the application.
How should i break this problem and solve it ? I am not good in serial programming. I have tried a code but my application halts when i execute the send message. May be because i am reading the message just after sending a message. I really don't know hot to break this problem down. Do i have to start listen to the port during the application start ? Do i have to keep the port open ? Is it ok if i open the port every time i need that ? and how should i make the program wait to respond until the response message is read form the port ? Please help me solve this problem..
--EDIT--
package testConn;
import forms_helper.global_variables;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.comm.*;
import java.util.*;
/** Check each port to see if it is open. **/
public class openPort implements SerialPortEventListener {
static Enumeration portList;
static CommPortIdentifier portId;
static String messageString;
public static SerialPort serialPort;
static OutputStream outputStream;
InputStream inputStream;
static boolean outputBufferEmptyFlag = false;
public void open() {
Enumeration port_list = CommPortIdentifier.getPortIdentifiers();
while (port_list.hasMoreElements()) {
// Get the list of ports
CommPortIdentifier port_id = (CommPortIdentifier) port_list.nextElement();
if (port_id.getName().equals("/dev/ttyS1")) {
// Attempt to open it
try {
SerialPort port = (SerialPort) port_id.open("PortListOpen", 20);
System.out.println("Opened successfully");
try {
int baudRate = 9600; //
port.setSerialPortParams(
baudRate,
SerialPort.DATABITS_7,
SerialPort.STOPBITS_1,
SerialPort.PARITY_EVEN);
port.setDTR(true);
/*
port.setFlowControlMode(
SerialPort.FLOWCONTROL_NONE);
*
*/
System.out.println("properties are set");
} catch (UnsupportedCommOperationException e) {
System.out.println(e);
}
try {
//input = new SerialReader(in);
port.addEventListener(this);
System.out.println("listeners attached" + this);
} catch (TooManyListenersException e) {
System.out.println("too many listeners");
}
port.notifyOnDataAvailable(true);
//port.notifyOnOutputEmpty(true);
//sendMessage(port,"#PL");
//port.close ();
try {
inputStream = port.getInputStream();
System.out.println("inputstream" + inputStream.available());
outputStream = (OutputStream) port.getOutputStream();
} catch (IOException e) {
System.out.println(e);
}
//set the created variables to global variables
global_variables.port = port;
global_variables.inputStream = inputStream;
global_variables.outputStream = outputStream;
} catch (PortInUseException pe) {
System.out.println("Open failed");
String owner_name = port_id.getCurrentOwner();
if (owner_name == null) {
System.out.println("Port Owned by unidentified app");
} else // The owner name not returned correctly unless it is
// a Java program.
{
System.out.println(" " + owner_name);
}
}
}
}
}
public static void sendMessage(SerialPort port, String msg) {
if (port != null) {
try {
global_variables.outputStream.write(msg.getBytes());
global_variables.outputStream.flush();
try {
Thread.sleep(2000); // Be sure data is xferred before closing
System.out.println("read called");
//SimpleRead read = new SimpleRead();
//int read = global_variables.inputStream.read();
//System.out.println("read call ended"+read);
} catch (Exception e) {
}
} catch (IOException ex) {
Logger.getLogger(openPort.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void serialEvent(SerialPortEvent event) {
System.out.println(event.getEventType());
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:
System.out.println("event.getEventType()");
break;
*
*/
case SerialPortEvent.DATA_AVAILABLE:
System.out.println("inside event handler data available");
byte[] readBuffer = new byte[20];
try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
}
System.out.print(new String(readBuffer));
System.exit(1);
} catch (IOException e) {
System.out.println(e);
}
break;
}
}
}
What is wrong with this code ? I cant see the response from the terminal connected to serialport when i send a polling message. I am opening the connection at my application start and i am sending the message when a button inside my application is clicked. How do i solve the problem ??

See this wikibook, section Event Driven Serial Communication.

Previously answered question, here: How do I get Java to use the serial port in Linux?
Depending on your platform (if you are on a *NIX box) you can often get away with using stty to set the baud rate/port settings, and then simply open the /dev/tty* port with a FileInputStream/FileOutputStream. I used to have a chunk of code that did that and worked quite reliably, but now that I go looking for it it appears to have been misplaced. Sad.

Try to retryger the tx again after than the once and when keep the Rx on read for debugg the came back message from the device

Related

Java and XON XOFF serial print

I m build a java code to use xon xoff protocol to print a fiscal document with cash register Custom K3. This is the setting of this cash register.
This is the code about DriverPrinterSeriale.java
package prove;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.mcsolution.common.LoggerFactory.MyLog4J;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
public class DriverPrinterSeriale {
private SerialPort serialPort;
private OutputStream outStream;
private InputStream inStream;
public static MyLog4J log;
public DriverPrinterSeriale(String portaCOM){
log = new MyLog4J();
try {
this.connect(portaCOM);
} catch (IOException e) {
log.logStackTrace(e);
}
}
public void apriCassetto(){
try {
outStream = serialPort.getOutputStream();
//inStream = serialPort.getInputStream();
//log.information("output acquisito ");
String messageString = "a";
outStream.write(messageString.getBytes());
log.information("cassetto aperto");
} catch (Exception e) {
log.logStackTrace(e);
}
}
public void provaScontrino(String codiceDaInviare){
try {
outStream = serialPort.getOutputStream();
//inStream = serialPort.getInputStream();
log.information("output acquisito ora provo a stampare uno scontrino");
//String messageString = "j";
//outStream.write(messageString.getBytes());
//messageString = "'PANTALONE'10H1R";
//outStream.write(messageString.getBytes());
//String messageString = "\"MAGLIA. 1\"100H1R";
outStream.write(codiceDaInviare.getBytes());
//messageString = "1T";
//outStream.write(messageString.getBytes());
//messageString = "J";
//outStream.write(messageString.getBytes());
log.information("scontrino stampato ora apro il cassetto");
//apriCassetto();
} catch (Exception e) {
log.logStackTrace(e);
}
}
public void connect(String portName) throws IOException {
try {
// Obtain a CommPortIdentifier object for the port you want to open
CommPortIdentifier portId =
CommPortIdentifier.getPortIdentifier(portName);
log.information("apro porta seriale");
//System.out.println("apro porta seriale");
// Get
serialPort =
(SerialPort) portId.open("Demo application", 5000);
// Set the parameters of the connection.
setSerialPortParameters();
log.information("settaggio porta terminato");
} catch (NoSuchPortException e) {
log.logStackTrace(e);
throw new IOException(e.getMessage());
} catch (PortInUseException e) {
log.logStackTrace(e);
throw new IOException(e.getMessage());
} catch (IOException e) {
log.logStackTrace(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;
}
/**
* Sets the serial port parameters
*/
private void setSerialPortParameters() throws IOException {
int baudRate = 19200; // 57600bps
//int baudRate = 38400; // 57600bps
try {
// Set serial port to 57600bps-8N1..my favourite
serialPort.setSerialPortParams(
baudRate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE
);
log.information("settaggio porta iniziato");
serialPort.setFlowControlMode(
SerialPort.FLOWCONTROL_NONE);
log.information("settaggio porta eseguito");
} catch (UnsupportedCommOperationException ex) {
log.logStackTrace(ex);
throw new IOException("Unsupported serial port parameter");
}
}
}
This is the code to print a fiscal document:
driverSeriale = new DriverPrinterSeriale("COM3");
String rigaDaStampare = "\"Pippo"+
"\"10"+"*1"+"H1R";
driverSeriale.provaScontrino(rigaDaStampare);
I have no error but I m not able to print fiscal document. nothing comes out of the cash register
I found a copy of your printer manual located here. Page 40 lists the printer parameters supported. From your description, it seems like there is a mismatch of parameters. First, I would try setting it to something other than CUSTOM XON-XOFF and see if the printer will work with hardware flow control. That shouldn't be a problem with today's equipment and may make this work out of the box.
If you can't change to hardware flow control, then I think you need to set flowcontrol in your serial port. Here is a link to Java documentation on setFlowControlMode. From the current configuration, it appears you might want to logical or include both FLOWCONTROL_XONXOFF_IN and FLOWCONTROL_XONXOFF_OUT.

RXTX still reading data when device disconnected

I use RXTX library in java, if I write space ascii(32) to outpurstream I can get data, unless I can't get. I dont know why and it can be a problem ?
The problem is: I get data from a ohmmeter, I measure the product but when I take off probe, ohmetter display a value and then display "0.L" but I always get last data so I can't detect if ohmetter measure a product or not.
For example
02.00 OHM (coreect value) >>
125.20 OHM (while taking off probe) >>
0.L (after take off the probe)
I always get 125.20 OHM, how can I get the 0.L value ?
Any suggestions?
EDIT:
public class SerialComm {
SerialPort serialPort;
OutputStream outStream = null;
InputStream inStream = null;
public SerialComm() {
super();
}
void connect(String portName) throws Exception {
CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portName);
serialPort = (SerialPort) portId.open("gnu.io.CommPortIdentifier", 5000);
int baudRate = 9600;
serialPort.setSerialPortParams(
baudRate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(
SerialPort.FLOWCONTROL_NONE);
setSerialListener();
}
public void initIOStream() throws InterruptedException {
try {
outStream = serialPort.getOutputStream();
inStream = serialPort.getInputStream();
write();
} catch (IOException ex) {
Logger.getLogger(SerialComm.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void disconnect() {
if (serialPort != null) {
try {
outStream.close();
inStream.close();
} catch (IOException ex) {
}
serialPort.close();
}
}
public void write() throws IOException, InterruptedException {
outStream.write(32);
outStream.flush();
}
private byte[] readBuffer = new byte[400];
private void readSerial() throws InterruptedException, Exception {
try {
initIOStream();
Thread.sleep(2000);
int availableBytes = inStream.available();
if (availableBytes > 0) {
inStream.read(readBuffer, 0, availableBytes);
System.out.println("value: " + new String(readBuffer, 0, 30));
}
} catch (IOException e) {
}
}
private class SerialEventHandler implements SerialPortEventListener {
#Override
public void serialEvent(SerialPortEvent event) {
System.out.println("event.getEventType()" + event.getEventType());
switch (event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE: {
try {
readSerial();
} catch (Exception ex) {
Logger.getLogger(SerialComm.class.getName()).log(Level.SEVERE, null, ex);
}
}
break;
}
}
}
private class ReadThread implements Runnable {
#Override
public void run() {
while (true) {
try {
readSerial();
} catch (InterruptedException ex) {
Logger.getLogger(SerialComm.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(SerialComm.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public void setSerialListener() throws InterruptedException, TooManyListenersException {
new Thread(new ReadThread()).start();
}
public void setSerialEventHandler(SerialPort serialPort) throws Exception {
try {
initIOStream();
serialPort.addEventListener(new SerialEventHandler());
serialPort.notifyOnDataAvailable(true);
} catch (TooManyListenersException ex) {
System.err.println(ex.getMessage());
}
}
public static void main(String args[]) throws IOException, Exception {
SerialComm serial = new SerialComm();
serial.connect("COM3");
}
}
RXTX is designed for serial communication, the resistance that you get between serial ports is based on the internal TTL to RS232 converter on your motherboard (or usb to serial converter) and therefore is more of a hardware question.
I am guessing from your question that you are attempting to pull flow control pins up or down, this will effectively produce a voltage on the pins (and has nothing to do with resistance between pins. )
if you post a code example I can assist with any potential bugs in the code. and expected output from the serial port.
Unfortunately this is an issue which is related to the Prova 700, because the behaviour you describe is exactly the behaviour one would expect from an Ohm-meter. Basically by removing the probe from the resistor the resistance rises until it reaches a level which is not measurable by the device (the resistance of air). In this case the internal status of the device will say: We have reached infinitive resistance and will display 0.0L.
I am not 100% sure what your exact goal is with your software but I assume a workflow like this:
User attaches probes a resistor
On removal of the probes your software automatically records the data
However, as you can see this will not work out.
Please take a look into the instruction manual for the Prova 700. What exactly does the manual say about the RS-232 protocol? Other devices like this have an instruction protocol which is talked on the serial line such that you are able to send commands into the system. One could then perform a workflow like this
User attaches probes to resistor
Presses button on the computer
Computer sends a command to the Ohm-meter
Ohm-meter replies with current resistance
Computer stores resistance and shows a message that it is save to remove the probes
Hope this helps!

Read and write simultaneously on com port

My question is that isn't it possible to read and write simultaneously on one com port? This is just for demo purpose, I will only be reading a port once I press F5 key on the keyboard, but for demo purposes I was trying to read and write simultaneously but can't do it. It says that some other program is using the port.
UPDATE
package com_port;
import java.io.*;
import java.util.*;
import javax.comm.*;
public class simplerad implements Runnable, SerialPortEventListener
{
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
public static void main(String[] args) throws Exception
{
portList = CommPortIdentifier.getPortIdentifiers();
System.out.println("SimpleRead Started.");
while (portList.hasMoreElements())
{
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
System.out.println ("Found " + portId.getName());
if (portId.getName().equals("COM7"))
{
OutputStream outputStream;
SerialPort writePort = (SerialPort) portId.open("SimpleWriteApp", 2000);
writePort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
outputStream = writePort.getOutputStream();
outputStream.write("AT+CENG=2".getBytes());
System.out.println("write done");
writePort.close();
simplerad reader = new simplerad();
}
}
}
}
public simplerad()
{
try
{
System.out.println("1");
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
}
catch (PortInUseException e)
{
e.printStackTrace();
}
try
{
System.out.println("2");
inputStream = serialPort.getInputStream();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
System.out.println("3");
serialPort.addEventListener(this);
}
catch (TooManyListenersException e)
{
e.printStackTrace();
}
serialPort.notifyOnDataAvailable(true);
try
{
System.out.println("4");
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
}
catch (UnsupportedCommOperationException e)
{
e.printStackTrace();
}
readThread = new Thread(this);
readThread.start();
}
public void run()
{
System.out.println("5");
try
{
System.out.println("6");
Thread.sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public void serialEvent(SerialPortEvent event)
{
System.out.println("7");
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
{
System.out.println("8");
while (inputStream.available() > 0)
{
int numBytes = inputStream.read(readBuffer);
System.out.print(new String(readBuffer, 0, numBytes, "us-ascii"));
}
System.out.print(new String(readBuffer));
}
catch (IOException e)
{
e.printStackTrace();
}
break;
}
}
}
Why the serialEvent doesn't run?
The problem here is that you are trying to open the same COM port twice, and the answer is no, this will not work - at least the way that you are doing it here. The reason is that the underlying OS only allows one user mode handle per port.
But yes, as long as your COM port is bidirectional (most of them are) you can open a COM port and read/write to it at the same time - this is known as full duplex mode.
To get this behavior in your application you want to open your "COM7" port one time, then give your read thread access to this original object instead of trying to open it a second time. Another way is to just get your InputStream and OutputStream immediately after opening, then use these objects around the rest of your application.
I'm not sure exactly why your event listener is not firing, however your code seems a bit complex for what you are actually trying to do here. It's possible that opening/closing is causing you to miss an event notification.
Here is an example of what you should do on open, and this should be a more efficient solution than opening/closing the port in between reading and writing:
// Each of these could be object members so all your class methods have access
OutputStream outputStream;
InputStream inputStream;
SerialPort serialPort;
// Open the port one time, then init your settings
serialPort = (SerialPort)portId.open("SimpleWriteApp", 2000);
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
// Get the input/output streams for use in the application
outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream();
// Finally, add your event listener
serialPort.addEventListener(this);
NO,you cant read and write simultaneously on the same port.
Because to avoid deadlock condition.
i gone through your code and i found... in the while loop
while (portList.hasMoreElements())
{
}
the problem is with the while loop since portlist has no elememts to read.

At command shows busy when sms is Send again (in java)

import javax.comm.*;
import java.io.*;
import java.util.*;
public class Sms {
public synchronized static String main1(String arr) {
char cntrlZ=(char)26;
InputStream input = null;
OutputStream output = null;
SerialPort serialPort = null;
try {
CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM3");
serialPort = (SerialPort) portId.open("SimpleReadApp1", 2000);
//System.out.println("sdiosdfdsf");
String f=null;int n;
input = serialPort.getInputStream();
output = serialPort.getOutputStream();
Thread readThread;
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
output.write(("ATZ\r\natH\r\n+CMGW: 0\r\n+CMGW: 1\r\n").getBytes());
output.flush();Thread.sleep(200);
output.write(("ath0\r\n").getBytes());
output.flush();Thread.sleep(200);
output.write(("AT+CMGF=1\r\n").getBytes());
output.flush();Thread.sleep(200);
output.write(("AT+CMGS=\"09629993650\"\r\n+CMGW: 20\r\n").getBytes());
output.write(("hellooopssss445 545inoo you there?").getBytes());
output.write(("\032").getBytes());
output.flush();
Thread.sleep(2000);
byte[] readBuffer = new byte[120];
try {
while (input.available() > 0) {
int numBytes = input.read(readBuffer);
}
input.close();
output.close();
serialPort.removeEventListener();
serialPort.sendBreak(1000);
serialPort.getInputStream().close();
serialPort.getOutputStream().close();
if (serialPort!=null)
System.out.print("Port is not null!!!");
//serialPort.closeport();
if (serialPort!=null)
System.out.print("Port is not null!!!");
System.out.print(new String(readBuffer));
return(new String(readBuffer));
} catch (IOException e) {}
output.flush();
} catch (NoSuchPortException e) {
System.out.println("Exception in Adding Listener" + e);
} catch (PortInUseException e) {
System.out.println("Exception in Adding Listener" + e);
} catch (IOException e) {
System.out.println("Exception in Adding Listener" + e);
}
catch (InterruptedException e) {
System.out.println("Exception in Adding Listener" + e);
}
return ("fault");
}
public static void main(String[] arg) {
char ii[]=main1("").toCharArray();
for(int j=0;j<ii.length;j++)
{
if((ii[j]=='O')&&(ii[j+1]=='K'))
System.out.println("GOT");
}
}
}
When I compile and execute this program, message is not sent until I remove my Mobile from USB.And if I don't remove my Mobile and run the same program, Its shows Busy and CMI ERROR : 503.
And second message is never sent (when program is compiled again).Moreover Port is never closed as you can see in the program.
What can be done in this code? Please don't provide me some other program like SMSLIB rather improve/edit this code.
I'm trying this for about 3 days , still negative results.
Please help me.I want to send Bulk SMS without disconnecting the mobile again and again.
You must never use sleep like that; you must read and parse the response given by the modem. Sleeping like that is only marginally better then not waiting at all (which I address in this answer). See this answer for how to read and parse the response you get back.
BTW, an AT command should be terminated with only \r and not \r\n (unless you have changed S3, and you should not do that), see V.250 for more details on that and AT commands in general (e.g. if you have not already read that specification it is highly recommended).

Reading file from serial port in Java

i'm beginner in java technology, I have to read file from port. Frst I'll write "FLASH" to outputstream then I'll get response as a "FLASH_OK" from target device, after getting FLASH_OK as response then again i have to write name of the file which i want,but problem is its not writing file name to outputstream, below is my code. Please help me.
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 SerialPortEventListener {
Enumeration portList;
CommPortIdentifier portId;
String messageString = "\r\nFLASH\r\n";
SerialPort serialPort;
OutputStream outputStream;
InputStream inputStream;
Thread readThread;
String one, two;
String test = "ONLINE";
String[] dispArray = new String[1];
int i = 0;
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")) {
try {
serialPort = (SerialPort) portId.open("SimpleWriteApp",
1000);
} catch (PortInUseException e) {
}
try {
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 {
outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream();
} catch (IOException e) {
}
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort
.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
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 {
if (inputStream.available() > 0) {
numBytes = inputStream.available();
readBufferArray = new byte[numBytes];
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";
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;
}
}
public void sendRequest(int num) {
switch (num) {
case FLASH:
try {
outputStream.write(messageString.getBytes());
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
break;
case FILENAME:
try {
outputStream.write("\r\n26-02-08.FLS\r\n".getBytes());
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
Have you tested with a Serial Port Emulator software?
When I did this kind of app for college, our professor told us to build the app and test it using an emulator, since it's much cheaper and less error prone.
While searching for google you can find some softwares that do that. I don't remember exactly the one we used at that time, but it worked quite well.
I mean products like this: Eterlogic - Virtual Serial Ports Emulator, but that's just an example (and I haven't tested this software, I just googled it)
You are erroneously assuming that full messages are always going to be received. Instead, when a serial event is triggered, only part of the message may be available. For example, you may get an event and read "FLAS" and a subsequent event will give "H_OK". You need to adapt your code to something like this:
// member variables
byte [] receiveBuffer = new byte[BUFFER_LENGTH];
int receiveIndex = 0;
// Receive code
receiveIndex +=
inputStream.read(receiveBuffer, receiveIndex, BUFFER_LENGTH - receiveIndex);
Sorry I can't help you with the Java code but are you sure the data "FLASH" is
actually being sent on your serial port ? When I'm having this kind of problem I usually use an oscilloscope to look on the TX pin on the serial port and check if I can "see" the data being sent (the data burst will be brief but you will be able to see it). If you
can see it use the scope to look on the RX pin of the serial port and see if you can
see the "FLASH_OK" response actually being sent.
Nine out of ten times the problem isn't the software but a hardware issue often due to handshaking pins being incorrectly connected.
Good luck with this.

Categories