The following overview describes how to setup Modbus master communication. The overview reflects a typical programming workflow and is broken down into the sections provided below:
1.:ref:`modbus_api_port_initialization` - Initialization of Modbus controller interface for the selected port.
2.:ref:`modbus_api_master_configure_descriptor` - Configure data descriptors to access slave parameters.
3.:ref:`modbus_api_master_setup_communication_options` - Allows to setup communication options for selected port.
4.:ref:`modbus_api_master_start_communication` - Start stack and sending / receiving data.
The architectural approach of ESP_Modbus includes one level above standard Modbus IO driver. The additional layer is called Modbus controller and its goal is to add an abstraction such as CID - characteristic identifier. The CID is linked to a corresponding Modbus registers through the table called Data Dictionary and represents device physical parameter (such as temperature, humidity, etc.) in specific Modbus slave device. This approach allows the upper layer (e.g., MESH or MQTT) to be isolated from Modbus specifics thus simplify Modbus integration with other protocols/networks.
The Data Dictionary is the list in the Modbus master which shall be defined by user to link each CID to its corresponding Modbus registers representation using Register Mapping table of the Modbus slave being used.
Each element in this data dictionary is of type :cpp:type:`mb_parameter_descriptor_t` and represents the description of one physical characteristic:
..list-table:: Table 1 Modbus master Data Dictionary description
:widths:8 10 82
:header-rows:1
* - Field
- Description
- Detailed information
* - ``cid``
- Characteristic ID
- The identifier of characteristic (must be unique).
* - ``param_key``
- Characteristic Name
- String description of the characteristic.
* - ``param_units``
- Characteristic Units
- Physical Units of the characteristic.
* - ``mb_slave_addr``
- Modbus Slave Address
- The short address of the device with correspond parameter UID.
* - ``mb_param_type``
- Modbus Register Type
- Type of Modbus register area.
:cpp:enumerator:`MB_PARAM_INPUT`, :cpp:enumerator:`MB_PARAM_HOLDING`, :cpp:enumerator:`MB_PARAM_COIL`, :cpp:enumerator:`MB_PARAM_DISCRETE` - represents Input , Holding, Coil and Discrete input register area accordingly;
* - ``mb_reg_start``
- Modbus Register Start
- Relative register address of the characteristic in the register area.
- The storage size of the characteristic (in bytes) describes the size of data to keep into data instance during mapping. For the :ref:`modbus_mapping_complex_data_types` this allows to define the data container of the corresponded type.
..note:: The ``cid`` and ``param_key`` have to be unique. Please use the prefix to the parameter key if you have several similar parameters in your register map table.
- Device name (16 bytes) ASCII string. The type of `PARAM_TYPE_ASCII` allows to read/write complex parameter (string or binary data) that corresponds to one CID.
The example above describes the definition of just several extended types. The types described in the :ref:`modbus_mapping_complex_data_types` allow to address the most useful value formats from devices of known third-party vendors.
Once the type of characteristic is defined in data dictionary the stack is responsible for conversion of values to/from the corresponding type option into the format recognizable by compiler.
..note:: Please refer to your vendor device manual and its mapping table to select the types suitable for your device.
The Modbus stack contains also the :ref:`modbus_api_endianness_conversion` - endianness conversion API functions that allow to convert values from/to each extended type into compiler representation.
During initialization of the Modbus stack, a pointer to the Data Dictionary (called descriptor) must be provided as the parameter of the function below.
:cpp:func:`mbc_master_set_descriptor`:Initialization of master descriptor.
Initialization of master descriptor. The descriptor represents an array of type :cpp:type:`mb_parameter_descriptor_t` and describes all the characteristics accessed by master.
The Data Dictionary can be initialized from SD card, MQTT or other source before start of stack. Once the initialization and setup is done, the Modbus controller allows the reading of complex parameters from any slave included in descriptor table using its CID.
The communication options supported by this library are described in the section :ref:`modbus_supported_communication_options`.
However, it is possible to override the serial communication options calling the function :cpp:func:`uart_param_config` right after :cpp:func:`mbc_slave_setup`.
..note:: Refer to `UART driver documentation <https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/uart.html#set-communication-parameters>`__ for more information about UART peripheral configuration.
..note:: RS485 communication requires call to UART specific APIs to setup communication mode and pins. Refer to the `UART communication section <https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/uart.html#uart-api-running-uart-communication>`__ in documentation.
Modbus master TCP port requires additional definition of IP address table where number of addresses should be equal to number of unique slave addresses in master Modbus Data Dictionary:
The order of IP address string corresponds to short slave address in the Data Dictionary.
..code::c
#define MB_SLAVE_COUNT 2 // Number of slaves in the segment being accessed (as defined in Data Dictionary)
char*slave_ip_address_table[MB_SLAVE_COUNT]={
"192.168.1.2",// Address corresponds to UID1 and set to predefined value by user
"192.168.1.3",// corresponds to UID2 in the segment
NULL// end of table
};
mb_communication_info_tcomm_info={
.ip_port=MB_TCP_PORT,// Modbus TCP port number (default = 502)
.ip_addr_type=MB_IPV4,// version of IP protocol
.ip_mode=MB_MODE_TCP,// Port communication mode
.ip_addr=(void*)slave_ip_address_table,// assign table of IP addresses
.ip_netif_ptr=esp_netif_ptr// esp_netif_ptr pointer to the corresponding network interface
..note:: Refer to `esp_netif component <https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_netif.html>`__ for more information about network interface initialization.
The slave IP addresses in the table can be assigned automatically using mDNS service as described in the example.
Refer to :ref:`example TCP master <example_mb_tcp_master>` for more information.
.._modbus_api_master_start_communication:
Master Communication
^^^^^^^^^^^^^^^^^^^^
The starting of the Modbus controller is the final step in enabling communication. This is performed using function below:
The list of functions below are used by the Modbus master stack from a user's application:
:cpp:func:`mbc_master_send_request`:This function executes a blocking Modbus request. The master sends a data request (as defined in parameter request structure :cpp:type:`mb_param_request_t`) and then blocks until a response from corresponding slave and returns the status of command execution. This function provides a standard way for read/write access to Modbus devices in the network.
:cpp:func:`mbc_master_get_cid_info`:The function gets information about each characteristic supported in the data dictionary and returns the characteristic's description in the form of the :cpp:type:`mb_parameter_descriptor_t` structure. Each characteristic is accessed using its CID.
:cpp:func:`mbc_master_get_parameter`:The function reads the data of a characteristic defined in the parameters of a Modbus slave device. The additional data for request is taken from parameter description table.
ESP_LOGE(TAG,"Could not get information for characteristic %d.",cid);
}
:cpp:func:`mbc_master_set_parameter`
The function writes characteristic's value defined as a name and cid parameter in corresponded slave device. The additional data for parameter request is taken from master parameter description table.
In case the does not clarify some information, such as slave exception code returned in the response, the functions below can be useful.
:cpp:func:`mbc_master_get_transaction_info`
Allows to return the below information as a :cpp:type:`mb_trans_info_t` structure.
..list-table:: Table 4 Transaction extended information
:widths:2 68
:header-rows:1
* - Field
- Description
* - uint64_t ``trans_id``
- The unique transaction identificator stored as uint64_t timestamp.
* - uint8_t ``dest_addr``
- Destination short address (or UID - Unit Identificator) of the slave being accessed.
* - uint8_t ``func_code``
- The last transaction function code.
* - uint8_t ``exception``
- The last transaction exception code returned by slave. :cpp:type:`eMBException`.
* - uint16_t ``err_type``
- The last transaction error type.
:cpp:enumerator:`EV_ERROR_INIT` = 0, No error, initial state or the request is in progress.
:cpp:enumerator:`EV_ERROR_RESPOND_TIMEOUT` = 1, Slave respond timeout. No response during response timeout.
:cpp:enumerator:`EV_ERROR_RECEIVE_DATA` = 2, Receive frame data error.
:cpp:enumerator:`EV_ERROR_EXECUTE_FUNCTION` = 3, Execute function error. Function is not supported or slave returned an error.
:cpp:enumerator:`EV_ERROR_OK` = 4, No error, processing completed successfully.
..warning:: The functionality described in this section is for advanced users and should to be handled correctly.
..note:: The above function returns the latest transaction information which may not be actual if another IO call is performed from higher priority task right before the :cpp:func:`mbc_master_get_transaction_info`. In this case the ``trans_id`` field can clarify if the returned information is obsolete. The transaction ID is just a timestamp of type `uint64_t` returned by function `esp_timer_get_time()`. In this case it is possible determining if the information retrieved corresponds to the actual request using timestamp kept before the IO call and transaction identificator.
..code::c
#define MAX_TRANSACTION_TOUT_US 640000
uint64_tstart_timestamp=esp_timer_get_time();// Get current timestamp in microseconds
ESP_LOGI("TRANSACTION_INFO","Transaction Id: %"PRIu64" is expired",tinfo.trans_id);
}
Below is the way to expose the transaction information and request/response buffers defining the user error handling function. This funcion defined as described in the code below will be executed from internal final state machine before returning from blocking :cpp:func:`mbc_master_set_parameter` or :cpp:func:`mbc_master_get_parameter` functions and expose the internal parameters.
..list-table:: Table 5 Transaction user handler parameters
:widths:2 68
:header-rows:1
* - Field
- Description
* - uint64_t ``trans_id``;
- The unique transaction identificator stored as uint64_t timestamp.
* - uint16_t ``err_type``;
- The last transaction error type.
* - uint8_t ``dest_addr``;
- Destination short address (or UID - Unit Identificator) of the slave being accessed.
* - ``precv_buf``;
- The last transaction internal receive buffer pointer that points to the Modbus PDU frame. NULL - not actual.
* - ``recv_length``;
- The last transaction receive buffer length.
* - ``psent_buf``;
- The last transaction internal sent buffer pointer that points to the Modbus PDU frame. NULL - not actual.
* - ``sent_length``;
- The last transaction sent buffer length.
The user handler function can be useful to check the Modbus frame buffers and expose some information right before returning from the call :cpp:func:`mbc_master_set_parameter` or :cpp:func:`mbc_master_get_parameter` functions.
..warning:: The above handler function may prevent the Modbus FSM to work properly! The body of the handler needs to be as short as possible and contain just simple functionality that will not block processing for relatively long time. This is user software responcibility to not break the Modbus functionality using the function.