I'm developing a Java application which uses jssc library for serial port communication with external device. I need to send a command and then immediatelly read the answer back. The problem which I`m facing is that without 200 ms delay between write and read command the answer is empty. I have developed similar functionality using python and in python it works perfectly, but in Java due to 200 ms delay the communication is very slow. I would like to ask if is it any possibility to make it faster? I have been trying, closing ang opening port between operation, purge port but without any success. Thank you in advance for your help. Bellow you can find my code
serialPort = new SerialPort(getPortName());
if (false == serialPort.isOpened()) {
try {
logger.debug("Opening serial port: " + getPortName());
// Open port
serialPort.openPort();
// We expose the settings. You can also use this line - serialPort.setParams(9600, 8, 1, 0);
serialPort.setParams(SerialPort.BAUDRATE_115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (SerialPortException ex) {
logger.error("Exceptiion during opening port: " + ex);
}
}
serialPort.writeBytes(cmd);
logger.debug("command sended=" + javax.xml.bind.DatatypeConverter.printHexBinary(cmd));
// delay added because java didn`t read data at once
Thread.sleep(200);
answer = serialPort.readBytes();
I think JSSC is based on Javax comm api javax.comm, this API has a delay of 200ms while sending a command and then reading the reply... i think thats why you don't get any response when trying to read before the 200ms...
This is my output times using javax.comms, I'm trying to find a solution for this delay, I'm using serial comms to communicate with an ESP8266
2016-11-08 12:32:31.155[INFO]Starting the receiver 2016-11-08 12:32:31.355[INFO]Receives first char 200ms after..
will try a few things and post if I got a solution... also posting this here in case someone finds a solution.
-------UDATE-------------(sorry for all the comments im new on StackOverflow)
In javax comms API there is a property to set the time that the reader will wait for data, by default is set to 200 ms (Too much i guess) you can set it to wichever value you want, but take in mind that you could read after the data has arrived and get a -1 as response byte:
port = (javax.comm.SerialPort) portId.open( String.valueOf( this ), (int) timeout );
port.setSerialPortParams( freq, dataBits, stopBits, parity );
port.enableReceiveTimeout( 0 );
with this and a little reprograming of my code i got responses in less than 3 ms, I guess something similar is happening in JSSC.
2016-11-08 01:43:32.875[DEBUG]Starting the receiver 2016-11-08 01:43:32.878[DEBUG]Receives first char 3ms after
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.