debevv/nanoMODBUS

Comment clarity

Opened this issue · 3 comments

I see lines:

nmbs->platform.read(nmbs->msg.buf, sizeof(nmbs->msg.buf), 0, nmbs->platform.arg);

Should the user's read and write callbacks empty the nmbs->msg.buf and the hardware's UART buffers when the timeout parameter is zero? The comment in nanomodbus.h doesn't say to do this:

Both methods should block until either:
- count bytes of data are read/written
- the byte timeout, with byte_timeout_ms >= 0, expires

In general:

  • with timeout == 0, the function should try to read the data already available from the device and return immediately
  • with timeout < 0, the function should return only when the requested size bytes are read
    Remember that, except for the < 0, it is not mandatory for the function to return exactly the amount of data requested, for whatever reason it can just read a fraction of it and return the number of read bytes.

In that particular line, the function is called to make it read (and thus flush) the data that may be still cached inside the device

Okay, I think I understand. Every time the user's read() callback is called, even if all the Modbus packet's bytes aren't yet available in the UART's receive buffer, the user's read() callback should empty the hardware's receive buffer, discarding even incomplete Modbus packets (the hope is that the next time the poll is made, the Modbus packet will be complete and able to be used).

The read() callback should not empty the hardware read buffer on purpose. It should try to read the number of bytes requested by the library, given the timeout constraints. Finally, it should return the number of bytes that were actually read.
The line you quoted is an edge case where the library exploits the 0 timeout to (ideally) make the callback drain what's in the read buffer and return immediately without waiting for new data