1

I am developing a Modbus TCP client on Linux to communicate with different Modbus devices using libmodbus.

To initialize the TCP connection, the function int modbus_connect(modbus_t *ctx); is called and returns 0 if the connection was successful.

I need to have one separate thread that continuously monitors this TCP connection to the device to see if it's still connected, and if not, attempt to connect again.

Continuously calling modbus_connectto check if the connection was successful will create multiple connections which is not what I want.

I could attempt to continuously try and read from the device and if there is an error, check the error code and try to connect again. However, The writing and reading to / from the Modbus device happens from a different class and thread which should be extracted from the communication control.

There doesn't seem to be any function in libmodbus to support this.

Any suggestions are appreciated.

Engineer999
  • 3,683
  • 6
  • 33
  • 71
  • What about, instead of make the main thread repeatedly call `modbus_connect`, blocking it waiting for an event ? The event could be raised by the other thread whenever a send/receive error occurs and block itself. On that event the main thread would reconnect and unblock again the data exchange thread. – Roberto Caboni Mar 25 '20 at 18:57
  • @RobertoCaboni Thanks for your reply. What do you mean by blocking it waiting for an event? – Engineer999 Mar 26 '20 at 08:49
  • I used the _event_ term meaning any IPC mechanism provided by Linux. Even a couple of mutex/semaphores could make the job: initially the `read_mutex` is locked, and the `connect_thread` enters a connect `do-while`. After the connect, it locks `connect_mutex` and unlocks `read_mutex`. In this way the `read_thead` goes on until a _"connection_lost"_ error is detected, so that it locks `read_mutex` and unlocks `connect_mutex` making the next while loop to be executed. Watch out for deadlocks. – Roberto Caboni Mar 26 '20 at 09:14
  • I'm sorry, but don't have time to provide a _real_ answer with a full code solution. I'm afraid a pseudo-code is not enough for an answer. Anyway I hope my comment helped. – Roberto Caboni Mar 26 '20 at 09:16
  • [Pthread conditions](https://linux.die.net/man/3/pthread_cond_wait) are probably what you need. [This question](https://stackoverflow.com/q/16038877/11336762) (and its answers) will probably enlight your path as well. – Roberto Caboni Mar 26 '20 at 09:29
  • @RobertoCaboni Thanks again for your suggestions . – Engineer999 Mar 26 '20 at 13:19

0 Answers0