So Libmodbus is a C library. You can find it here: https://libmodbus.org/ – this needs to be compiled into a DLL (assuming you’re on Windows) or a dylib (mac). Once you have that, you can use Declare statements in Xojo to access any of the functions in that DLL, which are documented on the libmodbus site. This is the most direct way to do it, but doing it with individual declare statements is a little clunky.
Instead, I created a Module in Xojo for libmodbus. This module has a constant called LibModBus that holds the path to the library. Inside the module is a class that has all of the libmodbus functions we needed as External Methods, which are private in scope.
The external methods each reference the LibModBus constant in their lib
attribute in the inspector. For each of these External Methods is a method in xojo that calls it. Your code only calls the public method, not the external method.
The constructor for this class has code that sets up the modbus connection so when you create an instance it automatically handles that and from then on you reference that instance of the class when sending or receiving via modbus.
Doing it this way means you can create an instance of this class when you launch your app, or open the main window, and sending/receiving data via modbus is just a matter of accessing the right method in that class, which is a lot cleaner than constantly declaring into the library every time you need it.
Using the example from my post above: We have two MCUs we control. One for film transport and one for the imaging stuff like LEDs. When the app is started it creates a new instance of the libmodbus class called TransportController
. This class creates a connection to the transport MCU.
When we want to write to a register on the MCU we call TransportController.Write_Register(x, y)
where x is the register number and y is the value we want to set. Write_Register
is a public method in my app’s libmodbus class that calls the private external method called modbus_write_register
.
Write_Register
passes the x and y values to the external modbus_write_register
method, which in turn passes it on to the function of the same name in the DLL.
Right now the implementation of the class we have is very specific to our setup and is incomplete (I only dealt with the functions in libmodbus that we needed and there’s a little code in there that’s not generic) and I just don’t really have time to modify it and make it public right now, but this is the basic outline of how I set it up.