Fazecast / jSerialComm

Platform-independent serial port access for Java
GNU Lesser General Public License v3.0
1.34k stars 287 forks source link

Attempting to Write Too Many Bytes #271

Closed fs149 closed 4 years ago

fs149 commented 4 years ago

Hi, I am attempting to communicate with a with device through jSerialComm. The device receives 10 byte instructions and sends 8 byte replies. For some reason the write function takes ridiculously long to complete (on the order of seconds), and when I tried to troubleshoot the problem I found that it was sending about 256 bytes of data. I tried limiting the bytesToWrite to 10 bytes, but it wouldn't transmit the instructions. I was wondering if anybody knew why it was transmitting so much data? I suspect that it is the cause of the slow transmission. My system uses x64, Windows 10 Pro. The device uses UART with 9600bps, 1 stop bit, no parity check.

hedgecrw commented 4 years ago

Could you please post a minimally working version of your code to help in debugging? It should definitely not be sending 256 bytes if you are only specifying 10, so we'll need to see some code to figure it out.

fs149 commented 4 years ago

Thanks for the reply. I've managed to solve the problem by limiting both the read and write buffer sizes to the length of the messages, but below is a simplified version of the original problem.

 import com.fazecast.jSerialComm.SerialPort;
 import java.nio.charset.StandardCharsets;

 public class Main {
     public static void main(String[] args) {

        SerialPort port = SerialPort.getCommPort("COM6");
        port.openPort();

        int buffer = port.getDeviceWriteBufferSize());
        System.out.println(buffer);

       String message = ":J2" + (char) 13;

       byte[] tx;
       tx = message.getBytes(StandardCharsets.US_ASCII);
       System.out.println(port.writeBytes(tx, buffer);

       port.closePort();
     }
 }

The write buffer size is 4096, and the message uses ":" to begin a command and (char) 13 to end one.

hedgecrw commented 4 years ago

K, glad you got it working. Closing this as not an issue. By the way, in your example code above, it does look like you're trying to write 4096 bytes of essentially a 4-byte buffer, so the behavior you documented is expected. Instead of port.writeBytes(tx, buffer), it should have been port.writeBytes(tx, tx.length).