Fazecast / jSerialComm

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

Question about Event Based Read/Write Best Practices #291

Closed martinkoslof closed 3 years ago

martinkoslof commented 4 years ago

Hello, I've been looking at JSerialComm and I want to use it for a small portion of a larger project written in Java which will run on linux. The requirements I have are somewhat simple and I want to avoid over-complexity and too many threads and other standard bad practices. What I need to do is receive messages from a serial port and also send ACK or NAK responses or write back to the serial port (the outputstream).

I really want to use Event Based and async here, and just receive a callback when data is available to read. Upon reading the data, if I need to send either an ACK or NAK I simply use the .write or .writeBytes() method, but there really isn't an "async" write process, so I'm wondering if this is bad practice.

1) Does the .write and writeBytes() methods simply write to the OutputStream of the serial port? I'm assuming it does, but I wanted to verify

2) Is it bad practice to write to the serial port within its DataListenerCallback? If so, does that mean people normally have a different thread or some sort of blocking collection to collect and push writes from the async callback? I'd really like to avoid all possibly complexity here.

Does this situation call for a different type of design where async events aren't used at all?

Thanks in advance

hedgecrw commented 3 years ago

Quick responses to your questions:

  1. Yes, write() and writeBytes() just pass the bytes to write to the OS's underlying write buffer for the indicated serial device, so unless any flushing occurs or you pass more data than the buffer can handle, it should happen immediately.
  2. It depends very heavily on what type of data is being sent and how frequently you are receiving data. For your application where you are just replying with an ACK or NACK, replying inside of the data callback should be perfectly fine.

Hope that helps!