debevv / nanoMODBUS

A compact MODBUS RTU/TCP C library for embedded/microcontrollers
MIT License
294 stars 63 forks source link

Comment clarity #66

Open joegittingherdone opened 1 month ago

joegittingherdone commented 1 month ago

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
debevv commented 1 month ago

In general:

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

joegittingherdone commented 1 month ago

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).

debevv commented 1 month ago

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