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!
Related
I'm currently writing a client-server application where data should be transferred to the server to process the data. For building the connection I use ServerSocket and Socket and for sending the data I use OutputStream + ObjectOutputStream on the client-side and InputStream + ObjectInputStream on the server-side. The connection is currently running on localhost.
The object I try to transfer is a serializable class that only contains String parameters.
The problem I'm facing now is that readObject() immediately throws an EOFException as soon as the OutputStreams of the client are initialized (which leads to an initialization of the InputStreams of the server at the same time) instead of waiting for input from the client.
I send the data from the client using this code:
public void send(DataSet dataSet) {
if (!clientStreamsEstablished) {
initiateClientStreams();
}
try {
out.writeObject(dataSet);
} catch (IOException e) {
e.printStackTrace();
}
}
This method is only called when I hit the "submit"-button in the UI so it will not be executed on start of the application.
The data is currently (already tried a ton of other approaches with and without while() loop etc., etc.) read on the server using this method:
private void waitForInput(ObjectInputStream in, InputStream listeningPort) {
boolean dataReceived = false;
DataSet dataSet = null;
System.out.println("waiting ...");
while (!dataReceived) {
try {
Object temp = in.readObject(); // <-- EOFException is thrown here
boolean test = false;
if (temp instanceof DataSet) {
dataSet = (DataSet) temp;
}
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
break;
}
}
System.out.println("Test 2: " + dataSet.toString());
if (dataReceived) {
waitForInput(in, listeningPort);
}
}
As soon as the client thread on the server reaches this line (see code-comment above) I get this stacktrace:
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2626)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1321)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373)
at com.labdashboardserver.ClientThread.waitForInput(ClientThread.java:53)
at com.labdashboardserver.ClientThread.run(ClientThread.java:43)
Exception in thread "Thread-2" java.lang.NullPointerException
at com.labdashboardserver.ClientThread.waitForInput(ClientThread.java:65)
at com.labdashboardserver.ClientThread.run(ClientThread.java:43)
The reason for the second part of the stacktrace containing the NullPointerException is apparent as due to the EOFExcpetion the dataSet never is initialized.
However from my point of view readObject() should block and wait for the client to send ANY data before starting to read it and throw an EOF. I feel like I read through half of Stack Overflow and other forums searching for an answer but the articles I found only discuss reading files or only immediate temporary streams which are closed afterwards.
Edit
I initialize the connection before calling the UI in my main method:
public static void main(String[] args) {
connector = new LabConnector();
connector.run();
if (connector.getConnectionEstablished()) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new LabUI();
frame.setVisible(true);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,
"Error Message:\n" + e.getMessage() + "\nProgram shutting down!", "Critical Error", 0);
}
}
});
}
While in the LabConnector class I initialize the streams and connection like this:
public void run() {
try {
establishConnection();
} catch (UnknownHostException e) {
retryConnection(e);
} catch (IOException e) {
retryConnection(e);
}
if (connectionEstablished) {
initiateClientStreams();
}
}
private void establishConnection() throws UnknownHostException, IOException {
client = new Socket(HOST_IP_ADRESS, HOST_PORT);
JOptionPane.showMessageDialog(null, "Connected to Server!");
connectionEstablished = true;
}
private void initiateClientStreams() {
try {
sendingPort = client.getOutputStream();
out = new ObjectOutputStream(sendingPort);
clientStreamsEstablished = true;
} catch (IOException e) {
e.printStackTrace();
}
}
I have a method that write the content of a file to a serial port and then awaits the acknowledgement message. i am trying to use an even listener however no message are printed back to the console.
however, when i read the message with out the event listener, manually in a slow pace, the messages comes back just fine.
here is my code:
public class portConnector {
private static SerialPort SP;
public portConnector(String pName){
SP = new SerialPort(pName);
}
public static byte[] read(String name) throws IOException{
File file = new File(name);
byte[] bytes = new byte[(int) file.length()];
FileInputStream inputStream = new FileInputStream(file);
inputStream.read(bytes);
inputStream.close();
return bytes;
}
public void push2rec (File[] LOF){
try {
SP.openPort();
SP.setParams(SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
int mask = SerialPort.MASK_RXCHAR;
SP.setEventsMask(mask);
SP.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR);
for (File f : LOF){
byte[] rd = read(f.getName());
SP.writeBytes(rd);
}
SP.closePort();
}
catch (SerialPortException ex) {System.out.println(ex);}
catch (IOException ex) {System.out.println(ex);}
}
private static class PortReader implements SerialPortEventListener {
#Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() == 10) {
try {
byte[] buffer = SP.readBytes(10);
for (byte b : buffer){
System.out.format("%02X ", b);
}
System.out.println("");
}
catch (SerialPortException ex) {
System.out.println("Error in receiving string from COM-port: " + ex);
}
}
}}}
is the "addEventListener" located in the right place?
can anyone help me with this problem.
any help would be appreciated. thank you.
The first time your serial receive event fires it will most likely only have one character since thousands of instructions execute in a single character time.
You need to capture the characters into a buffer variable with each event until you have the 10 characters your are looking for.
You also have to synchronize the receive event with the first character sent. That is why most serial communication is terminated with a CR or some other known character.
I started learning networking with the main networking package in JDK, it's pretty simple and easy after a few examples. But now I am interested into making multi-client applications like a chat system.
My structure idea so far is like this:
Connection handler class, which handles incoming connections, and holds the list of clients.
If new connection was found, create a new client object, start it's thread (Client object will implement runnable, so it will start it's own looping service, it will loop for new packets received), and add it to the list.
I create a new thread for each client instead of looping through all clients because the reading from client process stops the whole execution and will wait for the client to send data, which is kinda annoys me and this is my issue there.
I have created a simple console app that receives messages from the client, but now I want to detect disconnections. I read that bufferedReader .read() method returns -1 if user is not connected, so I thought I could loop and do that every number of seconds to every client, but the thing is, the client must send a packet in order to .read() it, so let's say if you do .read() it will wait & stop the whole thread until packet is received, (I think).
This is my current code which gets messages from client:
public boolean isConnected() {
try {
this.in.read();
this.lastCheck = System.currentTimeMillis();
return true;
} catch (IOException e) {
if (!inConnection()) {
System.out.println("User disconnected");
try {
this.destruct();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return false;
}
private boolean inConnection() {
return System.currentTimeMillis() - lastCheck < this.maxTime;
}
public void startClientService() throws IOException {
while(!this.session.isClosed()) {
if (System.currentTimeMillis() - this.checkTime > 600) {
System.out.println(System.currentTimeMillis() - this.checkTime);
if (this.isConnected()) {
int packetType = this.dataIn.readInt();
packets.getPacket(packetType);
}
}
}
}
public void destruct() throws IOException {
this.session.close();
this.connection.removeClient(this);
System.out.println("Session killed");
}
Basically what happens here, I am sending a integer packed from the client, I might have many things to do so therefore I can set many unique packet ID's, so if I want to receive and process a chat message, the packet id is 216, the client sends a int 216, server reads the packet, enters the switch loop of all packet ids and detects if its really 216, if yes it gets the instance of the packed class that handles messages & gets the bytes of the received message like this:
public class Chat implements Packet {
#Override
public void processPacket(Session c) {
String message = readMessage(c);
System.out.println("Message: " + message);
}
private String readMessage(Session c) {
byte[] data = c.readBytes();
String message = null;
try {
message = new String(data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return message;
}
}
And this is how I read bytes:
public byte[] readBytes() {
int len;
byte[] data = null;
try {
len = this.dataIn.readInt();
data = new byte[len];
if (len > 0) {
this.dataIn.readFully(data);
}
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
Okay my problem:
after adding the is disconnected detection, when I send my message, nothing happens. This is probably due to the .read() it stops and is waiting for a response. BUT if I write a message again, I will get the message in server.
This is my temporary, ugly client:
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("127.0.0.1", 43594);
Scanner r = new Scanner(System.in);
PrintWriter out = new PrintWriter(socket.getOutputStream());
String input;
while(true) {
input = r.next();
if (input != null) {
sendMessage(input, out);
}
}
}
public static void sendMessage(String message, PrintWriter out) {
byte[] encoded = encode(message);
out.write(0);
out.println(encoded + "\n");
out.flush();
}
public static byte[] encode(String s) {
return DatatypeConverter.parseBase64Binary(s);
}
public static String decode(byte[] s) {
return DatatypeConverter.printBase64Binary(s);
}
}
My question is: What is a better way of reading data from client without making the application wait for it and actually loop everytime? OR maybe should I have a new thread for checking if user is online so it's 2 threads per 1 client?
If someone needs my session object (client object):
public class Session extends Thread implements Runnable {
private Socket session;
private Client client;
private PrintWriter out;
private BufferedReader in;
private PacketHandler packets;
private DataInputStream dataIn;
private ConnectionHandler connection;
private final int checkTime = 1600;
private final int maxTime = 22000;
private long lastCheck;
public Session(Socket session) {
this.session = session;
this.client = new Client(this);
try {
this.setStream();
} catch (IOException e) {
e.printStackTrace();
}
this.packets = new PacketHandler(this);
System.out.println("[New session created]: " + session.getRemoteSocketAddress());
}
public void setConnectionHandler(ConnectionHandler c) {
this.connection = c;
}
public void run() {
try {
this.startClientService();
} catch (IOException e) {
e.printStackTrace();
}
}
public void setStream() throws IOException {
this.out = new PrintWriter(this.session.getOutputStream());
this.in = new BufferedReader(new InputStreamReader(this.session.getInputStream()));
this.dataIn = new DataInputStream(this.session.getInputStream());
}
public Client getClient() {
return this.client;
}
public byte[] readBytes() {
int len;
byte[] data = null;
try {
len = this.dataIn.readInt();
data = new byte[len];
if (len > 0) {
this.dataIn.readFully(data);
}
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
public String readMessage() {
try {
return this.in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public boolean isConnected() {
try {
this.in.read();
this.lastCheck = System.currentTimeMillis();
return true;
} catch (IOException e) {
if (!inConnection()) {
System.out.println("User disconnected");
try {
this.destruct();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return false;
}
private boolean inConnection() {
return System.currentTimeMillis() - lastCheck < this.maxTime;
}
public void startClientService() throws IOException {
while(!this.session.isClosed()) {
if (System.currentTimeMillis() - this.checkTime > 600) {
System.out.println(System.currentTimeMillis() - this.checkTime);
if (this.isConnected()) {
int packetType = this.dataIn.readInt();
packets.getPacket(packetType);
}
}
}
}
public void destruct() throws IOException {
this.session.close();
this.connection.removeClient(this);
System.out.println("Session killed");
}
}
Thanks!
While I don't have time to look over all the code, here are two things that could help you out.
1) Use a defined message header. Define X number of bytes of each message that the client will send to the server. Use these bytes to define how long the message will be, and what type of message it is. The server knows the length and layout of this header, and uses it to process the message in a particular way. Example could be a header of one byte. A value of 1 could be a I'm connected message. 2 could be I'm about to disconnect. 3 could be I'm currently away, and 4 could be an incoming chat message.
2) There are 2 ways you can handle the input. First is to use blocking IO, and create a separate thread to receive messages from each client. I believe this is what you are currently doing. The second is to use non-blocking IO, and have a separate thread iterate over the open sockets and do a read. Non-blocking will check if there is data to read, but if there is not, the thread will continue executing.
I'm working on a game that uses local area network. Like most of multiplayer games, there is a server-client system. Computer A runs an instance of program, creates a server and wait; Computer B do the same thing. Now Computer C runs the program, what I want is that he can see computer A and B listed there as game servers. How can I do this?
In order to list all of the servers available, a simple solution might be this: I need to check all of the IP addresses in a particular range and see if they respond via my specific port or not. If yes, therefor an instance of game is running on it and should be listed in the servers list.
Is the solution described above a good one?
I've searched and get this piece of code:
public void checkHosts(String subnet){
int timeout=1000;
for (int i=1;i<254;i++){
String host=subnet + "." + i;
if (InetAddress.getByName(host).isReachable(timeout)){
System.out.println(host + " is reachable");
}
}
}
but is takes so much time and is useless.
If it's not the right solution, what are some other ways?
If you are running on a local network, your method might take a huge amount of time and is definitely not the best solution.
You can solve it by having your servers periodically broadcast their addresses in the network, and have all the clients listen for it. A good example can be found in the Java Tutorials.
Send a discover message using either:
a multicast (use java.netMulticast socket)
broadcast (use java.net.DatagramSocket) to the networks broadcast address
Have all servers listen for that and reply saying "I'm here" and possibly more information for further connection setup (server name, version, use port x, udp or tcp etc)
The best way to do this is with something like ZeroConf ( also known as Bonjour ).
This is what Apple uses for all its network discovery in iTunes and iOS devices so that they can find each other.
I have implemented it Linux, Windows and OSX in server side applications with great success.
And there is great support in all the major relevant languages as well.
There is no need to re-invent this wheel.
you could use udp for this; send out a broadcast if a server is up and let al nodes listen for udp packets.
As requested, here is some example code on utp; theses are 2 classes, one is the heart (wich beats) and the other is the listener.
public class Heart extends Observable implements Runnable {
private String groupName = "229.5.38.17";
private int port = 4567;
MulticastSocket multicastSocket;
DatagramPacket datagramPacket;
public Heart(int connectionListenerPort, Observer...observers) {
for(Observer observer : observers) {
this.addObserver(observer);
}
try {
multicastSocket = new MulticastSocket();
InetAddress group = InetAddress.getByName(groupName);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(new Beat(connectionListenerPort));
objectOutputStream.flush();
objectOutputStream.close();
byte[] buf = byteArrayOutputStream.toByteArray();
datagramPacket = new DatagramPacket(buf, buf.length, group, port);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while(true) {
beat();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void beat() {
try {
multicastSocket.send(datagramPacket);
message(new Message(TYPE.INFO, KEY.MESSAGE, "Heart beat sent."));
} catch (IOException e) {
e.printStackTrace();
}
}
private void message(Message message) {
setChanged();
notifyObservers(message);
}
}
public class BeatListener extends Observable implements Runnable {
private boolean run = true;
private String groupName = "229.5.38.17";
MulticastSocket multicastSocket;
private Network network;
public BeatListener(Network network, Observer... observers) {
for(Observer observer : observers) {
addObserver(observer);
}
try {
multicastSocket = new MulticastSocket(4567);
multicastSocket.joinGroup(InetAddress.getByName(groupName));
} catch (IOException e) {
error(e);
e.printStackTrace();
}
this.network = network;
}
#Override
public void run() {
while(run) {
DatagramPacket datagramPacket = new DatagramPacket(new byte[1500], 1500);
try {
multicastSocket.receive(datagramPacket);
if(!isLocalhost(datagramPacket.getAddress().getHostAddress())) {
Beat beat = getBeat(datagramPacket);
if(beat != null) {
network.setPeer(new Peer(datagramPacket.getAddress(), beat.getConnectionListenerPort()));
message(new Message(TYPE.NETWORK, KEY.NETWORK, network));
}
}
} catch (IOException e) {
error(e);
e.printStackTrace();
}
}
}
private void message(Message message) {
setChanged();
notifyObservers(message);
}
private void error(Exception e) {
message(new Message(TYPE.ERROR, KEY.MESSAGE, e.getClass().getSimpleName()));
}
public void stop() {
run = false;
}
private boolean isLocalhost(String hostAddress) {
boolean isLocalhost = false;
Enumeration<NetworkInterface> networkInterfaces;
try {
networkInterfaces = NetworkInterface.getNetworkInterfaces();
if(networkInterfaces != null) {
OUTER:
while(networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
if(inetAddresses != null) {
while(inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if(hostAddress.equals(inetAddress.getHostAddress())) {
isLocalhost = true;
break OUTER;
}
}
}
}
}
} catch (SocketException e) {
error(e);
e.printStackTrace();
}
return isLocalhost;
}
private Beat getBeat(DatagramPacket datagramPacket) {
Beat beat = null;
byte[] data = datagramPacket.getData();
if(data != null) {
try {
ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(data));
beat = (Beat)objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return beat;
}
}
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.