stephane / libmodbus

A Modbus library for Linux, Mac OS, FreeBSD and Windows
http://libmodbus.org
GNU Lesser General Public License v2.1
3.29k stars 1.71k forks source link

modbus_rtu_set_serial_mode cannot be called before modbus_connect #703

Open dmoimas opened 1 year ago

dmoimas commented 1 year ago

Hello everybody,

TL,DR: System: Embedded Linux, Kernel 5.4.0, built on Yocto 3.1 for armhf (iMX6ULL) libmodbus: 3.1.6 built from sources

Issue:

How to reproduce:

How to fix:

Expected:

Long story:

I am developing an embedded system (Linux 5.4.0 on iMX6ULL, built using Yocto/OpenEmbedded) that uses RS-485 communication with an external controller.

RS-485 driver for Linux has support for TIOCGRS485 and TIOCSRS485 on our serial port and it works: I used it for a bootloader interface to upgrade external controller firmware.

The controller application uses Modbus RTU protocol so I decided to use libmodbus (3.1.6): after context creation and some settings (RTS, RTS delay, response timeout, slave address), I used modbus_connect. Everything works fine as all these "setup" functions sets members of ctx_rtu structure. If I tried to add modbus_rtu_set_serial_mode before connect (to configure for RS-485 mode), it failed with EBADF (bad file descriptor) from ioctl. A quick look at source code showed that modbus_rtu_set_serial_mode immediately executes ioctl on ctx->s (but if you don't execute modbus_connect that is not a valid file descriptor).

BR, Diego

akmubi commented 9 months ago

Hi. I agree, docs need to clarify that. Most of the calls expect the serial device or socket to be opened and configured by modbus_connect, but when you're only getting started with the library, you may get confused.