### start() Source: https://emodbus.github.io/modbusserver-tcp Initializes and starts the Modbus TCP server task, enabling it to listen for incoming client connections. ```APIDOC ## `bool start(uint16_t port, uint8_t maxClients, uint32_t timeout);` ### Description This call must be issued initially to start the server task and start listening for incoming requests. The arguments to this call are: * `port`: the TCP port number the server is listening on. The standard Modbus TCP port is 502, but you may choose another one if your application is requiring it. * `maxClients`: the maximum number of Modbus clients that can be served concurrently. This will help limit the load put upon the server. While the `maxClients` number of clients is connected, all further connection attempts will be refused. * `timeout`: closely related to the previous, this parameter tells the server to close a connection as soon as the `timeout` time has passed without another request from the connected client. Keeping a connection open will reduce the response times, but may lock out other clients. ### Method `bool start(uint16_t port, uint8_t maxClients, uint32_t timeout)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (bool) Returns `true` if the server started successfully, `false` otherwise. #### Response Example `true` ``` -------------------------------- ### ModbusClientRTU::begin() Source: https://emodbus.github.io/modbusclient-rtu-api Initializes the ModbusClient instance by opening the request queue and starting the background worker task. ```APIDOC ## void begin(Stream& s, uint32_t baudrate) ### Description Starts the ModbusClientRTU by initializing the request queue and launching a background worker task to process requests. It requires a `Stream` object and the baud rate for communication. ### Parameters - `s` (Stream&): A reference to the serial interface (e.g., `HardwareSerial`). - `baudrate` (uint32_t): The communication baud rate. - `coreID` (int): Optional. The core ID for the background worker task. Defaults to -1 (system picks). - `userInterval` (uint32_t): Optional. User-defined interval in microseconds between messages. Must not be shorter than the standard interval for the given baud rate. ``` ```APIDOC ## void begin(HardwareSerial& s) ### Description Starts the ModbusClientRTU by initializing the request queue and launching a background worker task to process requests. It requires a `HardwareSerial` object. The baud rate is inquired internally. ### Parameters - `s` (HardwareSerial&): A reference to the `HardwareSerial` interface. - `coreID` (int): Optional. The core ID for the background worker task. Defaults to -1 (system picks). - `userInterval` (uint32_t): Optional. User-defined interval in microseconds between messages. Must not be shorter than the standard interval for the given baud rate. ``` -------------------------------- ### Start ModbusServerTCP Source: https://emodbus.github.io/modbusserver-tcp Start the Modbus TCP server task and begin listening for incoming requests. Configure the port, maximum clients, and connection timeout. ```cpp bool start(uint16_t port, uint8_t maxClients, uint32_t timeout); ``` -------------------------------- ### ModbusClientRTU Setup Function Source: https://emodbus.github.io/modbusclient Configure and initialize the ModbusClientRTU client, including setting up the serial port and registering callback handlers. ```cpp void setup() { // Set up Serial2 connected to Modbus RTU RTUutils::prepareHardwareSerial(Serial2); Serial2.begin(19200, SERIAL_8N1); // Set up ModbusClientRTU client. // - provide onData and onError handler functions RS485.onDataHandler(&handleData); RS485.onErrorHandler(&handleError); // Start ModbusClientRTU background task RS485.begin(Serial2); } ``` -------------------------------- ### ModbusServerRTU begin() Methods Source: https://emodbus.github.io/modbusserver-rtu-api Details the various `begin()` methods for starting the Modbus server, including configurations for different serial interfaces, core selection, and custom message intervals. ```APIDOC ## `void begin(Stream& s, uint32_t baudrate)` ## `void begin(Stream& s, uint32_t baudrate, int coreID)` ## `void begin(Stream& s, uint32_t baudrate, int coreID, uint32_t userInterval)` ## `void begin(HardwareSerial& s)` ## `void begin(HardwareSerial& s, int coreID)` ## `void begin(HardwareSerial& s, int coreID, uint32_t userInterval)` ### Description These `begin()` methods start the Modbus server's background task and begin listening for Modbus communication. They require the serial interface and baud rate. Optional parameters allow specifying the core for the background task and a custom interval between messages. ### Parameters #### `s` (Stream& or HardwareSerial&) - Description: The serial interface (e.g., `Serial1`) to be used for Modbus communication. #### `baudrate` (uint32_t) - Description: The baud rate of the used `Stream`. For `HardwareSerial`, this is inquired internally. #### `coreID` (int) - Description: Optional. The ID of the core on which the background task should run. Default is -1, letting the system decide. #### `userInterval` (uint32_t) - Description: Optional. A user-defined interval in microseconds between messages. Must not be shorter than the standard interval for the given baud rate. ``` -------------------------------- ### Install eModbus with PlatformIO Source: https://emodbus.github.io/installation Add the eModbus library to your project's `platformio.ini` file. Ensure you are using a compatible `[env:...]` section. ```ini [platformio] # some settings [env:your_project_target] # some settings lib_deps = ModbusClient=https://github.com/eModbus/eModbus.git # avoid including incompatible libraries lib_compat_mode=strict # optionally set dependency finder to deep+, this might speed up compilation lib_ldf_mode=deep+ ``` -------------------------------- ### Start ModbusBridge Source: https://emodbus.github.io/modbusbridge Start the Modbus bridge, specifying the port, a server ID, and a timeout value. This enables the bridge to begin forwarding requests. ```cpp MBbridge.start(port, 4, 600); ``` -------------------------------- ### Initialize ModbusClientRTU with HardwareSerial Source: https://emodbus.github.io/modbusclient-rtu-api Initialize the ModbusClientRTU with a HardwareSerial object. The baud rate is inquired internally. This starts the background worker task. ```cpp mb.begin(Serial1); ``` -------------------------------- ### Begin ModbusServerRTU with Stream Source: https://emodbus.github.io/modbusserver-rtu-api Start the Modbus server background task and listening. Provide the baud rate for interval calculations. Optionally specify a coreID and a user-defined interval in microseconds. ```cpp void begin(Stream& s, uint32_t baudrate, int coreID, uint32_t userInterval); ``` ```cpp void begin(Stream& s, uint32_t baudrate, int coreID); ``` ```cpp void begin(Stream& s, uint32_t baudrate); ``` -------------------------------- ### Basic ModbusServer WiFi Setup and Callback Source: https://emodbus.github.io/modbusserver Sets up a Modbus server over WiFi, registering a callback function for READ_HOLD_REGISTER and READ_INPUT_REGISTER function codes. Ensure to replace 'YOURNETWORKSSID' and 'YOURNETWORKPASS' with your actual WiFi credentials. ```cpp #include #include "ModbusServerWiFi.h" char ssid[] = "YOURNETWORKSSID"; char pass[] = "YOURNETWORKPASS"; // Set up a Modbus server ModbusServerWiFi MBserver; IPAddress lIP; // assigned local IP const uint8_t MY_SERVER(1); uint16_t memo[128]; // Test server memory // Worker function for serverID=1, function code 0x03 or 0x04 ModbusMessage FC03(ModbusMessage request) { uint16_t addr = 0; // Start address to read uint16_t wrds = 0; // Number of words to read ModbusMessage response; // Get addr and words from data array. Values are MSB-first, get() will convert to binary request.get(2, addr); request.get(4, wrds); // address valid? if (!addr || addr > 128) { // No. Return error response response.setError(request.getServerID(), request.getFunctionCode(), ILLEGAL_DATA_ADDRESS); return response; } // Modbus address is 1..n, memory address 0..n-1 addr--; // Number of words valid? if (!wrds || (addr + wrds) > 127) { // No. Return error response response.setError(request.getServerID(), request.getFunctionCode(), ILLEGAL_DATA_ADDRESS); return response; } // Prepare response response.add(request.getServerID(), request.getFunctionCode(), (uint8_t)(wrds * 2)); // Loop over all words to be sent for (uint16_t i = 0; i < wrds; i++) { // Add word MSB-first to response buffer response.add(memo[addr + i]); } // Return the data response return response; } void setup() { // Init Serial Serial.begin(115200); while (!Serial) {} Serial.println("__ OK __"); // Register the worker function with the Modbus server MBserver.registerWorker(MY_SERVER, READ_HOLD_REGISTER, &FC03); // Register the worker function again for another FC MBserver.registerWorker(MY_SERVER, READ_INPUT_REGISTER, &FC03); // Connect to WiFi WiFi.begin(ssid, pass); delay(200); while (WiFi.status(); != WL_CONNECTED) { Serial.print('.'); delay(1000); } // print local IP address: lIP = WiFi.localIP(); Serial.printf("My IP address: %u.%u.%u.%u\n", lIP[0], lIP[1], lIP[2], lIP[3]); // Initialize server memory with consecutive values for (uint16_t i = 0; i < 128; ++i) { memo[i] = (i * 2) << 8 | ((i * 2) + 1); } // Start the Modbus TCP server: // Port number 502, maximum of 4 clients in parallel, 10 seconds timeout MBserver.start(502, 4, 10000); } void loop() { static uint32_t statusTime = millis(); const uint32_t statusInterval(10000); // We will be idling around here - all is done in subtasks :D if (millis() - statusTime > statusInterval) { Serial.printf("%d clients running.\n", MBserver.activeClients()); statusTime = millis(); } delay(100); } ``` -------------------------------- ### Begin ModbusServerRTU with HardwareSerial Source: https://emodbus.github.io/modbusserver-rtu-api Start the Modbus server background task and listening using HardwareSerial. The baud rate is inquired internally. Optionally specify a coreID and a user-defined interval in microseconds. ```cpp void begin(HardwareSerial& s, int coreID, uint32_t userInterval); ``` ```cpp void begin(HardwareSerial& s, int coreID); ``` ```cpp void begin(HardwareSerial& s); ``` -------------------------------- ### ModbusClientTCP Initialization Source: https://emodbus.github.io/modbusclient-tcp-api Begin the ModbusClientTCP operation by starting the request queue and worker task. Optionally specify a CPU core for the task. ```APIDOC ## `void begin()` and `void begin(int coreID)` This is the most important call to get a ModbusClient instance to work. It will open the request queue and start the background worker task to process the queued requests. The second form of `begin()` allows you to choose a CPU core for the worker task to run (only on multi-core systems like the ESP32). Note The worker task is running forever or until the ModbusClient instance is killed that started it. The destructor will take care of all requests still on the queue and remove those, then will stop the running worker task. ``` -------------------------------- ### Include ModbusServerTCPasync for WiFi Source: https://emodbus.github.io/modbusserver-tcp-async Include this header for Modbus TCP async server functionality. Ensure AsyncTCP is installed as a dependency. ```cpp #include "ModbusServerTCPasync.h" ... ModbusServerTCPasync myServer; ... ``` -------------------------------- ### Initialize ModbusClientTCP Instance Source: https://emodbus.github.io/modbusclient-tcp-api Call this method to start the ModbusClient instance. It opens the request queue and initiates the background worker task responsible for processing queued requests. For multi-core systems like ESP32, you can optionally specify a CPU core for the worker task. ```cpp void begin() void begin(int coreID) ``` -------------------------------- ### Data Response Callback Function Source: https://emodbus.github.io/modbusclient Define a callback function to handle incoming data responses. This example prints a hexadecimal dump of the response. ```cpp void handleData(ModbusMessage msg, uint32_t token) { Serial.printf("Response: serverID=%d, FC=%d, Token=%08X, length=%d:\n", msg.getServerID(), msg.getFunctionCode(), token, msg.size()); for (auto& byte : msg) { Serial.printf("%02X ", byte); } Serial.println(""); } ``` -------------------------------- ### Initialize ModbusClientRTU with Stream Source: https://emodbus.github.io/modbusclient-rtu-api Initialize the ModbusClientRTU with a Stream object and baud rate. This starts the background worker task. Ensure the baud rate is correct for accurate message interval calculation. ```cpp mb.begin(Serial1, 9600); ``` -------------------------------- ### Registering a local response filter function Source: https://emodbus.github.io/modbusbridge-api Example of a response filter function that dumps the response data and forwards it. This can be used for debugging or documentation purposes. ```cpp // filterResponse() - to be applied to returning responses ModbusMessage filterResponse(ModbusMessage response) { // Just dump out every response HEXDUMP_N("Response in filter", response.data(), response.size()); // In any case forward the response return response; } ``` -------------------------------- ### localRequest Source: https://emodbus.github.io/modbusserver-common-api Issues a local request to the Modbus server. This is a blocking call that returns the response immediately. It can be used even if the server has not been started. ```APIDOC ## localRequest ### Description Issues a local request to the Modbus server. This function provides a direct interface to send requests and receive responses without using the server's external interface. It is a blocking call and can be used even if the server has not been started. ### Method `ModbusMessage localRequest(ModbusMessage request)` ### Warning Calls to `localRequest()` may interfere with requests coming in over the server's interface. Protect shared server data access with a mutex or similar mechanism if using parallel calls. ### Note This call works even if the server has not been started via `start()`. It can be used for communication other than RTU or TCP. ``` -------------------------------- ### Get Coil Information Source: https://emodbus.github.io/modbusmessage-coildata Retrieve various properties of the CoilData object, such as total coil capacity, current number of set coils (ON/OFF), and buffer size. ```cpp uint16_t capacity = myCoils.coils(); uint16_t setON = myCoils.coilsSetON(); uint16_t setOFF = myCoils.coilsSetOFF(); uint8_t bufferSize = myCoils.size(); bool isEmpty = myCoils.empty(); ``` -------------------------------- ### skipLeading0x00 Source: https://emodbus.github.io/modbusclient-rtu-api Configures the client to internally skip leading '0x00' bytes in received messages. This is a workaround for potential 'ghost' bytes in some RTU bus setups. ```APIDOC ## skipLeading0x00 ### Description Allows the client to internally drop leading '0x00' bytes received in front of a proper message. This is a workaround for issues with 'ghost' bytes in some RTU bus setups. ### Method Signature `void skipLeading0x00(bool onOff = true)` ### Parameters - **onOff** (bool) - Optional. Set to `true` to enable skipping, `false` to disable. Defaults to `true`. ``` -------------------------------- ### Set Multiple Coils from Vector Source: https://emodbus.github.io/modbusmessage-coildata Update a range of coils starting at a specified index using values from a vector of bytes. Each bit in the bytes corresponds to a coil's state. ```cpp bool success = myCoils.set(index, length, newValueVector); ``` -------------------------------- ### set(uint16_t index, const char *initVector) Source: https://emodbus.github.io/modbusmessage-coildata Sets coil values from a character array (bit image) starting at the specified index. Similar to the `CoilData` version, it handles size differences by copying up to the available space or completely if the source is shorter. ```APIDOC ## set(uint16_t index, const char *initVector) ### Description Sets coil values from a character array (bit image) starting at the specified index. Handles size differences by copying up to the available space or completely if the source is shorter. ### Parameters #### Path Parameters - **index** (uint16_t) - Required - The starting coil index for writing. - **initVector** (const char *) - Required - A character array representing the bit image of the coils to write. ### Request Example ```cpp CoilData myCoils; myCoils.set(0, "11110000"); // Sets the first 8 coils ``` ``` -------------------------------- ### set(uint16_t index, const CoilData& c) Source: https://emodbus.github.io/modbusmessage-coildata Writes coils from a `CoilData` object `c` into the target, starting at coil `index`. The copy adjusts to the available space in the target, stopping if the source is larger than the target or copying completely if the source is shorter. ```APIDOC ## set(uint16_t index, const CoilData& c) ### Description Writes coils from a `CoilData` object `c` into the target, starting at coil `index`. The copy adjusts to the available space in the target, stopping if the source is larger than the target or copying completely if the source is shorter. If the source is an empty `CoilData`, nothing is altered. ### Parameters #### Path Parameters - **index** (uint16_t) - Required - The starting coil index for writing. - **c** (const CoilData&) - Required - The `CoilData` object containing the coils to write. ### Request Example ```cpp CoilData A("1111 1111 1111 1111"); CoilData B("0011 0011"); A.set(8, B); // A is "1111 1111 0011 0011" now! B.set(4, A); // B is "0011 1111" now ``` ``` -------------------------------- ### Message Handling: skipLeading0x00 Source: https://emodbus.github.io/modbusserver-rtu-api Configures the server to internally discard leading 0x00 bytes received in front of a proper message, which can help resolve issues with 'ghost' bytes on some RTU bus setups. ```APIDOC ## `void skipLeading0x00(bool onOff = true)` Some RTU bus setups have unresolvable issues with sporadic ‘ghost’ 0x00 bytes created within the electronics that have no logical representation at all. The `skipLeading0x00()` call allows to have these bytes droped internally, if these are received in front of a proper message. **Note:** this is a work-around only to cure a symptom and does not fix the issue. It always pays to try to fix the root cause! ``` -------------------------------- ### Set Coils from CoilData Object Source: https://emodbus.github.io/modbusmessage-coildata Writes coils from a source `CoilData` object to a target `CoilData` object starting at a specified index. The copy operation adjusts to the available space in the target, truncating if the source is too large or leaving remaining target coils untouched if the source is shorter. An empty source `CoilData` results in no changes. ```cpp CoilData A("1111 1111 1111 1111"); CoilData B("0011 0011"); A.set(8, B); // A is "1111 1111 0011 0011" now! B.set(4, A); // B is "0011 1111" now ``` -------------------------------- ### get(uint16_t index, float& value) and get(uint16_t index, double& value) Source: https://emodbus.github.io/reading-from-a-modbusmessage Extracts IEEE754 float or double values from the message, supporting MSB-first byte order and optional byte-reordering. ```APIDOC ## `uint16_t get(uint16_t index, float& value);` and `uint16_t get(uint16_t index, double& value);` ### Description These `get()` variants are used to extract a 4-byte IEEE754 float or an 8-byte IEEE754 double from a message. The byte order is assumed to be MSB-first. These functions also support optional third parameters for byte-reordering to retrieve values in a different byte order. ### Usage - `uint16_t get(uint16_t index, float& value);` - `uint16_t get(uint16_t index, double& value);` ``` -------------------------------- ### Get Active Clients Source: https://emodbus.github.io/modbusserver-tcp Retrieve the number of currently active client connections to the Modbus TCP server. ```cpp uint16_t activeClients(); ``` -------------------------------- ### Get Error Count Source: https://emodbus.github.io/modbusclient-common-api Retrieves the count of received Modbus error responses for a specific client instance. ```APIDOC ## `uint32_t getErrorCount()` ### Description Each error response received will be counted. The `getErrorCount()` method will return the current state of the counter. ``` -------------------------------- ### Get Message Count Source: https://emodbus.github.io/modbusclient-common-api Retrieves the count of successfully enqueued Modbus requests for a specific client instance. ```APIDOC ## `uint32_t getMessageCount()` ### Description Each request that got successfully enqueued is counted. By calling `getMessageCount()` you will be able to read the number accumulated so far. Please note that this count (and the error count, respectively) is instance-specific, so each ModbusClient instance you created will have its own count. ``` -------------------------------- ### Get Error Count Source: https://emodbus.github.io/modbusclient-common-api Retrieves the number of error responses that have been received. This count is specific to each ModbusClient instance. ```csharp uint32_t getErrorCount(); ``` -------------------------------- ### Instantiate ModbusServerWiFi Source: https://emodbus.github.io/modbusserver-tcp Instantiate a ModbusServerTCP for WiFi connections. Ensure WiFi is configured and available. ```cpp ModbusServerWiFi myServer; ``` -------------------------------- ### Instantiate and Configure ModbusClientRTU Source: https://emodbus.github.io/modbusbridge Create an instance of ModbusClientRTU, specifying the serial port, and set its timeout and begin the client. ```cpp ModbusClientRTU MB(Serial1); MB.setTimeout(2000); MB.begin(); ``` -------------------------------- ### Information Retrieval Source: https://emodbus.github.io/modbusmessage-coildata Methods to get information about the CoilData object's capacity, current state, and data buffer. ```APIDOC ## Information Retrieval ### `uint16_t coils()` Returns the total number of coils the `CoilData` object can hold. ### `bool empty()` Returns `true` if the `CoilData` object contains no coils, `false` otherwise. ### `uint8_t size()` Returns the size of the internal buffer in bytes. ### `uint8_t *data()` Returns a pointer to the internal buffer containing the coil data. ### `uint16_t coilsSetON()` Returns the count of coils currently set to `1`. ### `uint16_t coilsSetOFF()` Returns the count of coils currently set to `0`. ``` -------------------------------- ### get(uint16_t index, T& value) Source: https://emodbus.github.io/reading-from-a-modbusmessage Reads integral data types from the message at a specified index. Returns the index after extraction. ```APIDOC ## `uint16_t get(uint16_t index, T& value);` ### Description Reads integral data values back from a message. The `index` parameter specifies the starting position for extracting a `value` of the integral type `T`. The method returns the index value after the extraction has taken place. ### Example ```cpp // Get address and word count for a READ_INPUT_REGISTER request message uint16_t addr, words; msg.get(2, addr); msg.get(4, words); ``` ``` -------------------------------- ### Instantiate ModbusServerEthernet Source: https://emodbus.github.io/modbusserver-tcp Instantiate a ModbusServerTCP for Ethernet connections. Requires the appropriate Ethernet library. ```cpp ModbusServerEthernet myServer; ``` -------------------------------- ### Get Message Count Source: https://emodbus.github.io/modbusclient-common-api Retrieves the number of Modbus requests that have been successfully enqueued for sending. This count is specific to each ModbusClient instance. ```csharp uint32_t getMessageCount(); ``` -------------------------------- ### Constructor Source: https://emodbus.github.io/modbusclient-tcp-async-api Initializes the ModbusClientTCPasync with the server's IP address and port. An optional queue limit can be specified. ```APIDOC ## `ModbusClientTCPasync(IPAddress host, uint16_t port)` and `ModbusClientTCPasync(IPAddress host, uint16_t port, uint16_t queueLimit)` The asynchronous TCP version takes 2 or 3 arguments: the target host IP address and port number of the Modbus server and an optional queue size limit (defaults to 100). The async version will connect to exactly one Modbus server. ``` -------------------------------- ### Include ModbusServerWiFi Library Source: https://emodbus.github.io/modbusserver-tcp-wifi Include the ModbusServerWiFi library in your source file. The library automatically includes the WiFi.h header. ```cpp #include "ModbusServerWiFi.h" ``` ```cpp ModbusServerWiFi myServer; ``` -------------------------------- ### ModbusServerTCP Constructor Source: https://emodbus.github.io/modbusserver-tcp Instantiate a ModbusServerTCP object. Choose the appropriate class based on your network interface: ModbusServerWiFi, ModbusServerEthernet, ModbusServerETH, or ModbusServerTCPasync. ```APIDOC ## ModbusServerTCP Constructor A ModbusServerTCP is defined by: ```cpp ModbusServerWiFi myServer; ``` or ```cpp ModbusServerEthernet myServer; ``` or ```cpp ModbusServerETH myServer; ``` or ```cpp ModbusServerTCPasync myServer; ``` respectively. ``` -------------------------------- ### Initialize ModbusClientRTU with HardwareSerial and Core ID Source: https://emodbus.github.io/modbusclient-rtu-api Initialize the ModbusClientRTU with a HardwareSerial object and a specific core ID for the background task. This allows for core affinity. ```cpp mb.begin(Serial1, 0); ``` -------------------------------- ### Instantiate ModbusServerETH Source: https://emodbus.github.io/modbusserver-tcp Instantiate a ModbusServerTCP for boards requiring ETH definitions, such as WT32-ETH01. Ensure ETH.h definitions are available. ```cpp ModbusServerETH myServer; ``` -------------------------------- ### RTUutils::prepareHardwareSerial() Source: https://emodbus.github.io/modbusserver-rtu-api Prepares a `HardwareSerial` interface for Modbus RTU communication by setting appropriate buffer sizes. ```APIDOC ## `RTUutils::prepareHardwareSerial(HardwareSerial& s)` ### Description This method must be called **before** `HardwareSerial::begin()` to configure the UART buffer sizes for Modbus RTU. This is crucial for preventing timing errors. A reasonable buffer size for Modbus RTU is 260 bytes for both Rx/Tx buffers. ### Parameters #### `s` (HardwareSerial&) - Description: The `HardwareSerial` interface to prepare (e.g., `Serial1`). ``` -------------------------------- ### ModbusServerRTU Constructors Source: https://emodbus.github.io/modbusserver-rtu-api Details the available constructors for initializing the ModbusServerRTU, including options for timeout and RTS pin configuration. ```APIDOC ## `ModbusServerRTU()` ## `ModbusServerRTU(uint32_t timeout)` ## `ModbusServerRTU(uint32_t timeout, int rtsPin)` ### Description These constructors initialize the ModbusServerRTU. The `timeout` parameter defines the inactivity period after which the server re-initializes its working data. The optional `rtsPin` parameter is used for RS485 adaptors requiring DE/RE line control. ### Parameters #### `timeout` (uint32_t) - Description: Time of inactivity before re-initializing server data. A reasonable value is 20000 (20 seconds). #### `rtsPin` (int) - Description: GPIO number for the DE/RE line of an RS485 adaptor. The library will manage toggling this pin. ## `ModbusServerRTU(uint32_t timeout, RTScallback func)` ### Description This constructor initializes the ModbusServerRTU with a timeout and a callback function for managing the RS485 adaptor's DE/RE line. ### Parameters #### `timeout` (uint32_t) - Description: Time of inactivity before re-initializing server data. A reasonable value is 20000 (20 seconds). #### `func` (RTScallback) - Description: A user-defined callback function of type `void func(bool level);` that is called to toggle the RS485 adaptor’s DE/RE line. The required logic level is passed as a parameter. ``` -------------------------------- ### Initialize ModbusClientRTU with HardwareSerial, Core ID, and User Interval Source: https://emodbus.github.io/modbusclient-rtu-api Initialize the ModbusClientRTU with a HardwareSerial object, core ID, and a custom interval. Use userInterval for devices requiring longer quiet times between messages. ```cpp mb.begin(Serial1, 0, 5000); ``` -------------------------------- ### Initialize ModbusClientTCPasync Source: https://emodbus.github.io/modbusclient-tcp-async-api Instantiate the ModbusClientTCPasync with the server's IP address and port. An optional queue limit can be specified. ```cpp ModbusClientTCPasync(IPAddress host, uint16_t port) ``` ```cpp ModbusClientTCPasync(IPAddress host, uint16_t port, uint16_t queueLimit) ``` -------------------------------- ### Initialize ModbusClientRTU with Stream and Core ID Source: https://emodbus.github.io/modbusclient-rtu-api Initialize the ModbusClientRTU with a Stream object, baud rate, and a specific core ID for the background task. This allows for core affinity. ```cpp mb.begin(Serial1, 9600, 0); ``` -------------------------------- ### Setting File-Local Log Level Source: https://emodbus.github.io/logging Before including Logging.h, use #undef LOCAL_LOG_LEVEL to accept the global LOG_LEVEL for the current file, or define LOCAL_LOG_LEVEL to set a different level specifically for this file. ```c++ #define LOCAL_LOG_LEVEL LOG_LEVEL_DEBUG ``` -------------------------------- ### Hexadecimal Dump Source: https://emodbus.github.io/logging Use HEXDUMP_X to print a hexadecimal and ASCII dump of a specified memory region. X is a log level letter. It includes a user-defined label, starting address, and length. ```c++ HEXDUMP_D("Modbus request", request, length); ``` -------------------------------- ### ModbusClientRTU Constructors Source: https://emodbus.github.io/modbusclient-rtu-api Provides details on the different ways to instantiate a ModbusClientRTU object, including options for RTS pin and queue limits, or a callback function. ```APIDOC ## ModbusClientRTU() Constructors ### Description Instantiates a ModbusClientRTU object. You can specify an RTS pin for RS485 adapters and a queue limit for requests. ### Variants - `ModbusClientRTU()` - `ModbusClientRTU(int8_t rtsPin)` - `ModbusClientRTU(int8_t rtsPin, uint16_t queueLimit)` - `ModbusClientRTU(RTScallback func)` - `ModbusClientRTU(RTScallback func, uint16_t queueLimit)` ### Parameters - `rtsPin` (int8_t): GPIO number for the DE/RE wire of the RS485 adapter. - `queueLimit` (uint16_t): Maximum number of requests allowed in the worker task's queue. Defaults to 100. - `func` (RTScallback): User-defined callback function `void func(bool level)` to toggle the RS485 adaptor's DE/RE line. ``` -------------------------------- ### useModbusASCII Source: https://emodbus.github.io/modbusclient-rtu-api Switches the RTU client to use the Modbus ASCII protocol. In ASCII mode, messages are human-readable ASCII characters, starting with ':' and ending with '\r\n', with an LRC checksum. An optional timeout can be specified. ```APIDOC ## useModbusASCII ### Description Switches the RTU client to Modbus ASCII protocol mode. Messages are encoded as human-readable ASCII characters with a specific start and end sequence, and an LRC checksum. ### Method Signatures `void useModbusASCII()` `void useModbusASCII(unsigned long timeout)` ### Parameters #### For `useModbusASCII(unsigned long timeout)` - **timeout** (unsigned long) - Optional. Alters the standard 1s timeout. Specified in milliseconds. ``` -------------------------------- ### Initialize ModbusClientRTU with Stream, Core ID, and User Interval Source: https://emodbus.github.io/modbusclient-rtu-api Initialize the ModbusClientRTU with a Stream object, baud rate, core ID, and a custom interval. Use userInterval for devices requiring longer quiet times between messages. ```cpp mb.begin(Serial1, 9600, 0, 5000); ``` -------------------------------- ### Initialization Source: https://emodbus.github.io/modbusmessage-coildata Methods to initialize or reset all coils in a CoilData object to a specific state. ```APIDOC ## Initialization ### `void init()` Initializes all coils in the `CoilData` object to `0`. ### `void init(bool value)` Initializes all coils in the `CoilData` object. If `value` is `true`, all coils are set to `1`; otherwise, they are set to `0`. ``` -------------------------------- ### ModbusClientTCP Constructor with Host and Port Source: https://emodbus.github.io/modbusclient-tcp-api This constructor is useful when you need to set the initial target host IP address and port number directly. It's suitable for creating a ModbusClientTCP client dedicated to a single target host. An optional queueLimit can also be specified. ```cpp ModbusClientTCP(Client& client, IPAddress host, uint16_t port) ModbusClientTCP(Client& client, IPAddress host, uint16_t port, uint16_t queueLimit) ``` -------------------------------- ### Prepare HardwareSerial for Modbus RTU Source: https://emodbus.github.io/modbusclient-rtu-api Prepare the HardwareSerial interface before calling begin() to ensure sufficient buffer sizes for Modbus RTU communication. This is crucial for avoiding timing errors. ```cpp RTUutils.prepareHardwareSerial(Serial1); ``` -------------------------------- ### ModbusClientTCP Constructors Source: https://emodbus.github.io/modbusclient-tcp-api Instantiate ModbusClientTCP with a Client interface, optionally specifying a queue limit, or with a target host and port. ```APIDOC ## `ModbusClientTCP(Client& client)` and `ModbusClientTCP(Client& client, uint16_t queueLimit)` The first set of constructors does take a `client` reference parameter, that may be any interface instance supporting the methods defined in `Client.h`, f.i. an `EthernetClient` or a `WiFiClient` instance. This interface will be used to send the Modbus TCP requests and receive the respective TCP responses. The optional `queueLimit` parameter lets you define the maximum number of requests the worker task’s queue will accept. The default is 100; please see the remarks to this parameter in the ModbusClientRTU section. ## `ModbusClientTCP(Client& client, IPAddress host, uint16_t port)` and `ModbusClientTCP(Client& client, IPAddress host, uint16_t port, uint16_t queueLimit)` Alternatively you may give the initial target host IP address and port number to be used for communications. This can be sensible if you have to set up a ModbusClientTCP client dedicated to one single target host. ``` -------------------------------- ### ModbusServerRTU Constructor with RTS Callback Source: https://emodbus.github.io/modbusserver-rtu-api Instantiate ModbusServerRTU with a timeout and a callback function for RS485 DE/RE line toggling. The callback receives a boolean indicating the required logic level. ```cpp ModbusServerRTU(uint32_t timeout, RTScallback func); ``` -------------------------------- ### Instantiate ModbusServerTCPasync Source: https://emodbus.github.io/modbusserver-tcp Instantiate a ModbusServerTCP for asynchronous TCP connections. This is useful for non-blocking operations. ```cpp ModbusServerTCPasync myServer; ``` -------------------------------- ### End ModbusServerRTU Source: https://emodbus.github.io/modbusserver-rtu-api Stop the server's background process and delete the task. A subsequent begin() call will restart the server. ```cpp bool end(); ``` -------------------------------- ### ModbusClientRTU Constructor Source: https://emodbus.github.io/modbusclient Instantiate ModbusClientRTU, optionally providing an RTS pin for half-duplex control. ```cpp ModbusClientRTU RS485(); // for auto half-duplex ModbusClientRTU RS485(rtsPin); // use rtsPin to toggle DE/RE in half-duplex ``` -------------------------------- ### Include ModbusServerEthernet for Standard Ethernet Source: https://emodbus.github.io/modbusserver-tcp-ethernet Include the ModbusServerEthernet library for standard Ethernet shields. Ensure the ModbusServerEthernet object is declared after inclusion. ```cpp #include "ModbusServerEthernet.h" ... ModbusServerEthernet myServer; ... ``` -------------------------------- ### data() and size() Source: https://emodbus.github.io/reading-from-a-modbusmessage Provides constant access to the internal data buffer and its size. ```APIDOC ## All contents by data/size ### Description Provides `const` access to the internal data buffer and its size using the `data()` and `size()` methods, similar to `std::vector`. ### Methods - `uint8_t *data()` - `uint16_t size()` ``` -------------------------------- ### Checking Server Registration Source: https://emodbus.github.io/modbusserver-common-api The `isServerFor` function returns `true` if any callback has been registered for the given `serverID`, indicating that the server is configured to handle requests for that ID. ```cpp bool isServerFor(uint8_t serverID) ``` -------------------------------- ### ModbusServerRTU Constructors Source: https://emodbus.github.io/modbusserver-rtu-api Instantiate ModbusServerRTU with optional timeout and RTS pin. The timeout defines inactivity before re-initialization. The rtsPin is for RS485 adaptors requiring DE/RE line control. ```cpp ModbusServerRTU(uint32_t timeout, int rtsPin); ``` ```cpp ModbusServerRTU(uint32_t timeout); ``` ```cpp ModbusServerRTU(); ``` -------------------------------- ### Include ModbusBridgeEthernet Header Source: https://emodbus.github.io/modbusbridge Include the necessary header file for setting up an Ethernet-based Modbus bridge. ```cpp #include "ModbusBridgeEthernet.h" ``` -------------------------------- ### ModbusClientRTU Constructor with RTS Callback Source: https://emodbus.github.io/modbusclient-rtu-api Instantiate ModbusClientRTU using a callback function for RTS pin control and an optional queue limit. This is useful for custom RTS handling. ```cpp void rtsCallback(bool level) { // Custom RTS logic here } ModbusClientRTU mb(rtsCallback, 100); ``` -------------------------------- ### ModbusClientRTU Constructor Variants Source: https://emodbus.github.io/modbusclient-rtu-api Instantiate ModbusClientRTU with optional RTS pin and queue limit. The queue limit prevents excessive memory usage. ```cpp ModbusClientRTU mb(1, 100); ``` -------------------------------- ### ModbusClientTCP Constructor with Client Reference Source: https://emodbus.github.io/modbusclient-tcp-api Use this constructor when you want to provide an existing Client interface instance, such as EthernetClient or WiFiClient. The provided client will be used for sending Modbus TCP requests and receiving responses. An optional queueLimit can be specified to control the maximum number of requests in the worker task's queue. ```cpp ModbusClientTCP(Client& client) ModbusClientTCP(Client& client, uint16_t queueLimit) ``` -------------------------------- ### The Token Concept Source: https://emodbus.github.io/modbusclient-common-api Understand the token concept, where each request is assigned a user-defined token that is returned with the response, enabling tracking of sent requests. ```APIDOC ## The `token` concept Each request must be given a user-defined `token` value. This token is saved with each request and is returned in the callback. No processing whatsoever is done on the token, you will get what you gave. This enables a user to keep track of the sent requests when receiving a response. Imagine an application that has several ModbusClients working; some for dedicated TCP Modbus servers, another for a RS485 RTU Modbus and another again to request different TCP servers. If you only want to have a single onData and onError function handling all responses regardless of the server that sent them, you will need a means to tell one response from the other. Your token you gave at request time will tell you that, as the response will return exactly that token. ``` -------------------------------- ### Initialize Coil Data Source: https://emodbus.github.io/modbusmessage-coildata Initialize all coils in a CoilData object to 0 or 1. The `init()` call sets all coils to 0, while `init(true)` sets them to 1. ```cpp myCoils.init(); myCoils.init(true); ``` -------------------------------- ### Standard Log Statement Source: https://emodbus.github.io/logging Use LOG_X for printf-style logging. X is a log level letter (e.g., N, C, E, W, I, D, V). This statement includes a standard line header with log level, timestamp, source file, line number, and function name. ```c++ LOG_I("System started. Heap: %u", ESP.getFreeHeap()); ``` -------------------------------- ### Include ModbusServerETH for ETH.h Boards Source: https://emodbus.github.io/modbusserver-tcp-ethernet For boards utilizing the ETH.h library, include ModbusServerETH instead. The object declaration remains ModbusServerEthernet. ```cpp #include "ModbusServerETH.h" ... ModbusServerEthernet myServer; ... ``` -------------------------------- ### Prepare HardwareSerial for Modbus RTU Source: https://emodbus.github.io/modbusserver-rtu-api Call this method before Serial.begin() to ensure the UART buffer is large enough for Modbus RTU messages. A size of 260 is recommended for both Rx/Tx buffers. ```cpp RTUutils.prepareHardwareSerial(Serial1); ``` -------------------------------- ### connect and disconnect Source: https://emodbus.github.io/modbusclient-tcp-async-api Manages the connection to the Modbus server. The library connects automatically on the first request, but manual connection is supported. Disconnection can also be managed manually. ```APIDOC ## `void connect()` and `void disconnect()` The library connects automatically upon making the first request. However, you can also connect manually. When making requests, the requests are put in a queue and the queue is processed once connected. There is however a delay of 500msec between the moment the connection is established and the first request is sent to the server. All the following requests are send immediately. You can avoid the 500msec delay by connecting manually. Disconnecting is also automatic (see `void setIdleTimeout(uint32_t timeout)`). Likewise, you can disconnect manually. ``` -------------------------------- ### connect with host and port Source: https://emodbus.github.io/modbusclient-tcp-async-api Allows connecting to a different Modbus server host and optionally a different port. The existing connection is closed, and the internal default host is updated. ```APIDOC ## `void connect(IPAddress host)` and `void connect(IPAddress host, uint16_t port)` Another flavour of the `connect()` call, allowing you to address another Modbus server host. Any existing connection is closed before connecting to the given host. The internal default host is also switched to the new one, so any subsequent `connect()`, `disconnect()` etc. will be applied to the new host. The port may be omitted and defaults to 502 (standard Modbus port) unless you specify another one. ``` -------------------------------- ### Set Multiple Coils from Pointer Source: https://emodbus.github.io/modbusmessage-coildata Modify a sequence of coils using data from a raw byte pointer. Ensure the pointer and length are accurate to avoid reading unintended memory. ```cpp bool success = myCoils.set(index, length, newValuePtr); ``` -------------------------------- ### Include ModbusClientTCP Header Source: https://emodbus.github.io/modbusclient-tcp-api Include this line in your code to make the ModbusClientTCP API available. This is a prerequisite for using any ModbusClientTCP functionality. ```cpp #include "ModbusClientTCP.h" ``` -------------------------------- ### Set Target Host and Port Source: https://emodbus.github.io/modbusclient-tcp-api This function is essential for specifying the target Modbus TCP server's IP address and port. All subsequent requests will be directed to this host until another setTarget() call is made. Optional timeout and interval parameters can override the default settings for this specific target. ```cpp bool setTarget(IPAddress host, uint16_t port [, uint32_t timeout [, uint32_t interval]]) ``` -------------------------------- ### Include ModbusClientTCPasync Header Source: https://emodbus.github.io/modbusclient-tcp-async-api Include the necessary header file to use the ModbusClientTCPasync API in your C++ project. ```cpp #include "ModbusclientTCPasync.h" ``` -------------------------------- ### User-defined float and double byte order Source: https://emodbus.github.io/filling-a-modbusmessage Explains how to specify byte order for float and double data types using bitwise OR combinations of SWAP_BYTES, SWAP_REGISTERS, SWAP_WORDS, and SWAP_NIBBLES constants. ```APIDOC ## User-defined `float` and `double` byte order To cope with Modbus devices not using the IEEE754 byte sequence to communicate `float` or `double` values, both `add()` functions for these data types are supporting an optional second parameter defining the byte order. This parameter is constructed as an ORed combination of these four values: * `SWAP_BYTES` * `SWAP_REGISTERS` * `SWAP_WORDS` (`double` only) * `SWAP_NIBBLES` Given the normalized byte order of “0, 1, 2, 3” (“0, 1, 2, 3, 4, 5, 6, 7” for a `double`), the result of these values is as follows: * `SWAP_BYTES`: “1, 0, 3, 2” (“1, 0, 3, 2, 5, 4, 7, 6”) * `SWAP_REGISTERS`: “2, 3, 0, 1” (“2, 3, 0, 1, 6, 7, 4, 5”) * `SWAP_WORDS`: only valid for `double` - “4, 5, 6, 7, 0, 1, 2, 3,” * `SWAP_NIBBLES` will change the order of the two 4-bit nibbles in a byte. “0xAB” will be “0xBA”, “0x12” gets “0x21” and so on. A combination of values will yield the combined effect. `SWAP_BYTES|SWAP_REGISTERS` for instance will turn a “0, 1, 2, 3” `float` into “3, 2, 1, 0”. ``` -------------------------------- ### ModbusMessage(uint8_t serverID, uint8_t functionCode, uint16_t p1, uint16_t p2, uint8_t count, uint8_t *arrayOfBytes) Source: https://emodbus.github.io/modbusmessage-constructors Similar to the previous constructor but takes an array of bytes, used for Modbus standard FC 0x0F (WRITE_MULT_COILS). ```cpp ModbusMessage(uint8_t serverID, uint8_t functionCode, uint16_t p1, uint16_t p2, uint8_t count, uint8_t *arrayOfBytes); ``` -------------------------------- ### ModbusServerRTU end() Method Source: https://emodbus.github.io/modbusserver-rtu-api Details the `end()` method for stopping the Modbus server's background process. ```APIDOC ## `bool end()` ### Description Stops the server background process and deletes the associated task. The server can be restarted using another `begin()` call. Calling `begin()` on an already running server will stop and restart it. ### Returns - `true` if the server was stopped successfully, `false` otherwise. ``` -------------------------------- ### ModbusMessage() and ModbusMessage(uint16_t dataLen) Source: https://emodbus.github.io/modbusmessage-constructors Use these constructors to create an empty ModbusMessage instance. The second form pre-allocates memory for efficiency. ```cpp ModbusMessage(); ModbusMessage(uint16_t dataLen); ``` -------------------------------- ### Manual Connection and Disconnection Source: https://emodbus.github.io/modbusclient-tcp-async-api Manually establish or terminate the TCP connection to the Modbus server. The library connects automatically on the first request, but manual connection avoids an initial delay. ```cpp void connect() ``` ```cpp void disconnect() ```