I'm writing a Java application to control a custom IR research camera that will be installed on an aircraft. The camera connects to the the computer using UDP sockets via a direct LAN cable. The camera does not initiate any communications; it just replies to commands, 5-character strings, sent to it (the camera code is in C BTW). There are about 16 commands most of which reply more or less instantly with the string ACKNO if the command is recognized, 3 reply with very short data strings, and the last replies with 480 packets of 640 bytes: the image data.
My intent is to send a command and either get the reply buffer(s) or a time out. It must be blocking.
I last worked on this code about 5 months ago and then had to put it on hold while I wrote the interface for the user and the camera was still being built. I'm self taught in Java (my title is Ecologist). I've included code for sending a command and waiting for an ACKNO or time out response. It appears complicated and somewhat verbose to me so I'd like someone else to look at it and comment it or point me in a better direction. I'm using Java 8.
How it might be used in a method:
if (!waitForACK(waitMS, filter).isSuccess) {
// do something
return "Failed to receive ACK.";
}
Top code:
private SendAndWaitForACK sendAndWaitForACK = null;
sendAndWaitForACK = new SendAndWaitForACK();
public Result waitForACK(int waitMS, CameraCommands cmd) {
result.isSuccess = false;
result.dataBytebuffer = ackByteBuffer;
sendAndWaitForACK.setCommand(cmd); // set the comand
Future<?> future = executor.submit(sendAndWaitForACK);
try {
result = (Result) future.get(waitMS, TimeUnit.MILLISECONDS);
} catch (Exception e) {
} finally {
}
return result;
}
private class SendAndWaitForACK implements Callable<Result> {
private CameraCommands cmd;
@Override
public Result call() throws Exception {
// does not return on timeout
result.dataBytebuffer = postCommand(cmd);
result.isSuccess = true;
return result;
}
/**
* setCommand must be called prior to use.
*
* @param cmd
* : CameraCommands
*/
public void setCommand(CameraCommands cmd) {
this.cmd = cmd;
}
}
This is the method that actually deals with the socket.
/**
* postCommand configures the ackByteBuffer prior to writing it to the
* camera. It is invoked by postCommand call method.
*
* @return ackByteBuffer : tByteBuffer The image.
* @throws IOException
*
*/
private ByteBuffer postCommand(CameraCommands command) throws IOException {
ackByteBuffer.rewind();
writeCommand(command); // to UDP Socket
// blocking read reply from UDP Socket
datagramChannel.read(ackByteBuffer);
return ackByteBuffer;
}