debevv / nanoMODBUS

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

Doubts regarding the TCP connection in library #49

Open urrudelu30 opened 2 months ago

urrudelu30 commented 2 months ago

Hi, I am trying to find a Modbus IP library to fork it in my project SMT32. I also see that this project could work in client/server side and with RTU/IP mode, so I think it could be a good match. For me understanding, I could see that there is needed a my_connect_tcp, this function may be implemented by myself, is it correct?, maybe I can use LWIP stack or did you implemented it in your code?. Please help me to understand your library.

// Set up the TCP connection void* conn = my_connect_tcp(argv[1], argv[2]); if (!conn) { fprintf(stderr, "Error connecting to server\n"); return 1; }

// my_transport_read() and my_transport_write() are implemented by the user 
nmbs_platform_conf platform_conf;
platform_conf.transport = NMBS_TRANSPORT_TCP;
platform_conf.read = my_transport_read;
platform_conf.write = my_transport_write;
platform_conf.arg = conn;    // Passing our TCP connection handle to the read/write functions

// Create the modbus client
nmbs_t nmbs;
nmbs_error err = nmbs_client_create(&nmbs, &platform_conf);
if (err != NMBS_ERROR_NONE) {
    fprintf(stderr, "Error creating modbus client\n");
    return 1;
}

Thak you so much.

Looking formward to your response,

Regards, Aitor

debevv commented 2 months ago

Hi, the library doesn't really require a TCP connect() function. That my_connect_tcp() is in that example just to communicate to the reader "the TCP connection should be up before continuing"
What the library really needs you to implement are these 2 functions assigned to platform_conf.read and platform_conf.write, named my_transport_read and my_transport_write. They are needed because the library will call them automatically during the various Modbus protocol exchanges.

In general the library does not contain any code pertaining the transport through which the Modbus communication happens. This was done on purpose to avoid tying the library to any microcontroller platform/API/IP stack etc.

So in your case you should setup the TCP connection independently with lwIP, then implement these 2 functions using the lwIP API to read and write on that connection.
The linux example does this with the POSIX sockets API (which should be a bit more convoluted than lwIP). The arduino one instead uses the serial line, but by virtue of being simpler it could be useful to you to grasp the general idea behind the library.

I hope I was clear enough, if you have any other question don´t hesitate to ask.