mirror of
https://github.com/espressif/esp-idf.git
synced 2025-10-02 10:00:57 +02:00
Merge branch 'feature/modbus_remove_examples' into 'master'
remove(modbus): remove modbus examples in IDF v6.0 Closes IDF-13491 See merge request espressif/esp-idf!40477
This commit is contained in:
@@ -56,7 +56,6 @@ api-reference/error-codes.rst
|
||||
api-reference/index.rst
|
||||
api-reference/protocols/icmp_echo.rst
|
||||
api-reference/protocols/mqtt.rst
|
||||
api-reference/protocols/modbus.rst
|
||||
api-reference/protocols/mdns.rst
|
||||
api-reference/protocols/index.rst
|
||||
api-reference/protocols/asio.rst
|
||||
|
@@ -83,7 +83,6 @@ api-reference/protocols/esp_crt_bundle.rst
|
||||
api-reference/protocols/mdns.rst
|
||||
api-reference/protocols/asio.rst
|
||||
api-reference/protocols/mbedtls.rst
|
||||
api-reference/protocols/modbus.rst
|
||||
api-reference/protocols/icmp_echo.rst
|
||||
api-reference/protocols/esp_https_server.rst
|
||||
api-reference/protocols/esp_local_ctrl.rst
|
||||
|
@@ -83,7 +83,6 @@ api-reference/protocols/esp_crt_bundle.rst
|
||||
api-reference/protocols/mdns.rst
|
||||
api-reference/protocols/asio.rst
|
||||
api-reference/protocols/mbedtls.rst
|
||||
api-reference/protocols/modbus.rst
|
||||
api-reference/protocols/icmp_echo.rst
|
||||
api-reference/protocols/esp_https_server.rst
|
||||
api-reference/protocols/esp_local_ctrl.rst
|
||||
|
@@ -4,33 +4,25 @@ ESP-Modbus
|
||||
:link_to_translation:`zh_CN:[中文]`
|
||||
|
||||
The Espressif ESP-Modbus Library (esp-modbus) supports Modbus communication in the networks based on RS485, Wi-Fi, and Ethernet interfaces.
|
||||
Since ESP-IDF version v5.0, the component ``freemodbus`` has been moved from ESP-IDF to a separate repository:
|
||||
The component ``esp-modbus v2 (v2.x.x)`` is the current supported component version:
|
||||
|
||||
* `ESP-Modbus component on GitHub <https://github.com/espressif/esp-modbus>`__
|
||||
* `ESP-Modbus component on GitHub <https://github.com/espressif/esp-modbus/tree/main>`__
|
||||
* `ESP-Modbus component in component manager <https://components.espressif.com/components/espressif/esp-modbus>`__
|
||||
|
||||
Hosted Documentation
|
||||
--------------------
|
||||
|
||||
The documentation can be found through the link below:
|
||||
|
||||
* `ESP-Modbus documentation (English) <https://docs.espressif.com/projects/esp-modbus>`__
|
||||
* `ESP-Modbus V2 documentation (English) <https://docs.espressif.com/projects/esp-modbus/en/stable>`__
|
||||
|
||||
Application Examples
|
||||
--------------------
|
||||
Discussions
|
||||
~~~~~~~~~~~
|
||||
|
||||
The examples below demonstrate the ESP-Modbus library of serial and TCP ports for both slave and master implementations respectively.
|
||||
|
||||
- :example:`protocols/modbus/serial/mb_slave` demonstrates how to use {IDF_TARGET_NAME} as a Modbus serial slave device with the esp-modbus stack, enabling an external Modbus host to read and write device parameters using the Modbus protocol.
|
||||
|
||||
- :example:`protocols/modbus/serial/mb_master` demonstrates how to use the esp-modbus stack port on {IDF_TARGET_NAME} as a Modbus serial master device, capable of reading and writing values from slave devices in a Modbus segment.
|
||||
|
||||
- :example:`protocols/modbus/tcp/mb_tcp_slave` demonstrates the esp-modbus TCP slave stack port, allowing an external Modbus host to read and write device parameters via the Modbus protocol.
|
||||
|
||||
- :example:`protocols/modbus/tcp/mb_tcp_master` demonstrates how to use the esp-modbus stack port on {IDF_TARGET_NAME} as a Modbus TCP master device, capable of reading and writing values from slave devices in a Modbus network.
|
||||
|
||||
Please refer to the ``README.md`` documents of each specific example for details.
|
||||
* `Discussions for version v2 <https://github.com/espressif/esp-modbus/discussions>`__
|
||||
|
||||
Protocol References
|
||||
-------------------
|
||||
|
||||
- For the detailed protocol specifications, see `The Modbus Organization <https://modbus.org/specs.php>`_.
|
||||
|
||||
|
@@ -9,6 +9,7 @@ Migration from 5.5 to 6.0
|
||||
build-system
|
||||
peripherals
|
||||
provisioning
|
||||
protocols
|
||||
security
|
||||
tools
|
||||
system
|
||||
|
42
docs/en/migration-guides/release-6.x/6.0/protocols.rst
Normal file
42
docs/en/migration-guides/release-6.x/6.0/protocols.rst
Normal file
@@ -0,0 +1,42 @@
|
||||
ESP-Modbus
|
||||
==========
|
||||
|
||||
:link_to_translation:`zh_CN:[中文]`
|
||||
|
||||
The Espressif ESP-Modbus Library (esp-modbus) supports Modbus communication in the networks based on RS485, Wi-Fi, and Ethernet interfaces.
|
||||
|
||||
The component ``esp-modbus v2 (v2.x.x)`` is the current supported component version:
|
||||
|
||||
* `ESP-Modbus component on GitHub <https://github.com/espressif/esp-modbus/tree/main>`__
|
||||
|
||||
Documentation
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
* `ESP-MODBUS stable documentation v2.x.x <https://docs.espressif.com/projects/esp-modbus/en/stable>`__
|
||||
* `Documentation for legacy version v1.x.x <https://docs.espressif.com/projects/esp-modbus/en/v1>`__
|
||||
|
||||
Application Examples
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Since ESP-IDF version v6.0, the examples for component ``esp-modbus v1`` which is obsolete have been removed from ESP-IDF.
|
||||
|
||||
- `legacy esp-modbus v1.x.x examples (esp-idf v5.5) <https://github.com/espressif/esp-idf/tree/release/v5.5/examples/protocols/modbus>`__
|
||||
|
||||
The examples below demonstrate the ESP-Modbus library of serial and TCP ports for both slave and master implementations respectively.
|
||||
|
||||
- `mb_serial_slave - demonstrates how to use {IDF_TARGET_NAME} as a Modbus serial slave device with the esp-modbus stack, enabling an external Modbus host to read and write device parameters using the Modbus protocol. <https://github.com/espressif/esp-modbus/tree/main/examples/serial/mb_serial_slave>`__
|
||||
|
||||
- `mb_serial_master - demonstrates how to use the esp-modbus stack port on {IDF_TARGET_NAME} as a Modbus serial master device, capable of reading and writing values from slave devices in a Modbus segment. <https://github.com/espressif/esp-modbus/tree/main/examples/serial/mb_serial_master>`__
|
||||
|
||||
- `mb_tcp_slave - demonstrates the esp-modbus TCP slave stack port, allowing an external Modbus host to read and write device parameters via the Modbus protocol. <https://github.com/espressif/esp-modbus/tree/main/examples/tcp/mb_tcp_slave>`__
|
||||
|
||||
- `mb_tcp_master` - demonstrates how to use the esp-modbus stack port on {IDF_TARGET_NAME} as a Modbus TCP master device, capable of reading and writing values from slave devices in a Modbus network. <https://github.com/espressif/esp-modbus/tree/main/examples/tcp/mb_tcp_master>`__
|
||||
|
||||
Please refer to the ``README.md`` documents of each specific example for details.
|
||||
|
||||
Discussions
|
||||
~~~~~~~~~~~
|
||||
|
||||
* `Discussions for version v2 <https://github.com/espressif/esp-modbus/discussions>`__
|
||||
|
||||
|
@@ -3,34 +3,25 @@ ESP-Modbus
|
||||
|
||||
:link_to_translation:`en:[English]`
|
||||
|
||||
乐鑫的 ESP-Modbus 库 (esp-modbus) 支持基于 RS485、Wi-Fi 和以太网接口的 Modbus 通信。
|
||||
自 ESP-IDF v5.0 版本以来, 组件 ``freemodbus`` 已被移动到单独的代码仓库中:
|
||||
乐鑫 ESP-Modbus 库 (esp-modbus) 支持基于 RS485、Wi-Fi 和以太网接口网络的 Modbus 通信。
|
||||
组件 esp-modbus v2 (v2.x.x) 是当前支持的组件版本:
|
||||
|
||||
* `GitHub 上的 ESP-Modbus 组件 <https://github.com/espressif/esp-modbus>`__
|
||||
* `GitHub 上的 ESP-Modbus 组件 <https://github.com/espressif/esp-modbus/tree/main>`__
|
||||
* `组件管理器中的 ESP-Modbus 组件 <https://components.espressif.com/components/espressif/esp-modbus>`__
|
||||
|
||||
托管文档
|
||||
--------
|
||||
--------------------
|
||||
|
||||
相应文档请参阅:
|
||||
文档可通过以下链接找到:
|
||||
|
||||
* `ESP-Modbus 文档 <https://docs.espressif.com/projects/esp-modbus>`__
|
||||
* `ESP-Modbus V2 文档(英文) <https://docs.espressif.com/projects/esp-modbus/en/stable>`__
|
||||
|
||||
应用示例
|
||||
--------
|
||||
讨论
|
||||
~~~~
|
||||
|
||||
以下示例分别介绍了 ESP-Modbus 库的串行端口、TCP 端口的从机和主机实现。
|
||||
|
||||
- :example:`protocols/modbus/serial/mb_slave` 演示了如何使用 {IDF_TARGET_NAME} 作为 Modbus 串行从设备,通过 esp-modbus 栈,使外部 Modbus 主机能够使用 Modbus 协议读取和写入设备参数。
|
||||
|
||||
- :example:`protocols/modbus/serial/mb_master` 演示了如何在 {IDF_TARGET_NAME} 上使用 esp-modbus 栈端口作为 Modbus 串行主设备,读取和写入 Modbus 网络中从设备的值。
|
||||
|
||||
- :example:`protocols/modbus/tcp/mb_tcp_slave` 演示了 esp-modbus TCP 从设备栈端口,允许外部 Modbus 主机通过 Modbus 协议读取和写入设备参数。
|
||||
|
||||
- :example:`protocols/modbus/tcp/mb_tcp_master` 演示了如何在 {IDF_TARGET_NAME} 上使用 esp-modbus 栈端口作为 Modbus TCP 主设备,读取和写入 Modbus 网络中从设备的值。
|
||||
|
||||
详情请参阅具体示例的 ``README.md`` 。
|
||||
* `v2 版本的讨论 <https://github.com/espressif/esp-modbus/discussions>`__
|
||||
|
||||
协议参考
|
||||
--------
|
||||
-------------------
|
||||
|
||||
- Modbus 组织与规范协议请参阅 `The Modbus Organization <https://modbus.org/specs.php>`_。
|
||||
- 有关详细的协议规范,请参阅 `Modbus 组织 <https://modbus.org/specs.php>`_
|
||||
|
@@ -9,6 +9,7 @@
|
||||
build-system
|
||||
peripherals
|
||||
provisioning
|
||||
protocols
|
||||
security
|
||||
tools
|
||||
system
|
||||
|
40
docs/zh_CN/migration-guides/release-6.x/6.0/protocols.rst
Normal file
40
docs/zh_CN/migration-guides/release-6.x/6.0/protocols.rst
Normal file
@@ -0,0 +1,40 @@
|
||||
ESP-Modbus
|
||||
==========
|
||||
|
||||
:link_to_translation:`en:[English]`
|
||||
|
||||
乐鑫ESP-Modbus 库 (esp-modbus) 支持基于 RS485、Wi-Fi 和以太网接口网络的 Modbus 通信。
|
||||
|
||||
``esp-modbus v2 (v2.x.x)`` 组件是当前支持的组件版本:
|
||||
|
||||
* `GitHub 上的 ESP-Modbus 组件 <https://github.com/espressif/esp-modbus/tree/main>`__
|
||||
|
||||
文档
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
* `ESP-MODBUS 稳定版文档 v2.x.x <https://docs.espressif.com/projects/esp-modbus/en/stable>`__
|
||||
* `旧版本 v1.x.x 文档 <https://docs.espressif.com/projects/esp-modbus/en/v1>`__
|
||||
|
||||
应用示例
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
自 ESP-IDF v6.0 版本起,已从 ESP-IDF 中移除已废弃的 ``esp-modbus v1`` 组件示例。
|
||||
|
||||
- `旧版 esp-modbus v1.x.x 示例 (esp-idf v5.5) <https://github.com/espressif/esp-idf/tree/release/v5.5/examples/protocols/modbus>`__
|
||||
|
||||
以下示例分别演示了串行和 TCP 端口的 ESP-Modbus 库在从站和主站实现中的应用。
|
||||
|
||||
- `mb_serial_slave - 演示如何将 {IDF_TARGET_NAME} 用作 Modbus 串行从站设备,通过 esp-modbus 协议栈,使外部 Modbus 主机能够使用 Modbus 协议读写设备参数。 <https://github.com/espressif/esp-modbus/tree/main/examples/serial/mb_serial_slave>`__
|
||||
|
||||
- `mb_serial_master - 演示如何在 {IDF_TARGET_NAME} 上使用 esp-modbus 协议栈端口作为 Modbus 串行主站设备,能够读写 Modbus 段中从站设备的值。 <https://github.com/espressif/esp-modbus/tree/main/examples/serial/mb_serial_master>`__
|
||||
|
||||
- `mb_tcp_slave - 演示 esp-modbus TCP 从站协议栈端口,允许外部 Modbus 主机通过 Modbus 协议读写设备参数。 <https://github.com/espressif/esp-modbus/tree/main/examples/tcp/mb_tcp_slave>`__
|
||||
|
||||
- `mb_tcp_master` - 演示如何在 {IDF_TARGET_NAME} 上使用 esp-modbus 协议栈端口作为 Modbus TCP 主站设备,能够读写 Modbus 网络中从站设备的值。 <https://github.com/espressif/esp-modbus/tree/main/examples/tcp/mb_tcp_master>`__
|
||||
|
||||
有关详细信息,请参阅每个具体示例的 ``README.md`` 文档。
|
||||
|
||||
讨论
|
||||
~~~~~~~~~~~
|
||||
|
||||
* `v2 版本讨论 <https://github.com/espressif/esp-modbus/discussions>`__
|
@@ -17,7 +17,7 @@ menu "Echo Example Configuration"
|
||||
range 1200 115200
|
||||
default 115200
|
||||
help
|
||||
UART communication speed for Modbus example.
|
||||
UART communication speed.
|
||||
|
||||
config EXAMPLE_UART_RXD
|
||||
int "UART RXD pin number"
|
||||
|
@@ -17,7 +17,7 @@ menu "Echo RS485 Example Configuration"
|
||||
range 1200 115200
|
||||
default 115200
|
||||
help
|
||||
UART communication speed for Modbus example.
|
||||
UART communication speed.
|
||||
|
||||
config ECHO_UART_RXD
|
||||
int "UART RXD pin number"
|
||||
|
@@ -162,12 +162,6 @@ examples/protocols/l2tap:
|
||||
- if: IDF_TARGET != "esp32"
|
||||
reason: only test on esp32
|
||||
|
||||
examples/protocols/modbus:
|
||||
<<: *default_rules
|
||||
depends_filepatterns:
|
||||
- examples/common_components/protocol_examples_common/**/*
|
||||
- examples/protocols/modbus/mb_example_common/**/*
|
||||
|
||||
examples/protocols/mqtt/custom_outbox:
|
||||
<<: *mqtt_dependencies
|
||||
|
||||
|
@@ -1,5 +0,0 @@
|
||||
# The following five lines of boilerplate have to be in your project's
|
||||
# CMakeLists in this exact order for cmake to work correctly
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
idf_component_register(SRCS "modbus_params.c"
|
||||
INCLUDE_DIRS "include")
|
@@ -1,10 +0,0 @@
|
||||
# Modbus Example Common
|
||||
|
||||
This directory contains component that is common for Modbus master and slave examples. The component defines Modbus parameters that are shared between examples and provide code that you can copy and adapt into your own projects.
|
||||
For more information please refer to Modbus example README.md files located in the folders:
|
||||
|
||||
* `examples/protocols/modbus/serial/mb_master` Modbus serial master implementation (RTU and ASCII)
|
||||
* `examples/protocols/modbus/serial/mb_slave` Modbus serial slave implementation (RTU and ASCII)
|
||||
* `examples/protocols/modbus/serial/mb_master` Modbus serial master implementation (RTU and ASCII)
|
||||
* `examples/protocols/modbus/tcp/mb_tcp_slave` Modbus serial slave implementation (TCP)
|
||||
* `examples/protocols/modbus/tcp/mb_tcp_master` Modbus serial master implementation (TCP)
|
@@ -1,81 +0,0 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2016-2021 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
/*=====================================================================================
|
||||
* Description:
|
||||
* The Modbus parameter structures used to define Modbus instances that
|
||||
* can be addressed by Modbus protocol. Define these structures per your needs in
|
||||
* your application. Below is just an example of possible parameters.
|
||||
*====================================================================================*/
|
||||
#ifndef _DEVICE_PARAMS
|
||||
#define _DEVICE_PARAMS
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
// This file defines structure of modbus parameters which reflect correspond modbus address space
|
||||
// for each modbus register type (coils, discreet inputs, holding registers, input registers)
|
||||
#pragma pack(push, 1)
|
||||
typedef struct
|
||||
{
|
||||
uint8_t discrete_input0:1;
|
||||
uint8_t discrete_input1:1;
|
||||
uint8_t discrete_input2:1;
|
||||
uint8_t discrete_input3:1;
|
||||
uint8_t discrete_input4:1;
|
||||
uint8_t discrete_input5:1;
|
||||
uint8_t discrete_input6:1;
|
||||
uint8_t discrete_input7:1;
|
||||
uint8_t discrete_input_port1;
|
||||
uint8_t discrete_input_port2;
|
||||
} discrete_reg_params_t;
|
||||
#pragma pack(pop)
|
||||
|
||||
#pragma pack(push, 1)
|
||||
typedef struct
|
||||
{
|
||||
uint8_t coils_port0;
|
||||
uint8_t coils_port1;
|
||||
uint8_t coils_port2;
|
||||
} coil_reg_params_t;
|
||||
#pragma pack(pop)
|
||||
|
||||
#pragma pack(push, 1)
|
||||
typedef struct
|
||||
{
|
||||
float input_data0; // 0
|
||||
float input_data1; // 2
|
||||
float input_data2; // 4
|
||||
float input_data3; // 6
|
||||
uint16_t data[150]; // 8 + 150 = 158
|
||||
float input_data4; // 158
|
||||
float input_data5;
|
||||
float input_data6;
|
||||
float input_data7;
|
||||
uint16_t data_block1[150];
|
||||
} input_reg_params_t;
|
||||
#pragma pack(pop)
|
||||
|
||||
#pragma pack(push, 1)
|
||||
typedef struct
|
||||
{
|
||||
float holding_data0;
|
||||
float holding_data1;
|
||||
float holding_data2;
|
||||
float holding_data3;
|
||||
uint16_t test_regs[150];
|
||||
float holding_data4;
|
||||
float holding_data5;
|
||||
float holding_data6;
|
||||
float holding_data7;
|
||||
} holding_reg_params_t;
|
||||
#pragma pack(pop)
|
||||
|
||||
extern holding_reg_params_t holding_reg_params;
|
||||
extern input_reg_params_t input_reg_params;
|
||||
extern coil_reg_params_t coil_reg_params;
|
||||
extern discrete_reg_params_t discrete_reg_params;
|
||||
|
||||
#endif // !defined(_DEVICE_PARAMS)
|
@@ -1,20 +0,0 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2016-2021 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
/*=====================================================================================
|
||||
* Description:
|
||||
* C file to define parameter storage instances
|
||||
*====================================================================================*/
|
||||
#include "modbus_params.h"
|
||||
|
||||
// Here are the user defined instances for device parameters packed by 1 byte
|
||||
// These are keep the values that can be accessed from Modbus master
|
||||
holding_reg_params_t holding_reg_params = { 0 };
|
||||
|
||||
input_reg_params_t input_reg_params = { 0 };
|
||||
|
||||
coil_reg_params_t coil_reg_params = { 0 };
|
||||
|
||||
discrete_reg_params_t discrete_reg_params = { 0 };
|
@@ -1,82 +0,0 @@
|
||||
# Modbus Master-Slave Example
|
||||
|
||||
## Overview
|
||||
|
||||
These two projects illustrate the communication between Modbus master and slave device in the segment.
|
||||
Master initializes Modbus interface driver and then reads parameters from slave device in the segment.
|
||||
After several successful read attempts slave sets the alarm relay (end of test condition).
|
||||
Once master reads the alarm it stops communication and destroy driver.
|
||||
|
||||
The examples:
|
||||
|
||||
* `examples/protocols/modbus/serial/mb_master` - Modbus serial master ASCII/RTU
|
||||
* `examples/protocols/modbus/serial/mb_slave` - Modbus serial slave ASCII/RTU
|
||||
|
||||
See README.md for each individual project for more information.
|
||||
|
||||
## How to use example
|
||||
|
||||
### Hardware Required
|
||||
|
||||
This example can be run on any commonly available ESP32 development board.
|
||||
The master and slave boards should be connected to each other through the RS485 interface line driver.
|
||||
See the connection schematic in README.md files of each example.
|
||||
|
||||
### Configure the project
|
||||
|
||||
This example test requires communication mode setting for master and slave be the same and slave address set to 1.
|
||||
Please refer to README.md files of each example project for more information.
|
||||
|
||||
## About common_component in this example
|
||||
|
||||
The folder "mb_example_common" includes definitions of parameter structures for master and slave device (both projects share the same parameters).
|
||||
However, currently it is for example purpose only and can be modified for particular application.
|
||||
|
||||
## Example Output
|
||||
|
||||
Example of Slave output:
|
||||
|
||||
```
|
||||
I (343) SLAVE_TEST: Modbus slave stack initialized.
|
||||
I (343) SLAVE_TEST: Start modbus test...
|
||||
I (81463) SLAVE_TEST: HOLDING READ (81150420 us), ADDR:1, TYPE:2, INST_ADDR:0x3ffb2868, SIZE:6
|
||||
I (82463) SLAVE_TEST: HOLDING READ (82150720 us), ADDR:1, TYPE:2, INST_ADDR:0x3ffb2868, SIZE:6
|
||||
I (83573) SLAVE_TEST: HOLDING READ (83260630 us), ADDR:1, TYPE:2, INST_ADDR:0x3ffb2868, SIZE:6
|
||||
I (84603) SLAVE_TEST: HOLDING READ (84290530 us), ADDR:1, TYPE:2, INST_ADDR:0x3ffb2868, SIZE:6
|
||||
I (85703) SLAVE_TEST: HOLDING READ (85396692 us), ADDR:1, TYPE:2, INST_ADDR:0x3ffb2868, SIZE:6
|
||||
```
|
||||
|
||||
Example of Modbus Master output:
|
||||
|
||||
```
|
||||
I (399) MASTER_TEST: Modbus master stack initialized...
|
||||
I (499) MASTER_TEST: Start modbus test...
|
||||
I (549) MASTER_TEST: Characteristic #0 Data_channel_0 (Volts) value = 1.230000 (0x3f9d70a4) read successful.
|
||||
I (629) MASTER_TEST: Characteristic #1 Humidity_1 (%rH) value = 12.100000 (0x4141999a) read successful.
|
||||
I (709) MASTER_TEST: Characteristic #2 Temperature_1 (C) value = 3.560000 (0x4063d70a) read successful.
|
||||
I (769) MASTER_TEST: Characteristic #3 Humidity_2 (%rH) value = 23.400000 (0x41bb3333) read successful.
|
||||
I (829) MASTER_TEST: Characteristic #4 Temperature_2 (C) value = 5.890000 (0x40bc7ae1) read successful.
|
||||
I (889) MASTER_TEST: Characteristic #5 Humidity_3 (%rH) value = 34.500000 (0x420a0000) read successful.
|
||||
E (949) MB_CONTROLLER_MASTER: mbc_master_get_parameter(111): SERIAL master get parameter failure error=(0x108) (ESP_ERR_INVALID_RESPONSE).
|
||||
E (949) MASTER_TEST: Characteristic #6 (RelayP1) read fail, err = 264 (ESP_ERR_INVALID_RESPONSE).
|
||||
E (1029) MB_CONTROLLER_MASTER: mbc_master_get_parameter(111): SERIAL master get parameter failure error=(0x108) (ESP_ERR_INVALID_RESPONSE).
|
||||
E (1029) MASTER_TEST: Characteristic #7 (RelayP2) read fail, err = 264 (ESP_ERR_INVALID_RESPONSE).
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
If the examples do not work as expected and slave and master boards are not able to communicate correctly it is possible to find the reason for errors.
|
||||
The most important errors are described in master example output and formatted as below:
|
||||
|
||||
```
|
||||
E (1692332) MB_CONTROLLER_MASTER: mbc_master_get_parameter(111): SERIAL master get parameter failure error=(0x107) (ESP_ERR_TIMEOUT).
|
||||
```
|
||||
|
||||
ESP_ERR_TIMEOUT (0x107) - Modbus slave device does not respond during configured timeout. Check the connection and ability for communication using uart_echo_rs485 example or increase
|
||||
Kconfig value CONFIG_FMB_MASTER_TIMEOUT_MS_RESPOND (CONFIG_FMB_SERIAL_ASCII_TIMEOUT_RESPOND_MS).
|
||||
|
||||
ESP_ERR_NOT_SUPPORTED (0x106), ESP_ERR_INVALID_RESPONSE (0x108) - Modbus slave device does not support requested command or register and sent exeption response.
|
||||
|
||||
ESP_ERR_INVALID_STATE (0x103) - Modbus stack is not configured correctly or can't work correctly due to critical failure.
|
||||
|
||||
|
@@ -1,8 +0,0 @@
|
||||
# The following lines of boilerplate have to be in your project's CMakeLists
|
||||
# in this exact order for cmake to work correctly
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
# "Trim" the build. Include the minimal set of components, main, and anything it depends on.
|
||||
idf_build_set_property(MINIMAL_BUILD ON)
|
||||
project(modbus_master)
|
@@ -1,156 +0,0 @@
|
||||
| Supported Targets | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C5 | ESP32-C6 | ESP32-C61 | ESP32-H2 | ESP32-P4 | ESP32-S2 | ESP32-S3 |
|
||||
| ----------------- | ----- | -------- | -------- | -------- | -------- | --------- | -------- | -------- | -------- | -------- |
|
||||
|
||||
# Modbus Master Example
|
||||
|
||||
This example demonstrates using of FreeModbus stack port implementation for ESP32 as a master device.
|
||||
This implementation is able to read/write values of slave devices connected into Modbus segment. All parameters to be accessed are defined in data dictionary of the modbus master example source file.
|
||||
The values represented as characteristics with its name and characteristic CID which are linked into registers of slave devices connected into Modbus segment.
|
||||
The example implements simple control algorithm and checks parameters from slave device and gets alarm (relay in the slave device) when value of holding_data0 parameter exceeded limit.
|
||||
The instances for the modbus parameters are common for master and slave examples and located in `examples/protocols/modbus/mb_example_common` folder.
|
||||
|
||||
Example parameters definition:
|
||||
--------------------------------------------------------------------------------------------------
|
||||
| Slave Address | Characteristic ID | Characteristic name | Description |
|
||||
|---------------------|----------------------|----------------------|----------------------------|
|
||||
| MB_DEVICE_ADDR1 | CID_INP_DATA_0, | Data_channel_0 | Data channel 1 |
|
||||
| MB_DEVICE_ADDR1 | CID_HOLD_DATA_0, | Humidity_1 | Humidity 1 |
|
||||
| MB_DEVICE_ADDR1 | CID_INP_DATA_1 | Temperature_1 | Sensor temperature |
|
||||
| MB_DEVICE_ADDR1 | CID_HOLD_DATA_1, | Humidity_2 | Humidity 2 |
|
||||
| MB_DEVICE_ADDR1 | CID_INP_DATA_2 | Temperature_2 | Ambient temperature |
|
||||
| MB_DEVICE_ADDR1 | CID_HOLD_DATA_2 | Humidity_3 | Humidity 3 |
|
||||
| MB_DEVICE_ADDR1 | CID_RELAY_P1 | RelayP1 | Alarm Relay outputs on/off |
|
||||
| MB_DEVICE_ADDR1 | CID_RELAY_P2 | RelayP2 | Alarm Relay outputs on/off |
|
||||
--------------------------------------------------------------------------------------------------
|
||||
Note: The Slave Address is the same for all parameters for example test but it can be changed in the ```Example Data (Object) Dictionary``` table of master example to address parameters from other slaves.
|
||||
The Kconfig ```Modbus slave address``` - CONFIG_MB_SLAVE_ADDR parameter in slave example can be configured to create Modbus multi slave segment.
|
||||
|
||||
Simplified Modbus connection schematic for example test:
|
||||
```
|
||||
MB_DEVICE_ADDR1
|
||||
------------- -------------
|
||||
| | RS485 network | |
|
||||
| Slave 1 |---<>--+---<>---| Master |
|
||||
| | | |
|
||||
------------- -------------
|
||||
```
|
||||
Modbus multi slave segment connection schematic:
|
||||
```
|
||||
MB_DEVICE_ADDR1
|
||||
-------------
|
||||
| |
|
||||
| Slave 1 |---<>--+
|
||||
| | |
|
||||
------------- |
|
||||
MB_DEVICE_ADDR2 |
|
||||
------------- | -------------
|
||||
| | | | |
|
||||
| Slave 2 |---<>--+---<>---| Master |
|
||||
| | | | |
|
||||
------------- | -------------
|
||||
MB_DEVICE_ADDR3 |
|
||||
------------- RS485 network
|
||||
| | |
|
||||
| Slave 3 |---<>--+
|
||||
| |
|
||||
-------------
|
||||
```
|
||||
|
||||
## Hardware required :
|
||||
Option 1:
|
||||
PC (Modbus Slave app) + USB Serial adapter connected to USB port + RS485 line drivers + ESP32 based board
|
||||
|
||||
Option 2:
|
||||
Several ESP32 boards flashed with modbus_slave example software to represent slave device with specific slave address (See CONFIG_MB_SLAVE_ADDR). The slave addresses for each board have to be configured as defined in "connection schematic" above.
|
||||
One ESP32 board flashed with modbus_master example. All the boards require connection of RS485 line drivers (see below).
|
||||
|
||||
The MAX485 line driver is used as an example below but other similar chips can be used as well.
|
||||
RS485 example circuit schematic for connection of master and slave devices into segment:
|
||||
```
|
||||
VCC ---------------+ +--------------- VCC
|
||||
| |
|
||||
+-------x-------+ +-------x-------+
|
||||
RXD <------| RO | DIFFERENTIAL | RO|-----> RXD
|
||||
| B|---------------|B |
|
||||
TXD ------>| DI MAX485 | \ / | MAX485 DI|<----- TXD
|
||||
ESP32 BOARD | | RS-485 side | | External PC (emulator) with USB to serial or
|
||||
RTS --+--->| DE | / \ | DE|---+ ESP32 BOARD (slave)
|
||||
| | A|---------------|A | |
|
||||
+----| /RE | PAIR | /RE|---+-- RTS
|
||||
+-------x-------+ +-------x-------+
|
||||
| |
|
||||
--- ---
|
||||
Modbus Master device Modbus Slave device
|
||||
|
||||
```
|
||||
|
||||
## How to setup and use an example:
|
||||
|
||||
### Configure the application
|
||||
Start the command below to setup configuration:
|
||||
```
|
||||
idf.py menuconfig
|
||||
```
|
||||
Configure the UART pins used for modbus communication using and table below.
|
||||
Define the communication mode parameter for master and slave in Kconfig - CONFIG_MB_COMM_MODE (must be the same for master and slave devices in one segment).
|
||||
Configure the slave address for each slave in the Modbus segment (the CONFIG_MB_SLAVE_ADDR in Kconfig).
|
||||
```
|
||||
------------------------------------------------------------------------------------------------------------------------------
|
||||
| UART Interface | #define | Default pins for | Default pins for ESP32-S2 | External RS485 Driver Pin |
|
||||
| | | ESP32 (C6, P4) | (S3, C3, C2, C5, H2, C61) | |
|
||||
| ----------------------|--------------------|-----------------------|---------------------------|---------------------------|
|
||||
| Transmit Data (TxD) | CONFIG_MB_UART_TXD | GPIO23 | GPIO9 | DI |
|
||||
| Receive Data (RxD) | CONFIG_MB_UART_RXD | GPIO22 | GPIO8 | RO |
|
||||
| Request To Send (RTS) | CONFIG_MB_UART_RTS | GPIO18 | GPIO10 | ~RE/DE |
|
||||
| Ground | n/a | GND | GND | GND |
|
||||
------------------------------------------------------------------------------------------------------------------------------
|
||||
```
|
||||
Note: Each target chip has different GPIO pins available for UART connection. Please refer to UART documentation for selected target for more information.
|
||||
|
||||
Connect a USB-to-RS485 adapter to a computer, then connect the adapter's A/B output lines with the corresponding A/B output lines of the RS485 line driver connected to the ESP32 chip (see figure above).
|
||||
|
||||
The communication parameters of Modbus stack allow to configure it appropriately but usually it is enough to use default settings.
|
||||
See the help string of parameters for more information.
|
||||
|
||||
### Setup external Modbus slave devices or emulator
|
||||
Option 1:
|
||||
Configure the external Modbus master software according to port configuration parameters used in the example. The Modbus Slave application can be used with this example to emulate slave devices with its parameters. Use official documentation for software to setup emulation of slave devices.
|
||||
|
||||
Option 2:
|
||||
Other option is to have the modbus_slave example application flashed into ESP32 based board and connect boards together as showed on the Modbus connection schematic above. See the Modbus slave API documentation to configure communication parameters and slave addresses as defined in "Example parameters definition" table above.
|
||||
|
||||
### Build and flash software of master device
|
||||
Build the project and flash it to the board, then run monitor tool to view serial output:
|
||||
```
|
||||
idf.py -p PORT flash monitor
|
||||
```
|
||||
|
||||
(To exit the serial monitor, type ``Ctrl-]``.)
|
||||
|
||||
See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects.
|
||||
|
||||
## Example Output
|
||||
Example output of the application:
|
||||
```
|
||||
I (9035) MASTER_TEST: Characteristic #0 Data_channel_0 (Volts) value = 1.120000 (0x3f8f5c29) read successful.
|
||||
I (9045) MASTER_TEST: Characteristic #1 Humidity_1 (%rH) value = 5.539999 (0x40b147ac) read successful.
|
||||
I (9045) MASTER_TEST: Characteristic #2 Temperature_1 (C) value = 2.340000 (0x4015c28f) read successful.
|
||||
I (9055) MASTER_TEST: Characteristic #3 Humidity_2 (%rH) value = 2.560000 (0x4023d70a) read successful.
|
||||
I (9065) MASTER_TEST: Characteristic #4 Temperature_2 (C) value = 3.560000 (0x4063d70a) read successful.
|
||||
I (9075) MASTER_TEST: Characteristic #5 Humidity_3 (%rH) value = 3.780000 (0x4071eb85) read successful.
|
||||
I (9085) MASTER_TEST: Characteristic #6 RelayP1 (on/off) value = OFF (0x55) read successful.
|
||||
I (9095) MASTER_TEST: Characteristic #7 RelayP2 (on/off) value = OFF (0xaa) read successful.
|
||||
I (9605) MASTER_TEST: Characteristic #0 Data_channel_0 (Volts) value = 1.120000 (0x3f8f5c29) read successful.
|
||||
I (9615) MASTER_TEST: Characteristic #1 Humidity_1 (%rH) value = 5.739999 (0x40b7ae12) read successful.
|
||||
I (9615) MASTER_TEST: Characteristic #2 Temperature_1 (C) value = 2.340000 (0x4015c28f) read successful.
|
||||
I (9625) MASTER_TEST: Characteristic #3 Humidity_2 (%rH) value = 2.560000 (0x4023d70a) read successful.
|
||||
I (9635) MASTER_TEST: Characteristic #4 Temperature_2 (C) value = 3.560000 (0x4063d70a) read successful.
|
||||
I (9645) MASTER_TEST: Characteristic #5 Humidity_3 (%rH) value = 3.780000 (0x4071eb85) read successful.
|
||||
I (9655) MASTER_TEST: Characteristic #6 RelayP1 (on/off) value = OFF (0x55) read successful.
|
||||
I (9665) MASTER_TEST: Characteristic #7 RelayP2 (on/off) value = ON (0xff) read successful.
|
||||
I (10175) MASTER_TEST: Alarm triggered by cid #7.
|
||||
I (10175) MASTER_TEST: Destroy master...
|
||||
|
||||
```
|
||||
The example reads the characteristics from slave device(s), while alarm is not triggered in the slave device (See the "Example parameters definition"). The output line describes Timestamp, Cid of characteristic, Characteristic name (Units), Characteristic value (Hex).
|
||||
|
@@ -1,4 +0,0 @@
|
||||
set(PROJECT_NAME "modbus_master")
|
||||
|
||||
idf_component_register(SRCS "master.c"
|
||||
INCLUDE_DIRS ".")
|
@@ -1,83 +0,0 @@
|
||||
menu "Modbus Example Configuration"
|
||||
|
||||
orsource "$IDF_PATH/examples/common_components/env_caps/$IDF_TARGET/Kconfig.env_caps"
|
||||
|
||||
config MB_UART_PORT_ONE
|
||||
bool
|
||||
default y
|
||||
depends on (ESP_CONSOLE_UART_NUM !=1) && (SOC_UART_HP_NUM > 1)
|
||||
|
||||
config MB_UART_PORT_TWO
|
||||
bool
|
||||
default y
|
||||
depends on (ESP_CONSOLE_UART_NUM !=2) && (SOC_UART_HP_NUM > 2)
|
||||
|
||||
config MB_UART_PORT_NUM
|
||||
int "UART port number"
|
||||
range 0 2 if MB_UART_PORT_TWO
|
||||
default 2 if MB_UART_PORT_TWO
|
||||
range 0 1 if MB_UART_PORT_ONE
|
||||
default 1 if MB_UART_PORT_ONE
|
||||
help
|
||||
UART communication port number for Modbus example.
|
||||
|
||||
config MB_UART_BAUD_RATE
|
||||
int "UART communication speed"
|
||||
range 1200 115200
|
||||
default 115200
|
||||
help
|
||||
UART communication speed for Modbus example.
|
||||
|
||||
config MB_UART_RXD
|
||||
int "UART RXD pin number"
|
||||
range ENV_GPIO_RANGE_MIN ENV_GPIO_IN_RANGE_MAX
|
||||
default 22 if IDF_TARGET_ESP32 || IDF_TARGET_ESP32C6 || IDF_TARGET_ESP32P4
|
||||
default 8 if IDF_TARGET_ESP32S2 || IDF_TARGET_ESP32S3 || IDF_TARGET_ESP32C3
|
||||
default 8 if IDF_TARGET_ESP32C2 || IDF_TARGET_ESP32H2 || IDF_TARGET_ESP32C5
|
||||
default 8 if IDF_TARGET_ESP32C61
|
||||
help
|
||||
GPIO number for UART RX pin. See UART documentation for more information
|
||||
about available pin numbers for UART.
|
||||
|
||||
config MB_UART_TXD
|
||||
int "UART TXD pin number"
|
||||
range ENV_GPIO_RANGE_MIN ENV_GPIO_OUT_RANGE_MAX
|
||||
default 23 if IDF_TARGET_ESP32 || IDF_TARGET_ESP32C6 || IDF_TARGET_ESP32P4
|
||||
default 9 if IDF_TARGET_ESP32S2 || IDF_TARGET_ESP32S3 || IDF_TARGET_ESP32C3
|
||||
default 9 if IDF_TARGET_ESP32C2 || IDF_TARGET_ESP32H2 || IDF_TARGET_ESP32C5
|
||||
default 9 if IDF_TARGET_ESP32C61
|
||||
help
|
||||
GPIO number for UART TX pin. See UART documentation for more information
|
||||
about available pin numbers for UART.
|
||||
|
||||
config MB_UART_RTS
|
||||
int "UART RTS pin number"
|
||||
range ENV_GPIO_RANGE_MIN ENV_GPIO_OUT_RANGE_MAX
|
||||
default 20 if IDF_TARGET_ESP32P4
|
||||
default 18 if IDF_TARGET_ESP32 || IDF_TARGET_ESP32C6
|
||||
default 10 if IDF_TARGET_ESP32S2 || IDF_TARGET_ESP32S3 || IDF_TARGET_ESP32C3
|
||||
default 10 if IDF_TARGET_ESP32C2 || IDF_TARGET_ESP32H2 || IDF_TARGET_ESP32C5
|
||||
default 10 if IDF_TARGET_ESP32C61
|
||||
help
|
||||
GPIO number for UART RTS pin. This pin is connected to
|
||||
~RE/DE pin of RS485 transceiver to switch direction.
|
||||
See UART documentation for more information about available pin
|
||||
numbers for UART.
|
||||
|
||||
choice MB_COMM_MODE
|
||||
prompt "Modbus communication mode"
|
||||
default MB_COMM_MODE_RTU if CONFIG_FMB_COMM_MODE_RTU_EN
|
||||
help
|
||||
Selection of Modbus communication mode option for Modbus.
|
||||
|
||||
config MB_COMM_MODE_RTU
|
||||
bool "RTU mode"
|
||||
depends on FMB_COMM_MODE_RTU_EN
|
||||
|
||||
config MB_COMM_MODE_ASCII
|
||||
bool "ASCII mode"
|
||||
depends on FMB_COMM_MODE_ASCII_EN
|
||||
|
||||
endchoice
|
||||
|
||||
endmenu
|
@@ -1,6 +0,0 @@
|
||||
dependencies:
|
||||
idf: ">=4.1"
|
||||
espressif/esp-modbus:
|
||||
version: "^1.0"
|
||||
mb_example_common:
|
||||
path: ${IDF_PATH}/examples/protocols/modbus/mb_example_common
|
@@ -1,314 +0,0 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2016-2023 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
#include "string.h"
|
||||
#include "esp_log.h"
|
||||
#include "modbus_params.h" // for modbus parameters structures
|
||||
#include "mbcontroller.h"
|
||||
#include "sdkconfig.h"
|
||||
|
||||
#define MB_PORT_NUM (CONFIG_MB_UART_PORT_NUM) // Number of UART port used for Modbus connection
|
||||
#define MB_DEV_SPEED (CONFIG_MB_UART_BAUD_RATE) // The communication speed of the UART
|
||||
|
||||
// Note: Some pins on target chip cannot be assigned for UART communication.
|
||||
// See UART documentation for selected board and target to configure pins using Kconfig.
|
||||
|
||||
// The number of parameters that intended to be used in the particular control process
|
||||
#define MASTER_MAX_CIDS num_device_parameters
|
||||
|
||||
// Number of reading of parameters from slave
|
||||
#define MASTER_MAX_RETRY 30
|
||||
|
||||
// Timeout to update cid over Modbus
|
||||
#define UPDATE_CIDS_TIMEOUT_MS (500)
|
||||
#define UPDATE_CIDS_TIMEOUT_TICS (UPDATE_CIDS_TIMEOUT_MS / portTICK_PERIOD_MS)
|
||||
|
||||
// Timeout between polls
|
||||
#define POLL_TIMEOUT_MS (1)
|
||||
#define POLL_TIMEOUT_TICS (POLL_TIMEOUT_MS / portTICK_PERIOD_MS)
|
||||
|
||||
// The macro to get offset for parameter in the appropriate structure
|
||||
#define HOLD_OFFSET(field) ((uint16_t)(offsetof(holding_reg_params_t, field) + 1))
|
||||
#define INPUT_OFFSET(field) ((uint16_t)(offsetof(input_reg_params_t, field) + 1))
|
||||
#define COIL_OFFSET(field) ((uint16_t)(offsetof(coil_reg_params_t, field) + 1))
|
||||
// Discrete offset macro
|
||||
#define DISCR_OFFSET(field) ((uint16_t)(offsetof(discrete_reg_params_t, field) + 1))
|
||||
|
||||
#define STR(fieldname) ((const char*)( fieldname ))
|
||||
// Options can be used as bit masks or parameter limits
|
||||
#define OPTS(min_val, max_val, step_val) { .opt1 = min_val, .opt2 = max_val, .opt3 = step_val }
|
||||
|
||||
static const char *TAG = "MASTER_TEST";
|
||||
|
||||
// Enumeration of modbus device addresses accessed by master device
|
||||
enum {
|
||||
MB_DEVICE_ADDR1 = 1 // Only one slave device used for the test (add other slave addresses here)
|
||||
};
|
||||
|
||||
// Enumeration of all supported CIDs for device (used in parameter definition table)
|
||||
enum {
|
||||
CID_INP_DATA_0 = 0,
|
||||
CID_HOLD_DATA_0,
|
||||
CID_INP_DATA_1,
|
||||
CID_HOLD_DATA_1,
|
||||
CID_INP_DATA_2,
|
||||
CID_HOLD_DATA_2,
|
||||
CID_HOLD_TEST_REG,
|
||||
CID_RELAY_P1,
|
||||
CID_RELAY_P2,
|
||||
CID_DISCR_P1,
|
||||
CID_COUNT
|
||||
};
|
||||
|
||||
// Example Data (Object) Dictionary for Modbus parameters:
|
||||
// The CID field in the table must be unique.
|
||||
// Modbus Slave Addr field defines slave address of the device with correspond parameter.
|
||||
// Modbus Reg Type - Type of Modbus register area (Holding register, Input Register and such).
|
||||
// Reg Start field defines the start Modbus register number and Reg Size defines the number of registers for the characteristic accordingly.
|
||||
// The Instance Offset defines offset in the appropriate parameter structure that will be used as instance to save parameter value.
|
||||
// Data Type, Data Size specify type of the characteristic and its data size.
|
||||
// Parameter Options field specifies the options that can be used to process parameter value (limits or masks).
|
||||
// Access Mode - can be used to implement custom options for processing of characteristic (Read/Write restrictions, factory mode values and etc).
|
||||
const mb_parameter_descriptor_t device_parameters[] = {
|
||||
// { CID, Param Name, Units, Modbus Slave Addr, Modbus Reg Type, Reg Start, Reg Size, Instance Offset, Data Type, Data Size, Parameter Options, Access Mode}
|
||||
{ CID_INP_DATA_0, STR("Data_channel_0"), STR("Volts"), MB_DEVICE_ADDR1, MB_PARAM_INPUT, 0, 2,
|
||||
INPUT_OFFSET(input_data0), PARAM_TYPE_FLOAT, 4, OPTS( -10, 10, 1 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_HOLD_DATA_0, STR("Humidity_1"), STR("%rH"), MB_DEVICE_ADDR1, MB_PARAM_HOLDING, 0, 2,
|
||||
HOLD_OFFSET(holding_data0), PARAM_TYPE_FLOAT, 4, OPTS( 0, 100, 1 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_INP_DATA_1, STR("Temperature_1"), STR("C"), MB_DEVICE_ADDR1, MB_PARAM_INPUT, 2, 2,
|
||||
INPUT_OFFSET(input_data1), PARAM_TYPE_FLOAT, 4, OPTS( -40, 100, 1 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_HOLD_DATA_1, STR("Humidity_2"), STR("%rH"), MB_DEVICE_ADDR1, MB_PARAM_HOLDING, 2, 2,
|
||||
HOLD_OFFSET(holding_data1), PARAM_TYPE_FLOAT, 4, OPTS( 0, 100, 1 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_INP_DATA_2, STR("Temperature_2"), STR("C"), MB_DEVICE_ADDR1, MB_PARAM_INPUT, 4, 2,
|
||||
INPUT_OFFSET(input_data2), PARAM_TYPE_FLOAT, 4, OPTS( -40, 100, 1 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_HOLD_DATA_2, STR("Humidity_3"), STR("%rH"), MB_DEVICE_ADDR1, MB_PARAM_HOLDING, 4, 2,
|
||||
HOLD_OFFSET(holding_data2), PARAM_TYPE_FLOAT, 4, OPTS( 0, 100, 1 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_HOLD_TEST_REG, STR("Test_regs"), STR("__"), MB_DEVICE_ADDR1, MB_PARAM_HOLDING, 10, 58,
|
||||
HOLD_OFFSET(test_regs), PARAM_TYPE_ASCII, 116, OPTS( 0, 100, 1 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_RELAY_P1, STR("RelayP1"), STR("on/off"), MB_DEVICE_ADDR1, MB_PARAM_COIL, 2, 6,
|
||||
COIL_OFFSET(coils_port0), PARAM_TYPE_U8, 1, OPTS( 0xAA, 0x15, 0 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_RELAY_P2, STR("RelayP2"), STR("on/off"), MB_DEVICE_ADDR1, MB_PARAM_COIL, 10, 6,
|
||||
COIL_OFFSET(coils_port1), PARAM_TYPE_U8, 1, OPTS( 0x55, 0x2A, 0 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_DISCR_P1, STR("DiscreteInpP1"), STR("on/off"), MB_DEVICE_ADDR1, MB_PARAM_DISCRETE, 2, 7,
|
||||
DISCR_OFFSET(discrete_input_port1), PARAM_TYPE_U8, 1, OPTS( 0xAA, 0x15, 0 ), PAR_PERMS_READ_WRITE_TRIGGER }
|
||||
};
|
||||
|
||||
// Calculate number of parameters in the table
|
||||
const uint16_t num_device_parameters = (sizeof(device_parameters)/sizeof(device_parameters[0]));
|
||||
|
||||
// The function to get pointer to parameter storage (instance) according to parameter description table
|
||||
static void* master_get_param_data(const mb_parameter_descriptor_t* param_descriptor)
|
||||
{
|
||||
assert(param_descriptor != NULL);
|
||||
void* instance_ptr = NULL;
|
||||
if (param_descriptor->param_offset != 0) {
|
||||
switch(param_descriptor->mb_param_type)
|
||||
{
|
||||
case MB_PARAM_HOLDING:
|
||||
instance_ptr = ((void*)&holding_reg_params + param_descriptor->param_offset - 1);
|
||||
break;
|
||||
case MB_PARAM_INPUT:
|
||||
instance_ptr = ((void*)&input_reg_params + param_descriptor->param_offset - 1);
|
||||
break;
|
||||
case MB_PARAM_COIL:
|
||||
instance_ptr = ((void*)&coil_reg_params + param_descriptor->param_offset - 1);
|
||||
break;
|
||||
case MB_PARAM_DISCRETE:
|
||||
instance_ptr = ((void*)&discrete_reg_params + param_descriptor->param_offset - 1);
|
||||
break;
|
||||
default:
|
||||
instance_ptr = NULL;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Wrong parameter offset for CID #%u", (unsigned)param_descriptor->cid);
|
||||
assert(instance_ptr != NULL);
|
||||
}
|
||||
return instance_ptr;
|
||||
}
|
||||
|
||||
// User operation function to read slave values and check alarm
|
||||
static void master_operation_func(void *arg)
|
||||
{
|
||||
esp_err_t err = ESP_OK;
|
||||
float value = 0;
|
||||
bool alarm_state = false;
|
||||
const mb_parameter_descriptor_t* param_descriptor = NULL;
|
||||
|
||||
ESP_LOGI(TAG, "Start modbus test...");
|
||||
|
||||
for(uint16_t retry = 0; retry <= MASTER_MAX_RETRY && (!alarm_state); retry++) {
|
||||
// Read all found characteristics from slave(s)
|
||||
for (uint16_t cid = 0; (err != ESP_ERR_NOT_FOUND) && cid < MASTER_MAX_CIDS; cid++)
|
||||
{
|
||||
// Get data from parameters description table
|
||||
// and use this information to fill the characteristics description table
|
||||
// and having all required fields in just one table
|
||||
err = mbc_master_get_cid_info(cid, ¶m_descriptor);
|
||||
if ((err != ESP_ERR_NOT_FOUND) && (param_descriptor != NULL)) {
|
||||
void* temp_data_ptr = master_get_param_data(param_descriptor);
|
||||
assert(temp_data_ptr);
|
||||
uint8_t type = 0;
|
||||
if ((param_descriptor->param_type == PARAM_TYPE_ASCII) &&
|
||||
(param_descriptor->cid == CID_HOLD_TEST_REG)) {
|
||||
// Check for long array of registers of type PARAM_TYPE_ASCII
|
||||
err = mbc_master_get_parameter(cid, (char*)param_descriptor->param_key,
|
||||
(uint8_t*)temp_data_ptr, &type);
|
||||
if (err == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Characteristic #%u %s (%s) value = (0x%" PRIx32 ") read successful.",
|
||||
param_descriptor->cid,
|
||||
param_descriptor->param_key,
|
||||
param_descriptor->param_units,
|
||||
*(uint32_t*)temp_data_ptr);
|
||||
// Initialize data of test array and write to slave
|
||||
if (*(uint32_t*)temp_data_ptr != 0xAAAAAAAA) {
|
||||
memset((void*)temp_data_ptr, 0xAA, param_descriptor->param_size);
|
||||
*(uint32_t*)temp_data_ptr = 0xAAAAAAAA;
|
||||
err = mbc_master_set_parameter(cid, (char*)param_descriptor->param_key,
|
||||
(uint8_t*)temp_data_ptr, &type);
|
||||
if (err == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Characteristic #%u %s (%s) value = (0x%" PRIx32 "), write successful.",
|
||||
param_descriptor->cid,
|
||||
param_descriptor->param_key,
|
||||
param_descriptor->param_units,
|
||||
*(uint32_t*)temp_data_ptr);
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Characteristic #%u (%s) write fail, err = 0x%x (%s).",
|
||||
param_descriptor->cid,
|
||||
param_descriptor->param_key,
|
||||
(int)err,
|
||||
(char*)esp_err_to_name(err));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Characteristic #%u (%s) read fail, err = 0x%x (%s).",
|
||||
param_descriptor->cid,
|
||||
param_descriptor->param_key,
|
||||
(int)err,
|
||||
(char*)esp_err_to_name(err));
|
||||
}
|
||||
} else {
|
||||
err = mbc_master_get_parameter(cid, (char*)param_descriptor->param_key,
|
||||
(uint8_t*)temp_data_ptr, &type);
|
||||
if (err == ESP_OK) {
|
||||
if ((param_descriptor->mb_param_type == MB_PARAM_HOLDING) ||
|
||||
(param_descriptor->mb_param_type == MB_PARAM_INPUT)) {
|
||||
value = *(float*)temp_data_ptr;
|
||||
ESP_LOGI(TAG, "Characteristic #%u %s (%s) value = %f (0x%" PRIx32 ") read successful.",
|
||||
param_descriptor->cid,
|
||||
param_descriptor->param_key,
|
||||
param_descriptor->param_units,
|
||||
value,
|
||||
*(uint32_t*)temp_data_ptr);
|
||||
if (((value > param_descriptor->param_opts.max) ||
|
||||
(value < param_descriptor->param_opts.min))) {
|
||||
alarm_state = true;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
uint8_t state = *(uint8_t*)temp_data_ptr;
|
||||
const char* rw_str = (state & param_descriptor->param_opts.opt1) ? "ON" : "OFF";
|
||||
if ((state & param_descriptor->param_opts.opt2) == param_descriptor->param_opts.opt2) {
|
||||
ESP_LOGI(TAG, "Characteristic #%u %s (%s) value = %s (0x%" PRIx8 ") read successful.",
|
||||
param_descriptor->cid,
|
||||
param_descriptor->param_key,
|
||||
param_descriptor->param_units,
|
||||
(const char*)rw_str,
|
||||
*(uint8_t*)temp_data_ptr);
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Characteristic #%u %s (%s) value = %s (0x%" PRIx8 "), unexpected value.",
|
||||
param_descriptor->cid,
|
||||
param_descriptor->param_key,
|
||||
param_descriptor->param_units,
|
||||
(const char*)rw_str,
|
||||
*(uint8_t*)temp_data_ptr);
|
||||
alarm_state = true;
|
||||
break;
|
||||
}
|
||||
if (state & param_descriptor->param_opts.opt1) {
|
||||
alarm_state = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Characteristic #%u (%s) read fail, err = 0x%x (%s).",
|
||||
param_descriptor->cid,
|
||||
param_descriptor->param_key,
|
||||
(int)err,
|
||||
(char*)esp_err_to_name(err));
|
||||
}
|
||||
}
|
||||
vTaskDelay(POLL_TIMEOUT_TICS); // timeout between polls
|
||||
}
|
||||
}
|
||||
vTaskDelay(UPDATE_CIDS_TIMEOUT_TICS);
|
||||
}
|
||||
|
||||
if (alarm_state) {
|
||||
ESP_LOGI(TAG, "Alarm triggered by cid #%u.", param_descriptor->cid);
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Alarm is not triggered after %u retries.", MASTER_MAX_RETRY);
|
||||
}
|
||||
ESP_LOGI(TAG, "Destroy master...");
|
||||
ESP_ERROR_CHECK(mbc_master_destroy());
|
||||
}
|
||||
|
||||
// Modbus master initialization
|
||||
static esp_err_t master_init(void)
|
||||
{
|
||||
// Initialize and start Modbus controller
|
||||
mb_communication_info_t comm = {
|
||||
.port = MB_PORT_NUM,
|
||||
#if CONFIG_MB_COMM_MODE_ASCII
|
||||
.mode = MB_MODE_ASCII,
|
||||
#elif CONFIG_MB_COMM_MODE_RTU
|
||||
.mode = MB_MODE_RTU,
|
||||
#endif
|
||||
.baudrate = MB_DEV_SPEED,
|
||||
.parity = MB_PARITY_NONE
|
||||
};
|
||||
void* master_handler = NULL;
|
||||
|
||||
esp_err_t err = mbc_master_init(MB_PORT_SERIAL_MASTER, &master_handler);
|
||||
MB_RETURN_ON_FALSE((master_handler != NULL), ESP_ERR_INVALID_STATE, TAG,
|
||||
"mb controller initialization fail.");
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE, TAG,
|
||||
"mb controller initialization fail, returns(0x%x).", (int)err);
|
||||
err = mbc_master_setup((void*)&comm);
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE, TAG,
|
||||
"mb controller setup fail, returns(0x%x).", (int)err);
|
||||
|
||||
// Set UART pin numbers
|
||||
err = uart_set_pin(MB_PORT_NUM, CONFIG_MB_UART_TXD, CONFIG_MB_UART_RXD,
|
||||
CONFIG_MB_UART_RTS, UART_PIN_NO_CHANGE);
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE, TAG,
|
||||
"mb serial set pin failure, uart_set_pin() returned (0x%x).", (int)err);
|
||||
|
||||
err = mbc_master_start();
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE, TAG,
|
||||
"mb controller start fail, returned (0x%x).", (int)err);
|
||||
|
||||
// Set driver mode to Half Duplex
|
||||
err = uart_set_mode(MB_PORT_NUM, UART_MODE_RS485_HALF_DUPLEX);
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE, TAG,
|
||||
"mb serial set mode failure, uart_set_mode() returned (0x%x).", (int)err);
|
||||
|
||||
vTaskDelay(5);
|
||||
err = mbc_master_set_descriptor(&device_parameters[0], num_device_parameters);
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE, TAG,
|
||||
"mb controller set descriptor fail, returns(0x%x).", (int)err);
|
||||
ESP_LOGI(TAG, "Modbus master stack initialized...");
|
||||
return err;
|
||||
}
|
||||
|
||||
void app_main(void)
|
||||
{
|
||||
// Initialization of device peripheral and objects
|
||||
ESP_ERROR_CHECK(master_init());
|
||||
vTaskDelay(10);
|
||||
|
||||
master_operation_func(NULL);
|
||||
}
|
@@ -1,9 +0,0 @@
|
||||
#
|
||||
# Modbus configuration
|
||||
#
|
||||
CONFIG_FMB_TIMER_PORT_ENABLED=n
|
||||
CONFIG_MB_COMM_MODE_ASCII=y
|
||||
CONFIG_MB_UART_BAUD_RATE=115200
|
||||
CONFIG_FMB_MASTER_DELAY_MS_CONVERT=200
|
||||
CONFIG_FMB_MASTER_TIMEOUT_MS_RESPOND=400
|
||||
CONFIG_FMB_TIMER_USE_ISR_DISPATCH_METHOD=y
|
@@ -1,9 +0,0 @@
|
||||
# The following lines of boilerplate have to be in your project's CMakeLists
|
||||
# in this exact order for cmake to work correctly
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
# "Trim" the build. Include the minimal set of components, main, and anything it depends on.
|
||||
idf_build_set_property(MINIMAL_BUILD ON)
|
||||
|
||||
project(modbus_slave)
|
@@ -1,97 +0,0 @@
|
||||
| Supported Targets | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C5 | ESP32-C6 | ESP32-C61 | ESP32-H2 | ESP32-P4 | ESP32-S2 | ESP32-S3 |
|
||||
| ----------------- | ----- | -------- | -------- | -------- | -------- | --------- | -------- | -------- | -------- | -------- |
|
||||
|
||||
# Modbus Slave Example
|
||||
|
||||
This example demonstrates using the port of the FreeModbus stack on an ESP32 target where the ESP32 target is operating as a network slave. The example allows an external Modbus host to read/write device parameters on the ESP32 target using the Modbus protocol. The parameters accessible through Modbus are located in `mb_example_common/modbus_params.h\c` source/header files that users can update to add/remove their own custom parameters.
|
||||
These are represented in structures `holding_reg_params`, `input_reg_params`, `coil_reg_params`, `discrete_reg_params` for holding registers, input parameters, coils and discrete inputs accordingly. The app_main application demonstrates how to setup Modbus stack and use notifications about parameters change from host system.
|
||||
The FreeModbus stack located in `components/freemodbus` folder and contains the `/port` folder where the stack's port to the ESP32 is situated. There are some parameters of the port that can be configured in KConfig file to start stack correctly (See description below for more information).
|
||||
|
||||
The slave example uses shared parameter structures defined in `examples/protocols/modbus/mb_example_common` folder.
|
||||
|
||||
## Hardware required :
|
||||
Option 1:
|
||||
PC + USB Serial adapter connected to USB port + RS485 line drivers + ESP32 based board.
|
||||
The MAX485 line driver is used as an example below but other similar chips can be used as well.
|
||||
|
||||
Option 2:
|
||||
The modbus_master example application configured as described in its README.md file and flashed into ESP32 based board.
|
||||
Note: The ```Example Data (Object) Dictionary``` in the modbus_master example can be edited to address parameters from other slaves connected into Modbus segment.
|
||||
|
||||
RS485 example circuit schematic:
|
||||
```
|
||||
VCC ---------------+ +--------------- VCC
|
||||
| |
|
||||
+-------x-------+ +-------x-------+
|
||||
RXD <------| RO | DIFFERENTIAL | RO|-----> RXD
|
||||
| B|---------------|B |
|
||||
TXD ------>| DI MAX485 | \ / | MAX485 DI|<----- TXD
|
||||
ESP32 board | | RS-485 side | | Modbus master
|
||||
RTS --+--->| DE | / \ | DE|---+
|
||||
| | A|---------------|A | |
|
||||
+----| /RE | PAIR | /RE|---+-- RTS
|
||||
+-------x--------+ +-------x-------+
|
||||
| |
|
||||
--- ---
|
||||
```
|
||||
|
||||
## How to setup and use an example:
|
||||
|
||||
### Configure the application
|
||||
Start the command below to show the configuration menu:
|
||||
```
|
||||
idf.py menuconfig
|
||||
```
|
||||
Select Modbus Example Configuration menu item.
|
||||
Configure the UART pins used for modbus communication using the command and table below.
|
||||
```
|
||||
------------------------------------------------------------------------------------------------------------------------------
|
||||
| UART Interface | #define | Default pins for | Default pins for ESP32-S2 | External RS485 Driver Pin |
|
||||
| | | ESP32 (C6, P4) | (S3, C3, C2, C5, H2, C61) | |
|
||||
| ----------------------|--------------------|-----------------------|---------------------------|---------------------------|
|
||||
| Transmit Data (TxD) | CONFIG_MB_UART_TXD | GPIO23 | GPIO9 | DI |
|
||||
| Receive Data (RxD) | CONFIG_MB_UART_RXD | GPIO22 | GPIO8 | RO |
|
||||
| Request To Send (RTS) | CONFIG_MB_UART_RTS | GPIO18 | GPIO10 | ~RE/DE |
|
||||
| Ground | n/a | GND | GND | GND |
|
||||
------------------------------------------------------------------------------------------------------------------------------
|
||||
```
|
||||
Note: Each target chip has different GPIO pins available for UART connection. Please refer to UART documentation for selected target for more information.
|
||||
|
||||
Define the ```Modbus communiction mode``` for slave in Kconfig - CONFIG_MB_COMM_MODE (must be the same for master and slave application).
|
||||
Set ```Modbus slave address``` for the example application (by default for example script is set to 1).
|
||||
The communication parameters of freemodbus stack (Component config->Modbus configuration) allow to configure it appropriately but usually it is enough to use default settings.
|
||||
See the help strings of parameters for more information.
|
||||
|
||||
### Setup external Modbus master software
|
||||
Option 1:
|
||||
Configure the external Modbus master software according to port configuration parameters used in application.
|
||||
As an example the Modbus Poll application can be used with this example.
|
||||
Option 2:
|
||||
Setup ESP32 based board and set modbus_master example configuration as described in its README.md file.
|
||||
Setup one or more slave boards with different slave addresses and connect them into the same Modbus segment (See configuration above).
|
||||
Note: The ```Modbus communiction mode``` parameter must be the same for master and slave example application to be able to communicate with each other.
|
||||
|
||||
### Build and flash software
|
||||
Build the project and flash it to the board, then run monitor tool to view serial output:
|
||||
```
|
||||
idf.py -p PORT flash monitor
|
||||
```
|
||||
|
||||
(To exit the serial monitor, type ``Ctrl-]``.)
|
||||
|
||||
See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects.
|
||||
|
||||
## Example Output
|
||||
Example output of the application:
|
||||
```
|
||||
I (13941) SLAVE_TEST: INPUT READ (13651163 us), ADDR:1, TYPE:8, INST_ADDR:0x3ffb2fd0, SIZE:2
|
||||
I (13951) SLAVE_TEST: HOLDING READ (13656431 us), ADDR:1, TYPE:2, INST_ADDR:0x3ffb2fe0, SIZE:2
|
||||
I (13961) SLAVE_TEST: INPUT READ (13665877 us), ADDR:3, TYPE:8, INST_ADDR:0x3ffb2fd4, SIZE:2
|
||||
I (13971) SLAVE_TEST: HOLDING READ (13676010 us), ADDR:3, TYPE:2, INST_ADDR:0x3ffb2fe4, SIZE:2
|
||||
I (13981) SLAVE_TEST: INPUT READ (13686130 us), ADDR:5, TYPE:8, INST_ADDR:0x3ffb2fd8, SIZE:2
|
||||
I (13991) SLAVE_TEST: HOLDING READ (13696267 us), ADDR:5, TYPE:2, INST_ADDR:0x3ffb2fe8, SIZE:2
|
||||
I (14001) SLAVE_TEST: COILS READ (13706331 us), ADDR:0, TYPE:32, INST_ADDR:0x3ffb2fcc, SIZE:8
|
||||
I (14001) SLAVE_TEST: Modbus controller destroyed.
|
||||
```
|
||||
The output lines describe type of operation, its timestamp, modbus address, access type, storage address in parameter structure and number of registers accordingly.
|
||||
|
@@ -1,4 +0,0 @@
|
||||
set(PROJECT_NAME "modbus_slave")
|
||||
|
||||
idf_component_register(SRCS "slave.c"
|
||||
INCLUDE_DIRS ".")
|
@@ -1,92 +0,0 @@
|
||||
menu "Modbus Example Configuration"
|
||||
|
||||
orsource "$IDF_PATH/examples/common_components/env_caps/$IDF_TARGET/Kconfig.env_caps"
|
||||
|
||||
config MB_UART_PORT_ONE
|
||||
bool
|
||||
default y
|
||||
depends on (ESP_CONSOLE_UART_NUM !=1) && (SOC_UART_HP_NUM > 1)
|
||||
|
||||
config MB_UART_PORT_TWO
|
||||
bool
|
||||
default y
|
||||
depends on (ESP_CONSOLE_UART_NUM !=2) && (SOC_UART_HP_NUM > 2)
|
||||
|
||||
config MB_UART_PORT_NUM
|
||||
int "UART port number"
|
||||
range 0 2 if MB_UART_PORT_TWO
|
||||
default 2 if MB_UART_PORT_TWO
|
||||
range 0 1 if MB_UART_PORT_ONE
|
||||
default 1 if MB_UART_PORT_ONE
|
||||
help
|
||||
UART communication port number for Modbus example.
|
||||
|
||||
config MB_UART_BAUD_RATE
|
||||
int "UART communication speed"
|
||||
range 1200 115200
|
||||
default 115200
|
||||
help
|
||||
UART communication speed for Modbus example.
|
||||
|
||||
config MB_UART_RXD
|
||||
int "UART RXD pin number"
|
||||
range ENV_GPIO_RANGE_MIN ENV_GPIO_IN_RANGE_MAX
|
||||
default 22 if IDF_TARGET_ESP32 || IDF_TARGET_ESP32C6 || IDF_TARGET_ESP32P4
|
||||
default 8 if IDF_TARGET_ESP32S2 || IDF_TARGET_ESP32S3 || IDF_TARGET_ESP32C3
|
||||
default 8 if IDF_TARGET_ESP32C2 || IDF_TARGET_ESP32H2 || IDF_TARGET_ESP32C5
|
||||
default 8 if IDF_TARGET_ESP32C61
|
||||
help
|
||||
GPIO number for UART RX pin. See UART documentation for more information
|
||||
about available pin numbers for UART.
|
||||
|
||||
config MB_UART_TXD
|
||||
int "UART TXD pin number"
|
||||
range ENV_GPIO_RANGE_MIN ENV_GPIO_OUT_RANGE_MAX
|
||||
default 23 if IDF_TARGET_ESP32 || IDF_TARGET_ESP32C6 || IDF_TARGET_ESP32P4
|
||||
default 9 if IDF_TARGET_ESP32S2 || IDF_TARGET_ESP32S3 || IDF_TARGET_ESP32C3
|
||||
default 9 if IDF_TARGET_ESP32C2 || IDF_TARGET_ESP32H2 || IDF_TARGET_ESP32C5
|
||||
default 9 if IDF_TARGET_ESP32C61
|
||||
help
|
||||
GPIO number for UART TX pin. See UART documentation for more information
|
||||
about available pin numbers for UART.
|
||||
|
||||
config MB_UART_RTS
|
||||
int "UART RTS pin number"
|
||||
range ENV_GPIO_RANGE_MIN ENV_GPIO_OUT_RANGE_MAX
|
||||
default 20 if IDF_TARGET_ESP32P4
|
||||
default 18 if IDF_TARGET_ESP32 || IDF_TARGET_ESP32C6
|
||||
default 10 if IDF_TARGET_ESP32S2 || IDF_TARGET_ESP32S3 || IDF_TARGET_ESP32C3
|
||||
default 10 if IDF_TARGET_ESP32C2 || IDF_TARGET_ESP32H2 || IDF_TARGET_ESP32C5
|
||||
default 10 if IDF_TARGET_ESP32C61
|
||||
help
|
||||
GPIO number for UART RTS pin. This pin is connected to
|
||||
~RE/DE pin of RS485 transceiver to switch direction.
|
||||
See UART documentation for more information about available pin
|
||||
numbers for UART.
|
||||
|
||||
choice MB_COMM_MODE
|
||||
prompt "Modbus communication mode"
|
||||
default MB_COMM_MODE_RTU if CONFIG_FMB_COMM_MODE_RTU_EN
|
||||
help
|
||||
Selection of Modbus communication mode option for Modbus.
|
||||
|
||||
config MB_COMM_MODE_RTU
|
||||
bool "RTU mode"
|
||||
depends on FMB_COMM_MODE_RTU_EN
|
||||
|
||||
config MB_COMM_MODE_ASCII
|
||||
bool "ASCII mode"
|
||||
depends on FMB_COMM_MODE_ASCII_EN
|
||||
|
||||
endchoice
|
||||
|
||||
config MB_SLAVE_ADDR
|
||||
int "Modbus slave address"
|
||||
range 1 127
|
||||
default 1
|
||||
help
|
||||
This is the Modbus slave address in the network.
|
||||
It is used to organize Modbus network with several slaves connected into the same segment.
|
||||
|
||||
|
||||
endmenu
|
@@ -1,6 +0,0 @@
|
||||
dependencies:
|
||||
idf: ">=4.1"
|
||||
espressif/esp-modbus:
|
||||
version: "^1.0"
|
||||
mb_example_common:
|
||||
path: ${IDF_PATH}/examples/protocols/modbus/mb_example_common
|
@@ -1,229 +0,0 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2016-2023 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
// FreeModbus Slave Example ESP32
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include "esp_err.h"
|
||||
#include "mbcontroller.h" // for mbcontroller defines and api
|
||||
#include "modbus_params.h" // for modbus parameters structures
|
||||
#include "esp_log.h" // for log_write
|
||||
#include "sdkconfig.h"
|
||||
|
||||
#define MB_PORT_NUM (CONFIG_MB_UART_PORT_NUM) // Number of UART port used for Modbus connection
|
||||
#define MB_SLAVE_ADDR (CONFIG_MB_SLAVE_ADDR) // The address of device in Modbus network
|
||||
#define MB_DEV_SPEED (CONFIG_MB_UART_BAUD_RATE) // The communication speed of the UART
|
||||
|
||||
// Note: Some pins on target chip cannot be assigned for UART communication.
|
||||
// Please refer to documentation for selected board and target to configure pins using Kconfig.
|
||||
|
||||
// Defines below are used to define register start address for each type of Modbus registers
|
||||
#define HOLD_OFFSET(field) ((uint16_t)(offsetof(holding_reg_params_t, field) >> 1))
|
||||
#define INPUT_OFFSET(field) ((uint16_t)(offsetof(input_reg_params_t, field) >> 1))
|
||||
#define MB_REG_DISCRETE_INPUT_START (0x0000)
|
||||
#define MB_REG_COILS_START (0x0000)
|
||||
#define MB_REG_INPUT_START_AREA0 (INPUT_OFFSET(input_data0)) // register offset input area 0
|
||||
#define MB_REG_INPUT_START_AREA1 (INPUT_OFFSET(input_data4)) // register offset input area 1
|
||||
#define MB_REG_HOLDING_START_AREA0 (HOLD_OFFSET(holding_data0))
|
||||
#define MB_REG_HOLDING_START_AREA1 (HOLD_OFFSET(holding_data4))
|
||||
|
||||
#define MB_PAR_INFO_GET_TOUT (10) // Timeout for get parameter info
|
||||
#define MB_CHAN_DATA_MAX_VAL (6)
|
||||
#define MB_CHAN_DATA_OFFSET (0.2f)
|
||||
#define MB_READ_MASK (MB_EVENT_INPUT_REG_RD \
|
||||
| MB_EVENT_HOLDING_REG_RD \
|
||||
| MB_EVENT_DISCRETE_RD \
|
||||
| MB_EVENT_COILS_RD)
|
||||
#define MB_WRITE_MASK (MB_EVENT_HOLDING_REG_WR \
|
||||
| MB_EVENT_COILS_WR)
|
||||
#define MB_READ_WRITE_MASK (MB_READ_MASK | MB_WRITE_MASK)
|
||||
|
||||
static const char *TAG = "SLAVE_TEST";
|
||||
|
||||
static portMUX_TYPE param_lock = portMUX_INITIALIZER_UNLOCKED;
|
||||
|
||||
// Set register values into known state
|
||||
static void setup_reg_data(void)
|
||||
{
|
||||
// Define initial state of parameters
|
||||
discrete_reg_params.discrete_input0 = 1;
|
||||
discrete_reg_params.discrete_input1 = 0;
|
||||
discrete_reg_params.discrete_input2 = 1;
|
||||
discrete_reg_params.discrete_input3 = 0;
|
||||
discrete_reg_params.discrete_input4 = 1;
|
||||
discrete_reg_params.discrete_input5 = 0;
|
||||
discrete_reg_params.discrete_input6 = 1;
|
||||
discrete_reg_params.discrete_input7 = 0;
|
||||
|
||||
holding_reg_params.holding_data0 = 1.34;
|
||||
holding_reg_params.holding_data1 = 2.56;
|
||||
holding_reg_params.holding_data2 = 3.78;
|
||||
holding_reg_params.holding_data3 = 4.90;
|
||||
|
||||
holding_reg_params.holding_data4 = 5.67;
|
||||
holding_reg_params.holding_data5 = 6.78;
|
||||
holding_reg_params.holding_data6 = 7.79;
|
||||
holding_reg_params.holding_data7 = 8.80;
|
||||
|
||||
coil_reg_params.coils_port0 = 0x55;
|
||||
coil_reg_params.coils_port1 = 0xAA;
|
||||
|
||||
input_reg_params.input_data0 = 1.12;
|
||||
input_reg_params.input_data1 = 2.34;
|
||||
input_reg_params.input_data2 = 3.56;
|
||||
input_reg_params.input_data3 = 4.78;
|
||||
|
||||
input_reg_params.input_data4 = 1.12;
|
||||
input_reg_params.input_data5 = 2.34;
|
||||
input_reg_params.input_data6 = 3.56;
|
||||
input_reg_params.input_data7 = 4.78;
|
||||
}
|
||||
|
||||
// An example application of Modbus slave. It is based on freemodbus stack.
|
||||
// See deviceparams.h file for more information about assigned Modbus parameters.
|
||||
// These parameters can be accessed from main application and also can be changed
|
||||
// by external Modbus master host.
|
||||
void app_main(void)
|
||||
{
|
||||
mb_param_info_t reg_info; // keeps the Modbus registers access information
|
||||
mb_communication_info_t comm_info; // Modbus communication parameters
|
||||
mb_register_area_descriptor_t reg_area; // Modbus register area descriptor structure
|
||||
|
||||
// Set UART log level
|
||||
esp_log_level_set(TAG, ESP_LOG_INFO);
|
||||
void* mbc_slave_handler = NULL;
|
||||
|
||||
ESP_ERROR_CHECK(mbc_slave_init(MB_PORT_SERIAL_SLAVE, &mbc_slave_handler)); // Initialization of Modbus controller
|
||||
|
||||
// Setup communication mode and start stack
|
||||
#if CONFIG_MB_COMM_MODE_ASCII
|
||||
comm_info.mode = MB_MODE_ASCII;
|
||||
#elif CONFIG_MB_COMM_MODE_RTU
|
||||
comm_info.mode = MB_MODE_RTU;
|
||||
#endif
|
||||
comm_info.slave_addr = MB_SLAVE_ADDR;
|
||||
comm_info.port = MB_PORT_NUM;
|
||||
comm_info.baudrate = MB_DEV_SPEED;
|
||||
comm_info.parity = MB_PARITY_NONE;
|
||||
ESP_ERROR_CHECK(mbc_slave_setup((void*)&comm_info));
|
||||
|
||||
// The code below initializes Modbus register area descriptors
|
||||
// for Modbus Holding Registers, Input Registers, Coils and Discrete Inputs
|
||||
// Initialization should be done for each supported Modbus register area according to register map.
|
||||
// When external master trying to access the register in the area that is not initialized
|
||||
// by mbc_slave_set_descriptor() API call then Modbus stack
|
||||
// will send exception response for this register area.
|
||||
reg_area.type = MB_PARAM_HOLDING; // Set type of register area
|
||||
reg_area.start_offset = MB_REG_HOLDING_START_AREA0; // Offset of register area in Modbus protocol
|
||||
reg_area.address = (void*)&holding_reg_params.holding_data0; // Set pointer to storage instance
|
||||
// Set the size of register storage instance = 150 holding registers
|
||||
reg_area.size = (size_t)(HOLD_OFFSET(holding_data4) - HOLD_OFFSET(test_regs));
|
||||
ESP_ERROR_CHECK(mbc_slave_set_descriptor(reg_area));
|
||||
reg_area.type = MB_PARAM_HOLDING; // Set type of register area
|
||||
reg_area.start_offset = MB_REG_HOLDING_START_AREA1; // Offset of register area in Modbus protocol
|
||||
reg_area.address = (void*)&holding_reg_params.holding_data4; // Set pointer to storage instance
|
||||
reg_area.size = sizeof(float) << 2; // Set the size of register storage instance
|
||||
ESP_ERROR_CHECK(mbc_slave_set_descriptor(reg_area));
|
||||
|
||||
// Initialization of Input Registers area
|
||||
reg_area.type = MB_PARAM_INPUT;
|
||||
reg_area.start_offset = MB_REG_INPUT_START_AREA0;
|
||||
reg_area.address = (void*)&input_reg_params.input_data0;
|
||||
reg_area.size = sizeof(float) << 2;
|
||||
ESP_ERROR_CHECK(mbc_slave_set_descriptor(reg_area));
|
||||
reg_area.type = MB_PARAM_INPUT;
|
||||
reg_area.start_offset = MB_REG_INPUT_START_AREA1;
|
||||
reg_area.address = (void*)&input_reg_params.input_data4;
|
||||
reg_area.size = sizeof(float) << 2;
|
||||
ESP_ERROR_CHECK(mbc_slave_set_descriptor(reg_area));
|
||||
|
||||
// Initialization of Coils register area
|
||||
reg_area.type = MB_PARAM_COIL;
|
||||
reg_area.start_offset = MB_REG_COILS_START;
|
||||
reg_area.address = (void*)&coil_reg_params;
|
||||
reg_area.size = sizeof(coil_reg_params);
|
||||
ESP_ERROR_CHECK(mbc_slave_set_descriptor(reg_area));
|
||||
|
||||
// Initialization of Discrete Inputs register area
|
||||
reg_area.type = MB_PARAM_DISCRETE;
|
||||
reg_area.start_offset = MB_REG_DISCRETE_INPUT_START;
|
||||
reg_area.address = (void*)&discrete_reg_params;
|
||||
reg_area.size = sizeof(discrete_reg_params);
|
||||
ESP_ERROR_CHECK(mbc_slave_set_descriptor(reg_area));
|
||||
|
||||
setup_reg_data(); // Set values into known state
|
||||
|
||||
// Starts of modbus controller and stack
|
||||
ESP_ERROR_CHECK(mbc_slave_start());
|
||||
|
||||
// Set UART pin numbers
|
||||
ESP_ERROR_CHECK(uart_set_pin(MB_PORT_NUM, CONFIG_MB_UART_TXD,
|
||||
CONFIG_MB_UART_RXD, CONFIG_MB_UART_RTS,
|
||||
UART_PIN_NO_CHANGE));
|
||||
|
||||
// Set UART driver mode to Half Duplex
|
||||
ESP_ERROR_CHECK(uart_set_mode(MB_PORT_NUM, UART_MODE_RS485_HALF_DUPLEX));
|
||||
|
||||
ESP_LOGI(TAG, "Modbus slave stack initialized.");
|
||||
ESP_LOGI(TAG, "Start modbus test...");
|
||||
|
||||
// The cycle below will be terminated when parameter holdingRegParams.dataChan0
|
||||
// incremented each access cycle reaches the CHAN_DATA_MAX_VAL value.
|
||||
for(;holding_reg_params.holding_data0 < MB_CHAN_DATA_MAX_VAL;) {
|
||||
// Check for read/write events of Modbus master for certain events
|
||||
(void)mbc_slave_check_event(MB_READ_WRITE_MASK);
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(mbc_slave_get_param_info(®_info, MB_PAR_INFO_GET_TOUT));
|
||||
const char* rw_str = (reg_info.type & MB_READ_MASK) ? "READ" : "WRITE";
|
||||
// Filter events and process them accordingly
|
||||
if(reg_info.type & (MB_EVENT_HOLDING_REG_WR | MB_EVENT_HOLDING_REG_RD)) {
|
||||
// Get parameter information from parameter queue
|
||||
ESP_LOGI(TAG, "HOLDING %s (%" PRIu32 " us), ADDR:%u, TYPE:%u, INST_ADDR:0x%" PRIx32 ", SIZE:%u",
|
||||
rw_str,
|
||||
reg_info.time_stamp,
|
||||
(unsigned)reg_info.mb_offset,
|
||||
(unsigned)reg_info.type,
|
||||
(uint32_t)reg_info.address,
|
||||
(unsigned)reg_info.size);
|
||||
if (reg_info.address == (uint8_t*)&holding_reg_params.holding_data0)
|
||||
{
|
||||
portENTER_CRITICAL(¶m_lock);
|
||||
holding_reg_params.holding_data0 += MB_CHAN_DATA_OFFSET;
|
||||
if (holding_reg_params.holding_data0 >= (MB_CHAN_DATA_MAX_VAL - MB_CHAN_DATA_OFFSET)) {
|
||||
coil_reg_params.coils_port1 = 0xFF;
|
||||
}
|
||||
portEXIT_CRITICAL(¶m_lock);
|
||||
}
|
||||
} else if (reg_info.type & MB_EVENT_INPUT_REG_RD) {
|
||||
ESP_LOGI(TAG, "INPUT READ (%" PRIu32 " us), ADDR:%u, TYPE:%u, INST_ADDR:0x%" PRIx32 ", SIZE:%u",
|
||||
reg_info.time_stamp,
|
||||
(unsigned)reg_info.mb_offset,
|
||||
(unsigned)reg_info.type,
|
||||
(uint32_t)reg_info.address,
|
||||
(unsigned)reg_info.size);
|
||||
} else if (reg_info.type & MB_EVENT_DISCRETE_RD) {
|
||||
ESP_LOGI(TAG, "DISCRETE READ (%" PRIu32 " us): ADDR:%u, TYPE:%u, INST_ADDR:0x%" PRIx32 ", SIZE:%u",
|
||||
reg_info.time_stamp,
|
||||
(unsigned)reg_info.mb_offset,
|
||||
(unsigned)reg_info.type,
|
||||
(uint32_t)reg_info.address,
|
||||
(unsigned)reg_info.size);
|
||||
} else if (reg_info.type & (MB_EVENT_COILS_RD | MB_EVENT_COILS_WR)) {
|
||||
ESP_LOGI(TAG, "COILS %s (%" PRIu32 " us), ADDR:%u, TYPE:%u, INST_ADDR:0x%" PRIx32 ", SIZE:%u",
|
||||
rw_str,
|
||||
reg_info.time_stamp,
|
||||
(unsigned)reg_info.mb_offset,
|
||||
(unsigned)reg_info.type,
|
||||
(uint32_t)reg_info.address,
|
||||
(unsigned)reg_info.size);
|
||||
if (coil_reg_params.coils_port1 == 0xFF) break;
|
||||
}
|
||||
}
|
||||
// Destroy of Modbus controller on alarm
|
||||
ESP_LOGI(TAG,"Modbus controller destroyed.");
|
||||
vTaskDelay(100);
|
||||
ESP_ERROR_CHECK(mbc_slave_destroy());
|
||||
}
|
@@ -1,8 +0,0 @@
|
||||
#
|
||||
# Modbus configuration
|
||||
#
|
||||
CONFIG_MB_COMM_MODE_ASCII=y
|
||||
CONFIG_MB_SLAVE_ADDR=1
|
||||
CONFIG_MB_UART_BAUD_RATE=115200
|
||||
CONFIG_FMB_TIMER_PORT_ENABLED=y
|
||||
CONFIG_FMB_TIMER_USE_ISR_DISPATCH_METHOD=y
|
@@ -1,58 +0,0 @@
|
||||
# Modbus TCP Master-Slave Example
|
||||
|
||||
## Overview
|
||||
|
||||
These two projects illustrate the communication between Modbus master and slave device in the segment.
|
||||
Master initializes Modbus interface driver and then reads parameters from slave device in the segment.
|
||||
After several successful read attempts slave sets the alarm relay (end of test condition).
|
||||
Once master reads the alarm it stops communication and destroy driver.
|
||||
|
||||
The examples:
|
||||
|
||||
* `examples/protocols/modbus/tcp/mb_tcp_master` - Modbus TCP master
|
||||
* `examples/protocols/modbus/tcp/mb_tcp_slave` - Modbus TCP slave
|
||||
|
||||
See README.md for each individual project for more information.
|
||||
|
||||
## How to use example
|
||||
|
||||
### Hardware Required
|
||||
|
||||
This example can be run on any commonly available ESP32(-S2) development board.
|
||||
The master and slave boards should be connected to the same network (see the README.md file in example folder) and slave address `CONFIG_MB_SLAVE_ADDR` be defined for slave board(s).
|
||||
See the connection schematic in README.md files of each example.
|
||||
|
||||
### Configure the project
|
||||
|
||||
This example test requires communication mode setting for master and slave be the same and slave address set to 1.
|
||||
Please refer to README.md files of each example project for more information. This example uses the default option `CONFIG_MB_SLAVE_IP_FROM_STDIN` to resolve slave IP address and supports IPv4 address type for communication in this case.
|
||||
|
||||
## About common_component in this example
|
||||
|
||||
The folder "mb_example_common" one level above includes definitions of parameter structures for master and slave device (both projects share the same parameters).
|
||||
However, currently it is for example purpose only and can be modified for particular application.
|
||||
|
||||
## Example Output
|
||||
|
||||
Refer to README.md file in the appropriate example folder for more information about master and slave log output.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
If the examples do not work as expected and slave and master boards are not able to communicate correctly it is possible to find the reason for errors.
|
||||
The most important errors are described in master example output and formatted as below:
|
||||
|
||||
```
|
||||
E (1692332) MB_CONTROLLER_MASTER: mbc_master_get_parameter(111): SERIAL master get parameter failure error=(0x107) (ESP_ERR_TIMEOUT).
|
||||
```
|
||||
|
||||
ESP_ERR_TIMEOUT (0x107) - Modbus slave device does not respond during configured timeout.
|
||||
Check ability for communication pinging each slave configured in the master parameter description table or use command on your host machine to find modbus slave using mDNS (requires `CONFIG_MB_MDNS_IP_RESOLVER` option be enabled):
|
||||
```>dns-sd -L mb_slave_tcp_XX _modbus._tcp .```
|
||||
where XX is the short slave address (index) of the slave configured in the Kconfig of slave example.
|
||||
Also it is possible to increase Kconfig value `CONFIG_FMB_MASTER_TIMEOUT_MS_RESPOND` to compensate network communication delays between master and slaves.
|
||||
|
||||
ESP_ERR_NOT_SUPPORTED (0x106), ESP_ERR_INVALID_RESPONSE (0x108) - Modbus slave device does not support requested command or register and sent exeption response.
|
||||
|
||||
ESP_ERR_INVALID_STATE (0x103) - Modbus stack is not configured correctly or can't work correctly due to critical failure.
|
||||
|
||||
|
@@ -1,8 +0,0 @@
|
||||
# The following lines of boilerplate have to be in your project's CMakeLists
|
||||
# in this exact order for cmake to work correctly
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
# "Trim" the build. Include the minimal set of components, main, and anything it depends on.
|
||||
idf_build_set_property(MINIMAL_BUILD ON)
|
||||
project(modbus_tcp_master)
|
@@ -1,145 +0,0 @@
|
||||
| Supported Targets | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C5 | ESP32-C6 | ESP32-C61 | ESP32-H2 | ESP32-P4 | ESP32-S2 | ESP32-S3 |
|
||||
| ----------------- | ----- | -------- | -------- | -------- | -------- | --------- | -------- | -------- | -------- | -------- |
|
||||
|
||||
# Modbus TCP Master Example
|
||||
|
||||
This example demonstrates using of FreeModbus stack port implementation for ESP32 targets as a TCP master device.
|
||||
This implementation is able to read/write values of slave devices connected into Modbus segment. All parameters to be accessed are defined in data dictionary of the modbus master example source file.
|
||||
The values represented as characteristics with its name and characteristic CID which are linked into registers of slave devices connected into Modbus segment.
|
||||
The example implements simple control algorithm and checks parameters from slave device and gets alarm (relay in the slave device) when value of parameter exceeded limit.
|
||||
The instances for the modbus parameters are common for master and slave examples and located in `examples/protocols/modbus/mb_example_common` folder.
|
||||
|
||||
Example parameters definition:
|
||||
--------------------------------------------------------------------------------------------------
|
||||
| Slave Address | Characteristic ID | Characteristic name | Description |
|
||||
|---------------------|----------------------|----------------------|----------------------------|
|
||||
| MB_DEVICE_ADDR1 | CID_INP_DATA_0, | Data_channel_0 | Data channel 1 |
|
||||
| MB_DEVICE_ADDR1 | CID_HOLD_DATA_0, | Humidity_1 | Humidity 1 |
|
||||
| MB_DEVICE_ADDR1 | CID_INP_DATA_1 | Temperature_1 | Sensor temperature |
|
||||
| MB_DEVICE_ADDR1 | CID_HOLD_DATA_1, | Humidity_2 | Humidity 2 |
|
||||
| MB_DEVICE_ADDR1 | CID_INP_DATA_2 | Temperature_2 | Ambient temperature |
|
||||
| MB_DEVICE_ADDR1 | CID_HOLD_DATA_2 | Humidity_3 | Humidity 3 |
|
||||
| MB_DEVICE_ADDR1 | CID_RELAY_P1 | RelayP1 | Alarm Relay outputs on/off |
|
||||
| MB_DEVICE_ADDR1 | CID_RELAY_P2 | RelayP2 | Alarm Relay outputs on/off |
|
||||
--------------------------------------------------------------------------------------------------
|
||||
Note: The Slave Address is the same for all parameters for example test but it can be changed in the `Example Data (Object) Dictionary` table of master example to address parameters from other slaves.
|
||||
The Kconfig ```Modbus slave address``` - CONFIG_MB_SLAVE_ADDR parameter in slave example can be configured to create Modbus multi slave segment.
|
||||
|
||||
Simplified Modbus connection schematic for example test:
|
||||
```
|
||||
MB_DEVICE_ADDR1
|
||||
------------- -------------
|
||||
| | Network | |
|
||||
| Slave 1 |---<>--+---<>---| Master |
|
||||
| | | |
|
||||
------------- -------------
|
||||
```
|
||||
Modbus multi slave segment connection schematic:
|
||||
```
|
||||
MB_DEVICE_ADDR1
|
||||
-------------
|
||||
| |
|
||||
| Slave 1 |---<>--+
|
||||
| | |
|
||||
------------- |
|
||||
MB_DEVICE_ADDR2 |
|
||||
------------- | -------------
|
||||
| | | | |
|
||||
| Slave 2 |---<>--+---<>---| Master |
|
||||
| | | | |
|
||||
------------- | -------------
|
||||
MB_DEVICE_ADDR3 |
|
||||
------------- Network (Ethernet or WiFi connection)
|
||||
| | |
|
||||
| Slave 3 |---<>--+
|
||||
| |
|
||||
-------------
|
||||
```
|
||||
|
||||
## Hardware required :
|
||||
Option 1:
|
||||
PC (Modbus TCP Slave application) + ESP32 based development board with modbus_tcp_slave example.
|
||||
|
||||
Option 2:
|
||||
Several ESP32 based boards flashed with modbus_tcp_slave example software to represent slave devices. The IP slave addresses for each board have to be configured in `Modbus Example Configuration` menu according to the communication table of example.
|
||||
One ESP32 based development board should be flashed with modbus_master example and connected to the same network. All the boards require configuration of network settings as described in `examples/common_components/protocol_examples_common`.
|
||||
|
||||
## How to setup and use an example:
|
||||
|
||||
### Configure the application
|
||||
Start the command below to setup configuration:
|
||||
```
|
||||
idf.py menuconfig
|
||||
```
|
||||
|
||||
The communication parameters of Modbus stack allow to configure it appropriately but usually it is enough to use default settings.
|
||||
See the help string of parameters for more information.
|
||||
There are three ways to configure how the master example will obtain slave IP addresses in the network:
|
||||
* Enable CONFIG_MB_MDNS_IP_RESOLVER option allows to query for modbus services provided by Modbus slaves in the network and automatically configure IP table. This requires to activate the same option for each slave with unique modbus slave address configured in `Modbus Example Configuration` menu.
|
||||
* Enable CONFIG_MB_SLAVE_IP_FROM_STDIN option to define IP addresses of slaves manually. In order to enter the IP addresses wait for the prompt and type the string with IP address following format. Prompt: "Waiting IPN from stdin:", then enter the IP address of the slave to connect: "IPN=192.168.1.21", where N = (configured slave address - 1).
|
||||
* Configure slave addresses manually as below:
|
||||
```
|
||||
char* slave_ip_address_table[MB_DEVICE_COUNT] = {
|
||||
"192.168.1.21", // Address corresponds to MB_DEVICE_ADDR1 and set to predefined value by user
|
||||
"192.168.1.22", // Address corresponds to MB_DEVICE_ADDR2 of slave device in the Modbus data dictionary
|
||||
NULL // Marker of end of list
|
||||
};
|
||||
```
|
||||
|
||||
### Setup external Modbus slave devices or emulator
|
||||
Option 1:
|
||||
Configure the external Modbus master software according to port configuration parameters used in the example. The Modbus Slave application can be used with this example to emulate slave devices with its parameters. Use official documentation for software to setup emulation of slave devices.
|
||||
|
||||
Option 2:
|
||||
Other option is to have the modbus_slave example application flashed into ESP32 based board and connect boards together as showed on the Modbus connection schematic above. See the Modbus slave API documentation to configure communication parameters and slave addresses as defined in "Example parameters definition" table above.
|
||||
|
||||
### Build and flash software of master device
|
||||
Build the project and flash it to the board, then run monitor tool to view serial output:
|
||||
```
|
||||
idf.py -p PORT flash monitor
|
||||
```
|
||||
|
||||
(To exit the serial monitor, type ``Ctrl-]``.)
|
||||
|
||||
See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects.
|
||||
|
||||
## Example Output
|
||||
Example output of the application:
|
||||
```
|
||||
I (4644) esp_netif_handlers: example_connect: sta ip: 192.168.1.39, mask: 255.255.255.0, gw: 192.168.1.1
|
||||
I (4644) example_connect: Got IPv4 event: Interface "example_connect: sta" address: 192.168.1.39
|
||||
I (5644) example_connect: Got IPv6 event: Interface "example_connect: sta" address: fe80:0000:0000:0000:bedd:c2ff:fed1:b210, type: ESP_IP6_ADDR_IS_LINK_LOCAL
|
||||
I (5644) example_connect: Connected to example_connect: sta
|
||||
I (5654) example_connect: - IPv4 address: 192.168.1.39
|
||||
I (5664) example_connect: - IPv6 address: fe80:0000:0000:0000:bedd:c2ff:fed1:b210, type: ESP_IP6_ADDR_IS_LINK_LOCAL
|
||||
I (5674) uart: ESP_INTR_FLAG_IRAM flag not set while CONFIG_UART_ISR_IN_IRAM is enabled, flag updated
|
||||
I (5684) MASTER_TEST: Leave IP(0) = [192.168.1.21] set by user.
|
||||
I (5694) MASTER_TEST: IP(1) is not set in the table.
|
||||
I (5694) MASTER_TEST: Configured 1 IP address(es).
|
||||
I (5704) MASTER_TEST: Modbus master stack initialized...
|
||||
I (5704) MB_TCP_MASTER_PORT: TCP master stack initialized.
|
||||
I (5724) MB_TCP_MASTER_PORT: Host[IP]: "192.168.1.21"[192.168.1.21]
|
||||
I (5724) MB_TCP_MASTER_PORT: Add slave IP: 192.168.1.21
|
||||
I (5734) MB_TCP_MASTER_PORT: Connecting to slaves...
|
||||
-.-.-.I (5844) MB_TCP_MASTER_PORT: Connected 1 slaves, start polling...
|
||||
I (6004) MASTER_TEST: Start modbus test...
|
||||
I (6044) MASTER_TEST: Characteristic #0 Data_channel_0 (Volts) value = 1.120000 (0x3f8f5c29) read successful.
|
||||
I (6054) MASTER_TEST: Characteristic #1 Humidity_1 (%rH) value = 1.340000 (0x3fab851f) read successful.
|
||||
I (6074) MASTER_TEST: Characteristic #2 Temperature_1 (C) value = 2.340000 (0x4015c28f) read successful.
|
||||
I (6084) MASTER_TEST: Characteristic #3 Humidity_2 (%rH) value = 2.560000 (0x4023d70a) read successful.
|
||||
I (6094) MASTER_TEST: Characteristic #4 Temperature_2 (C) value = 3.560000 (0x4063d70a) read successful.
|
||||
I (6104) MASTER_TEST: Characteristic #5 Humidity_3 (%rH) value = 3.780000 (0x4071eb85) read successful.
|
||||
I (6124) MASTER_TEST: Characteristic #6 RelayP1 (on/off) value = OFF (0x55) read successful.
|
||||
I (6134) MASTER_TEST: Characteristic #7 RelayP2 (on/off) value = OFF (0xaa) read successful.
|
||||
I (6854) MASTER_TEST: Characteristic #0 Data_channel_0 (Volts) value = 1.120000 (0x3f8f5c29) read successful.
|
||||
I (7064) MASTER_TEST: Characteristic #1 Humidity_1 (%rH) value = 1.740000 (0x3fdeb852) read successful.
|
||||
I (7264) MASTER_TEST: Characteristic #2 Temperature_1 (C) value = 2.340000 (0x4015c28f) read successful.
|
||||
...
|
||||
I (45974) MASTER_TEST: Characteristic #4 Temperature_2 (C) value = 3.560000 (0x4063d70a) read successful.
|
||||
I (46174) MASTER_TEST: Characteristic #5 Humidity_3 (%rH) value = 3.780000 (0x4071eb85) read successful.
|
||||
I (46384) MASTER_TEST: Characteristic #6 RelayP1 (on/off) value = OFF (0x55) read successful.
|
||||
I (46584) MASTER_TEST: Characteristic #7 RelayP2 (on/off) value = ON (0xff) read successful.
|
||||
I (47094) MASTER_TEST: Alarm triggered by cid #7.
|
||||
I (47094) MASTER_TEST: Destroy master...
|
||||
```
|
||||
The example reads the characteristics from slave device(s), while alarm is not triggered in the slave device (See the "Example parameters definition"). The output line describes Timestamp, Cid of characteristic, Characteristic name (Units), Characteristic value (Hex data).
|
@@ -1,4 +0,0 @@
|
||||
set(PROJECT_NAME "modbus_tcp_master")
|
||||
|
||||
idf_component_register(SRCS "tcp_master.c"
|
||||
INCLUDE_DIRS ".")
|
@@ -1,16 +0,0 @@
|
||||
menu "Modbus TCP Example Configuration"
|
||||
|
||||
choice MB_SLAVE_IP_RESOLVER
|
||||
prompt "Select method to resolve slave IP addresses"
|
||||
help
|
||||
Select method which is used to resolve slave IP addresses
|
||||
and configure Master TCP IP stack.
|
||||
|
||||
config MB_MDNS_IP_RESOLVER
|
||||
bool "Resolve Modbus slave addresses using mDNS service."
|
||||
|
||||
config MB_SLAVE_IP_FROM_STDIN
|
||||
bool "Configure Modbus slave addresses from stdin"
|
||||
endchoice
|
||||
|
||||
endmenu
|
@@ -1,10 +0,0 @@
|
||||
dependencies:
|
||||
espressif/mdns: "^1.0.3"
|
||||
idf:
|
||||
version: ">=4.1.0"
|
||||
espressif/esp-modbus:
|
||||
version: "^1.0"
|
||||
mb_example_common:
|
||||
path: ${IDF_PATH}/examples/protocols/modbus/mb_example_common
|
||||
protocol_examples_common:
|
||||
path: ${IDF_PATH}/examples/common_components/protocol_examples_common
|
@@ -1,768 +0,0 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2016-2023 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
// FreeModbus Master Example ESP32
|
||||
|
||||
#include <string.h>
|
||||
#include <sys/queue.h>
|
||||
#include "esp_log.h"
|
||||
#include "esp_system.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_event.h"
|
||||
#include "esp_log.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "esp_netif.h"
|
||||
#include "esp_mac.h"
|
||||
|
||||
#include "mdns.h"
|
||||
#include "protocol_examples_common.h"
|
||||
|
||||
#include "modbus_params.h" // for modbus parameters structures
|
||||
#include "mbcontroller.h"
|
||||
#include "sdkconfig.h"
|
||||
|
||||
#define MB_TCP_PORT (CONFIG_FMB_TCP_PORT_DEFAULT) // TCP port used by example
|
||||
|
||||
// The number of parameters that intended to be used in the particular control process
|
||||
#define MASTER_MAX_CIDS num_device_parameters
|
||||
|
||||
// Number of reading of parameters from slave
|
||||
#define MASTER_MAX_RETRY (30)
|
||||
|
||||
// Timeout to update cid over Modbus
|
||||
#define UPDATE_CIDS_TIMEOUT_MS (500)
|
||||
#define UPDATE_CIDS_TIMEOUT_TICS (UPDATE_CIDS_TIMEOUT_MS / portTICK_PERIOD_MS)
|
||||
|
||||
// Timeout between polls
|
||||
#define POLL_TIMEOUT_MS (1)
|
||||
#define POLL_TIMEOUT_TICS (POLL_TIMEOUT_MS / portTICK_PERIOD_MS)
|
||||
#define MB_MDNS_PORT (502)
|
||||
|
||||
// The macro to get offset for parameter in the appropriate structure
|
||||
#define HOLD_OFFSET(field) ((uint16_t)(offsetof(holding_reg_params_t, field) + 1))
|
||||
#define INPUT_OFFSET(field) ((uint16_t)(offsetof(input_reg_params_t, field) + 1))
|
||||
#define COIL_OFFSET(field) ((uint16_t)(offsetof(coil_reg_params_t, field) + 1))
|
||||
#define DISCR_OFFSET(field) ((uint16_t)(offsetof(discrete_reg_params_t, field) + 1))
|
||||
#define STR(fieldname) ((const char*)( fieldname ))
|
||||
|
||||
// Options can be used as bit masks or parameter limits
|
||||
#define OPTS(min_val, max_val, step_val) { .opt1 = min_val, .opt2 = max_val, .opt3 = step_val }
|
||||
|
||||
#define MB_ID_BYTE0(id) ((uint8_t)(id))
|
||||
#define MB_ID_BYTE1(id) ((uint8_t)(((uint16_t)(id) >> 8) & 0xFF))
|
||||
#define MB_ID_BYTE2(id) ((uint8_t)(((uint32_t)(id) >> 16) & 0xFF))
|
||||
#define MB_ID_BYTE3(id) ((uint8_t)(((uint32_t)(id) >> 24) & 0xFF))
|
||||
|
||||
#define MB_ID2STR(id) MB_ID_BYTE0(id), MB_ID_BYTE1(id), MB_ID_BYTE2(id), MB_ID_BYTE3(id)
|
||||
|
||||
#if CONFIG_FMB_CONTROLLER_SLAVE_ID_SUPPORT
|
||||
#define MB_DEVICE_ID (uint32_t)CONFIG_FMB_CONTROLLER_SLAVE_ID
|
||||
#else
|
||||
#define MB_DEVICE_ID (uint32_t)0x00112233
|
||||
#endif
|
||||
|
||||
#define MB_MDNS_INSTANCE(pref) pref"mb_master_tcp"
|
||||
static const char *TAG = "MASTER_TEST";
|
||||
|
||||
// Enumeration of modbus device addresses accessed by master device
|
||||
// Each address in the table is a index of TCP slave ip address in mb_communication_info_t::tcp_ip_addr table
|
||||
enum {
|
||||
MB_DEVICE_ADDR1 = 1, // Slave UID = 1
|
||||
MB_DEVICE_ADDR2 = 200,
|
||||
MB_DEVICE_ADDR3 = 35
|
||||
};
|
||||
|
||||
// Enumeration of all supported CIDs for device (used in parameter definition table)
|
||||
enum {
|
||||
CID_INP_DATA_0 = 0,
|
||||
CID_HOLD_DATA_0,
|
||||
CID_INP_DATA_1,
|
||||
CID_HOLD_DATA_1,
|
||||
CID_INP_DATA_2,
|
||||
CID_HOLD_DATA_2,
|
||||
CID_HOLD_TEST_REG,
|
||||
CID_RELAY_P1,
|
||||
CID_RELAY_P2,
|
||||
CID_DISCR_P1,
|
||||
CID_COUNT
|
||||
};
|
||||
|
||||
// Example Data (Object) Dictionary for Modbus parameters:
|
||||
// The CID field in the table must be unique.
|
||||
// Modbus Slave Addr field defines slave address of the device with correspond parameter.
|
||||
// Modbus Reg Type - Type of Modbus register area (Holding register, Input Register and such).
|
||||
// Reg Start field defines the start Modbus register number and Reg Size defines the number of registers for the characteristic accordingly.
|
||||
// The Instance Offset defines offset in the appropriate parameter structure that will be used as instance to save parameter value.
|
||||
// Data Type, Data Size specify type of the characteristic and its data size.
|
||||
// Parameter Options field specifies the options that can be used to process parameter value (limits or masks).
|
||||
// Access Mode - can be used to implement custom options for processing of characteristic (Read/Write restrictions, factory mode values and etc).
|
||||
const mb_parameter_descriptor_t device_parameters[] = {
|
||||
// { CID, Param Name, Units, Modbus Slave Addr, Modbus Reg Type, Reg Start, Reg Size, Instance Offset, Data Type, Data Size, Parameter Options, Access Mode}
|
||||
{ CID_INP_DATA_0, STR("Data_channel_0"), STR("Volts"), MB_DEVICE_ADDR1, MB_PARAM_INPUT, 0, 2,
|
||||
INPUT_OFFSET(input_data0), PARAM_TYPE_FLOAT, 4, OPTS( -10, 10, 1 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_HOLD_DATA_0, STR("Humidity_1"), STR("%rH"), MB_DEVICE_ADDR1, MB_PARAM_HOLDING, 0, 2,
|
||||
HOLD_OFFSET(holding_data0), PARAM_TYPE_FLOAT, 4, OPTS( 0, 1000, 1 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_INP_DATA_1, STR("Temperature_1"), STR("C"), MB_DEVICE_ADDR1, MB_PARAM_INPUT, 2, 2,
|
||||
INPUT_OFFSET(input_data1), PARAM_TYPE_FLOAT, 4, OPTS( -40, 100, 1 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_HOLD_DATA_1, STR("Humidity_2"), STR("%rH"), MB_DEVICE_ADDR2, MB_PARAM_HOLDING, 2, 2,
|
||||
HOLD_OFFSET(holding_data1), PARAM_TYPE_FLOAT, 4, OPTS( 0, 100, 1 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_INP_DATA_2, STR("Temperature_2"), STR("C"), MB_DEVICE_ADDR2, MB_PARAM_INPUT, 4, 2,
|
||||
INPUT_OFFSET(input_data2), PARAM_TYPE_FLOAT, 4, OPTS( -40, 100, 1 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_HOLD_DATA_2, STR("Humidity_3"), STR("%rH"), MB_DEVICE_ADDR3, MB_PARAM_HOLDING, 4, 2,
|
||||
HOLD_OFFSET(holding_data2), PARAM_TYPE_FLOAT, 4, OPTS( 0, 100, 1 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_HOLD_TEST_REG, STR("Test_regs"), STR("__"), MB_DEVICE_ADDR1, MB_PARAM_HOLDING, 10, 58,
|
||||
HOLD_OFFSET(test_regs), PARAM_TYPE_ASCII, 116, OPTS( 0, 100, 1 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_RELAY_P1, STR("RelayP1"), STR("on/off"), MB_DEVICE_ADDR1, MB_PARAM_COIL, 2, 6,
|
||||
COIL_OFFSET(coils_port0), PARAM_TYPE_U8, 1, OPTS( 0xAA, 0x15, 0 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_RELAY_P2, STR("RelayP2"), STR("on/off"), MB_DEVICE_ADDR1, MB_PARAM_COIL, 10, 6,
|
||||
COIL_OFFSET(coils_port1), PARAM_TYPE_U8, 1, OPTS( 0x55, 0x2A, 0 ), PAR_PERMS_READ_WRITE_TRIGGER },
|
||||
{ CID_DISCR_P1, STR("DiscreteInpP1"), STR("on/off"), MB_DEVICE_ADDR1, MB_PARAM_DISCRETE, 2, 7,
|
||||
DISCR_OFFSET(discrete_input_port1), PARAM_TYPE_U8, 1, OPTS( 0xAA, 0x15, 0 ), PAR_PERMS_READ_WRITE_TRIGGER }
|
||||
};
|
||||
|
||||
// Calculate number of parameters in the table
|
||||
const uint16_t num_device_parameters = (sizeof(device_parameters) / sizeof(device_parameters[0]));
|
||||
|
||||
// This table represents slave IP addresses that correspond to the short address field of the slave in device_parameters structure
|
||||
// Modbus TCP stack shall use these addresses to be able to connect and read parameters from slave
|
||||
char* slave_ip_address_table[] = {
|
||||
#if CONFIG_MB_SLAVE_IP_FROM_STDIN
|
||||
"FROM_STDIN", // Address corresponds to MB_DEVICE_ADDR1 and set to predefined value by user
|
||||
"FROM_STDIN", // Corresponds to characteristic MB_DEVICE_ADDR2
|
||||
"FROM_STDIN", // Corresponds to characteristic MB_DEVICE_ADDR3
|
||||
NULL // End of table condition (must be included)
|
||||
#elif CONFIG_MB_MDNS_IP_RESOLVER
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL
|
||||
#endif
|
||||
};
|
||||
|
||||
const size_t ip_table_sz = (size_t)(sizeof(slave_ip_address_table) / sizeof(slave_ip_address_table[0]));
|
||||
|
||||
#if CONFIG_MB_SLAVE_IP_FROM_STDIN
|
||||
|
||||
// Scan IP address according to IPV settings
|
||||
char* master_scan_addr(int* index, char* buffer)
|
||||
{
|
||||
char* ip_str = NULL;
|
||||
int a[8] = {0};
|
||||
int buf_cnt = 0;
|
||||
#if !CONFIG_EXAMPLE_CONNECT_IPV6
|
||||
buf_cnt = sscanf(buffer, "IP%d="IPSTR, index, &a[0], &a[1], &a[2], &a[3]);
|
||||
if (buf_cnt == 5) {
|
||||
if (-1 == asprintf(&ip_str, IPSTR, a[0], a[1], a[2], a[3])) {
|
||||
abort();
|
||||
}
|
||||
}
|
||||
#else
|
||||
buf_cnt = sscanf(buffer, "IP%d="IPV6STR, index, &a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6], &a[7]);
|
||||
if (buf_cnt == 9) {
|
||||
if (-1 == asprintf(&ip_str, IPV6STR, a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7])) {
|
||||
abort();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return ip_str;
|
||||
}
|
||||
|
||||
static int master_get_slave_ip_stdin(char** addr_table)
|
||||
{
|
||||
char buf[128];
|
||||
int index;
|
||||
char* ip_str = NULL;
|
||||
int buf_cnt = 0;
|
||||
int ip_cnt = 0;
|
||||
|
||||
if (!addr_table) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
ESP_ERROR_CHECK(example_configure_stdin_stdout());
|
||||
while(1) {
|
||||
if (addr_table[ip_cnt] && strcmp(addr_table[ip_cnt], "FROM_STDIN") == 0) {
|
||||
printf("Waiting IP%d from stdin:\r\n", ip_cnt);
|
||||
while (fgets(buf, sizeof(buf), stdin) == NULL) {
|
||||
fputs(buf, stdout);
|
||||
}
|
||||
buf_cnt = strlen(buf);
|
||||
buf[buf_cnt - 1] = '\0';
|
||||
fputc('\n', stdout);
|
||||
ip_str = master_scan_addr(&index, buf);
|
||||
if (ip_str != NULL) {
|
||||
ESP_LOGI(TAG, "IP(%d) = [%s] set from stdin.", ip_cnt, ip_str);
|
||||
if ((ip_cnt >= ip_table_sz) || (index != ip_cnt)) {
|
||||
addr_table[ip_cnt] = NULL;
|
||||
break;
|
||||
}
|
||||
addr_table[ip_cnt++] = ip_str;
|
||||
} else {
|
||||
// End of configuration
|
||||
addr_table[ip_cnt++] = NULL;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (addr_table[ip_cnt]) {
|
||||
ESP_LOGI(TAG, "Leave IP(%d) = [%s] set manually.", ip_cnt, addr_table[ip_cnt]);
|
||||
ip_cnt++;
|
||||
} else {
|
||||
ESP_LOGI(TAG, "IP(%d) is not set in the table.", ip_cnt);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ip_cnt;
|
||||
}
|
||||
|
||||
#elif CONFIG_MB_MDNS_IP_RESOLVER
|
||||
|
||||
typedef struct slave_addr_entry_s {
|
||||
uint16_t index;
|
||||
char* ip_address;
|
||||
uint8_t slave_addr;
|
||||
void* p_data;
|
||||
LIST_ENTRY(slave_addr_entry_s) entries;
|
||||
} slave_addr_entry_t;
|
||||
|
||||
LIST_HEAD(slave_addr_, slave_addr_entry_s) slave_addr_list = LIST_HEAD_INITIALIZER(slave_addr_list);
|
||||
|
||||
// convert MAC from binary format to string
|
||||
static inline char* gen_mac_str(const uint8_t* mac, char* pref, char* mac_str)
|
||||
{
|
||||
sprintf(mac_str, "%s%02X%02X%02X%02X%02X%02X", pref, MAC2STR(mac));
|
||||
return mac_str;
|
||||
}
|
||||
|
||||
static inline char* gen_id_str(char* service_name, char* slave_id_str)
|
||||
{
|
||||
sprintf(slave_id_str, "%s%02X%02X%02X%02X", service_name, MB_ID2STR(MB_DEVICE_ID));
|
||||
return slave_id_str;
|
||||
}
|
||||
|
||||
static void master_start_mdns_service()
|
||||
{
|
||||
char temp_str[32] = {0};
|
||||
uint8_t sta_mac[6] = {0};
|
||||
ESP_ERROR_CHECK(esp_read_mac(sta_mac, ESP_MAC_WIFI_STA));
|
||||
char* hostname = gen_mac_str(sta_mac, MB_MDNS_INSTANCE("")"_", temp_str);
|
||||
// initialize mDNS
|
||||
ESP_ERROR_CHECK(mdns_init());
|
||||
// set mDNS hostname (required if you want to advertise services)
|
||||
ESP_ERROR_CHECK(mdns_hostname_set(hostname));
|
||||
ESP_LOGI(TAG, "mdns hostname set to: [%s]", hostname);
|
||||
|
||||
// set default mDNS instance name
|
||||
ESP_ERROR_CHECK(mdns_instance_name_set(MB_MDNS_INSTANCE("esp32_")));
|
||||
|
||||
// structure with TXT records
|
||||
mdns_txt_item_t serviceTxtData[] = {
|
||||
{"board","esp32"}
|
||||
};
|
||||
|
||||
// initialize service
|
||||
ESP_ERROR_CHECK(mdns_service_add(MB_MDNS_INSTANCE(""), "_modbus", "_tcp", MB_MDNS_PORT, serviceTxtData, 1));
|
||||
// add mac key string text item
|
||||
ESP_ERROR_CHECK(mdns_service_txt_item_set("_modbus", "_tcp", "mac", gen_mac_str(sta_mac, "\0", temp_str)));
|
||||
// add slave id key txt item
|
||||
ESP_ERROR_CHECK( mdns_service_txt_item_set("_modbus", "_tcp", "mb_id", gen_id_str("\0", temp_str)));
|
||||
}
|
||||
|
||||
static char* master_get_slave_ip_str(mdns_ip_addr_t* address, mb_tcp_addr_type_t addr_type)
|
||||
{
|
||||
mdns_ip_addr_t* a = address;
|
||||
char* slave_ip_str = NULL;
|
||||
|
||||
while (a) {
|
||||
if ((a->addr.type == ESP_IPADDR_TYPE_V6) && (addr_type == MB_IPV6)) {
|
||||
if (-1 == asprintf(&slave_ip_str, IPV6STR, IPV62STR(a->addr.u_addr.ip6))) {
|
||||
abort();
|
||||
}
|
||||
} else if ((a->addr.type == ESP_IPADDR_TYPE_V4) && (addr_type == MB_IPV4)) {
|
||||
if (-1 == asprintf(&slave_ip_str, IPSTR, IP2STR(&(a->addr.u_addr.ip4)))) {
|
||||
abort();
|
||||
}
|
||||
}
|
||||
if (slave_ip_str) {
|
||||
break;
|
||||
}
|
||||
a = a->next;
|
||||
}
|
||||
return slave_ip_str;
|
||||
}
|
||||
|
||||
static esp_err_t master_resolve_slave(uint8_t short_addr, mdns_result_t* result, char** resolved_ip,
|
||||
mb_tcp_addr_type_t addr_type)
|
||||
{
|
||||
if (!short_addr || !result || !resolved_ip) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
mdns_result_t* r = result;
|
||||
int t;
|
||||
char* slave_ip = NULL;
|
||||
char slave_name[22] = {0};
|
||||
|
||||
if (sprintf(slave_name, "mb_slave_tcp_%02" PRIx8, (int)short_addr) < 0) {
|
||||
ESP_LOGE(TAG, "Fail to create instance name for index: %u", (unsigned)short_addr);
|
||||
abort();
|
||||
}
|
||||
for (; r ; r = r->next) {
|
||||
if ((r->ip_protocol == MDNS_IP_PROTOCOL_V4) && (addr_type == MB_IPV6)) {
|
||||
continue;
|
||||
} else if ((r->ip_protocol == MDNS_IP_PROTOCOL_V6) && (addr_type == MB_IPV4)) {
|
||||
continue;
|
||||
}
|
||||
// Check host name for Modbus short address and
|
||||
// append it into slave ip address table
|
||||
if ((strcmp(r->instance_name, slave_name) == 0) && (r->port == CONFIG_FMB_TCP_PORT_DEFAULT)) {
|
||||
printf(" PTR : %s\n", r->instance_name);
|
||||
if (r->txt_count) {
|
||||
printf(" TXT : [%u] ", (unsigned)r->txt_count);
|
||||
for ( t = 0; t < r->txt_count; t++) {
|
||||
printf("%s=%s; ", r->txt[t].key, r->txt[t].value?r->txt[t].value:"NULL");
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
slave_ip = master_get_slave_ip_str(r->addr, addr_type);
|
||||
if (slave_ip) {
|
||||
ESP_LOGI(TAG, "Resolved slave %s[%s]:%u", r->hostname, slave_ip, (unsigned)r->port);
|
||||
*resolved_ip = slave_ip;
|
||||
return ESP_OK;
|
||||
}
|
||||
}
|
||||
}
|
||||
*resolved_ip = NULL;
|
||||
ESP_LOGD(TAG, "Fail to resolve slave: %s", slave_name);
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
|
||||
static int master_create_slave_list(mdns_result_t* results, char** addr_table,
|
||||
int addr_table_size, mb_tcp_addr_type_t addr_type)
|
||||
{
|
||||
if (!results) {
|
||||
return -1;
|
||||
}
|
||||
int i, cid_resolve_cnt = 0;
|
||||
uint8_t slave_addr = 0;
|
||||
int ip_index = 0;
|
||||
const mb_parameter_descriptor_t* pdescr = &device_parameters[0];
|
||||
char** ip_table = addr_table;
|
||||
char* slave_ip = NULL;
|
||||
slave_addr_entry_t *it;
|
||||
|
||||
for (i = 0; (i < num_device_parameters && pdescr); i++, pdescr++)
|
||||
{
|
||||
slave_addr = pdescr->mb_slave_addr;
|
||||
|
||||
it = NULL;
|
||||
// Is the slave address already registered?
|
||||
LIST_FOREACH(it, &slave_addr_list, entries) {
|
||||
if (slave_addr == it->slave_addr) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!it) {
|
||||
// Resolve new slave IP address using its short address
|
||||
esp_err_t err = master_resolve_slave(slave_addr, results, &slave_ip, addr_type);
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Index: %d, sl_addr: %u, failed to resolve!", i, slave_addr);
|
||||
// Set correspond index to NULL indicate host not resolved
|
||||
ip_table[ip_index] = NULL;
|
||||
continue;
|
||||
}
|
||||
// Register new slave address information
|
||||
slave_addr_entry_t* new_slave_entry = (slave_addr_entry_t*) heap_caps_malloc(sizeof(slave_addr_entry_t),
|
||||
MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
|
||||
MB_RETURN_ON_FALSE((new_slave_entry != NULL), ESP_ERR_NO_MEM,
|
||||
TAG, "Can not allocate memory for slave entry.");
|
||||
new_slave_entry->index = i;
|
||||
new_slave_entry->ip_address = slave_ip;
|
||||
new_slave_entry->slave_addr = slave_addr;
|
||||
new_slave_entry->p_data = NULL;
|
||||
LIST_INSERT_HEAD(&slave_addr_list, new_slave_entry, entries);
|
||||
ip_table[ip_index] = slave_ip;
|
||||
ESP_LOGI(TAG, "Index: %d, sl_addr: %u, resolved to IP: [%s]",
|
||||
i, slave_addr, slave_ip);
|
||||
cid_resolve_cnt++;
|
||||
if (ip_index < addr_table_size) {
|
||||
ip_index++;
|
||||
}
|
||||
} else {
|
||||
ip_table[ip_index] = it ? it->ip_address : ip_table[ip_index];
|
||||
ESP_LOGI(TAG, "Index: %d, sl_addr: %u, set to IP: [%s]",
|
||||
i, slave_addr, ip_table[ip_index]);
|
||||
cid_resolve_cnt++;
|
||||
}
|
||||
}
|
||||
ESP_LOGI(TAG, "Resolved %d cids, with %d address(es)", cid_resolve_cnt, ip_index);
|
||||
return cid_resolve_cnt;
|
||||
}
|
||||
|
||||
static int master_query_slave_service(const char * service_name, const char * proto,
|
||||
mb_tcp_addr_type_t addr_type)
|
||||
{
|
||||
ESP_LOGI(TAG, "Query PTR: %s.%s.local", service_name, proto);
|
||||
|
||||
mdns_result_t* results = NULL;
|
||||
int count = 0;
|
||||
|
||||
esp_err_t err = mdns_query_ptr(service_name, proto, 3000, 20, &results);
|
||||
if(err){
|
||||
ESP_LOGE(TAG, "Query Failed: %s", esp_err_to_name(err));
|
||||
return count;
|
||||
}
|
||||
if(!results){
|
||||
ESP_LOGW(TAG, "No results found!");
|
||||
return count;
|
||||
}
|
||||
|
||||
count = master_create_slave_list(results, slave_ip_address_table, ip_table_sz, addr_type);
|
||||
|
||||
mdns_query_results_free(results);
|
||||
return count;
|
||||
}
|
||||
#endif
|
||||
|
||||
static void master_destroy_slave_list(char** table, size_t ip_table_size)
|
||||
{
|
||||
#if CONFIG_MB_MDNS_IP_RESOLVER
|
||||
slave_addr_entry_t *it;
|
||||
while ((it = LIST_FIRST(&slave_addr_list))) {
|
||||
LIST_REMOVE(it, entries);
|
||||
free(it);
|
||||
}
|
||||
#endif
|
||||
for (int i = 0; ((i < ip_table_size) && table[i] != NULL); i++) {
|
||||
if (table[i]) {
|
||||
#if CONFIG_MB_SLAVE_IP_FROM_STDIN
|
||||
free(table[i]);
|
||||
table[i] = "FROM_STDIN";
|
||||
#elif CONFIG_MB_MDNS_IP_RESOLVER
|
||||
table[i] = NULL;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The function to get pointer to parameter storage (instance) according to parameter description table
|
||||
static void* master_get_param_data(const mb_parameter_descriptor_t* param_descriptor)
|
||||
{
|
||||
assert(param_descriptor != NULL);
|
||||
void* instance_ptr = NULL;
|
||||
if (param_descriptor->param_offset != 0) {
|
||||
switch(param_descriptor->mb_param_type)
|
||||
{
|
||||
case MB_PARAM_HOLDING:
|
||||
instance_ptr = ((void*)&holding_reg_params + param_descriptor->param_offset - 1);
|
||||
break;
|
||||
case MB_PARAM_INPUT:
|
||||
instance_ptr = ((void*)&input_reg_params + param_descriptor->param_offset - 1);
|
||||
break;
|
||||
case MB_PARAM_COIL:
|
||||
instance_ptr = ((void*)&coil_reg_params + param_descriptor->param_offset - 1);
|
||||
break;
|
||||
case MB_PARAM_DISCRETE:
|
||||
instance_ptr = ((void*)&discrete_reg_params + param_descriptor->param_offset - 1);
|
||||
break;
|
||||
default:
|
||||
instance_ptr = NULL;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Wrong parameter offset for CID #%u", param_descriptor->cid);
|
||||
assert(instance_ptr != NULL);
|
||||
}
|
||||
return instance_ptr;
|
||||
}
|
||||
|
||||
// User operation function to read slave values and check alarm
|
||||
static void master_operation_func(void *arg)
|
||||
{
|
||||
esp_err_t err = ESP_OK;
|
||||
float value = 0;
|
||||
bool alarm_state = false;
|
||||
const mb_parameter_descriptor_t* param_descriptor = NULL;
|
||||
|
||||
ESP_LOGI(TAG, "Start modbus test...");
|
||||
|
||||
for(uint16_t retry = 0; retry <= MASTER_MAX_RETRY && (!alarm_state); retry++) {
|
||||
// Read all found characteristics from slave(s)
|
||||
for (uint16_t cid = 0; (err != ESP_ERR_NOT_FOUND) && cid < MASTER_MAX_CIDS; cid++)
|
||||
{
|
||||
// Get data from parameters description table
|
||||
// and use this information to fill the characteristics description table
|
||||
// and having all required fields in just one table
|
||||
err = mbc_master_get_cid_info(cid, ¶m_descriptor);
|
||||
if ((err != ESP_ERR_NOT_FOUND) && (param_descriptor != NULL)) {
|
||||
void* temp_data_ptr = master_get_param_data(param_descriptor);
|
||||
assert(temp_data_ptr);
|
||||
uint8_t type = 0;
|
||||
if ((param_descriptor->param_type == PARAM_TYPE_ASCII) &&
|
||||
(param_descriptor->cid == CID_HOLD_TEST_REG)) {
|
||||
// Check for long array of registers of type PARAM_TYPE_ASCII
|
||||
err = mbc_master_get_parameter(cid, (char*)param_descriptor->param_key,
|
||||
(uint8_t*)temp_data_ptr, &type);
|
||||
if (err == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Characteristic #%u %s (%s) value = (0x%" PRIx32 ") read successful.",
|
||||
param_descriptor->cid,
|
||||
param_descriptor->param_key,
|
||||
param_descriptor->param_units,
|
||||
*(uint32_t*)temp_data_ptr);
|
||||
// Initialize data of test array and write to slave
|
||||
if (*(uint32_t*)temp_data_ptr != 0xAAAAAAAA) {
|
||||
memset((void*)temp_data_ptr, 0xAA, param_descriptor->param_size);
|
||||
*(uint32_t*)temp_data_ptr = 0xAAAAAAAA;
|
||||
err = mbc_master_set_parameter(cid, (char*)param_descriptor->param_key,
|
||||
(uint8_t*)temp_data_ptr, &type);
|
||||
if (err == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Characteristic #%u %s (%s) value = (0x%" PRIx32 "), write successful.",
|
||||
param_descriptor->cid,
|
||||
param_descriptor->param_key,
|
||||
param_descriptor->param_units,
|
||||
*(uint32_t*)temp_data_ptr);
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Characteristic #%u (%s) write fail, err = 0x%x (%s).",
|
||||
param_descriptor->cid,
|
||||
param_descriptor->param_key,
|
||||
(int)err,
|
||||
(char*)esp_err_to_name(err));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Characteristic #%u (%s) read fail, err = 0x%x (%s).",
|
||||
param_descriptor->cid,
|
||||
param_descriptor->param_key,
|
||||
(int)err,
|
||||
(char*)esp_err_to_name(err));
|
||||
}
|
||||
} else {
|
||||
err = mbc_master_get_parameter(cid, (char*)param_descriptor->param_key,
|
||||
(uint8_t*)temp_data_ptr, &type);
|
||||
if (err == ESP_OK) {
|
||||
if ((param_descriptor->mb_param_type == MB_PARAM_HOLDING) ||
|
||||
(param_descriptor->mb_param_type == MB_PARAM_INPUT)) {
|
||||
value = *(float*)temp_data_ptr;
|
||||
ESP_LOGI(TAG, "Characteristic #%u %s (%s) value = %f (0x%" PRIx32 ") read successful.",
|
||||
param_descriptor->cid,
|
||||
param_descriptor->param_key,
|
||||
param_descriptor->param_units,
|
||||
value,
|
||||
*(uint32_t*)temp_data_ptr);
|
||||
if (((value > param_descriptor->param_opts.max) ||
|
||||
(value < param_descriptor->param_opts.min))) {
|
||||
alarm_state = true;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
uint8_t state = *(uint8_t*)temp_data_ptr;
|
||||
const char* rw_str = (state & param_descriptor->param_opts.opt1) ? "ON" : "OFF";
|
||||
if ((state & param_descriptor->param_opts.opt2) == param_descriptor->param_opts.opt2) {
|
||||
ESP_LOGI(TAG, "Characteristic #%u %s (%s) value = %s (0x%" PRIx8 ") read successful.",
|
||||
param_descriptor->cid,
|
||||
param_descriptor->param_key,
|
||||
param_descriptor->param_units,
|
||||
rw_str,
|
||||
*(uint8_t*)temp_data_ptr);
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Characteristic #%u %s (%s) value = %s (0x%" PRIx8 "), unexpected value.",
|
||||
param_descriptor->cid,
|
||||
param_descriptor->param_key,
|
||||
param_descriptor->param_units,
|
||||
rw_str,
|
||||
*(uint8_t*)temp_data_ptr);
|
||||
alarm_state = true;
|
||||
break;
|
||||
}
|
||||
if (state & param_descriptor->param_opts.opt1) {
|
||||
alarm_state = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Characteristic #%u (%s) read fail, err = 0x%x (%s).",
|
||||
param_descriptor->cid,
|
||||
param_descriptor->param_key,
|
||||
(int)err,
|
||||
(char*)esp_err_to_name(err));
|
||||
}
|
||||
}
|
||||
vTaskDelay(POLL_TIMEOUT_TICS); // timeout between polls
|
||||
}
|
||||
}
|
||||
vTaskDelay(UPDATE_CIDS_TIMEOUT_TICS);
|
||||
}
|
||||
|
||||
if (alarm_state) {
|
||||
ESP_LOGI(TAG, "Alarm triggered by cid #%u.", param_descriptor->cid);
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Alarm is not triggered after %u retries.",
|
||||
MASTER_MAX_RETRY);
|
||||
}
|
||||
ESP_LOGI(TAG, "Destroy master...");
|
||||
vTaskDelay(100);
|
||||
}
|
||||
|
||||
static esp_err_t init_services(mb_tcp_addr_type_t ip_addr_type)
|
||||
{
|
||||
esp_err_t result = nvs_flash_init();
|
||||
if (result == ESP_ERR_NVS_NO_FREE_PAGES || result == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
result = nvs_flash_init();
|
||||
}
|
||||
MB_RETURN_ON_FALSE((result == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"nvs_flash_init fail, returns(0x%x).",
|
||||
(int)result);
|
||||
result = esp_netif_init();
|
||||
MB_RETURN_ON_FALSE((result == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"esp_netif_init fail, returns(0x%x).",
|
||||
(int)result);
|
||||
result = esp_event_loop_create_default();
|
||||
MB_RETURN_ON_FALSE((result == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"esp_event_loop_create_default fail, returns(0x%x).",
|
||||
(int)result);
|
||||
#if CONFIG_MB_MDNS_IP_RESOLVER
|
||||
// Start mdns service and register device
|
||||
master_start_mdns_service();
|
||||
#endif
|
||||
// This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
|
||||
// Read "Establishing Wi-Fi or Ethernet Connection" section in
|
||||
// examples/protocols/README.md for more information about this function.
|
||||
result = example_connect();
|
||||
MB_RETURN_ON_FALSE((result == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"example_connect fail, returns(0x%x).",
|
||||
(int)result);
|
||||
#if CONFIG_EXAMPLE_CONNECT_WIFI
|
||||
result = esp_wifi_set_ps(WIFI_PS_NONE);
|
||||
MB_RETURN_ON_FALSE((result == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"esp_wifi_set_ps fail, returns(0x%x).",
|
||||
(int)result);
|
||||
#endif
|
||||
#if CONFIG_MB_MDNS_IP_RESOLVER
|
||||
int res = 0;
|
||||
for (int retry = 0; (res < num_device_parameters) && (retry < 10); retry++) {
|
||||
res = master_query_slave_service("_modbus", "_tcp", ip_addr_type);
|
||||
}
|
||||
if (res < num_device_parameters) {
|
||||
ESP_LOGE(TAG, "Could not resolve one or more slave IP addresses, resolved: %d out of %u.", res, (unsigned)num_device_parameters );
|
||||
ESP_LOGE(TAG, "Make sure you configured all slaves according to device parameter table and they alive in the network.");
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
mdns_free();
|
||||
#elif CONFIG_MB_SLAVE_IP_FROM_STDIN
|
||||
int ip_cnt = master_get_slave_ip_stdin(slave_ip_address_table);
|
||||
if (ip_cnt) {
|
||||
ESP_LOGI(TAG, "Configured %d IP address(es).", ip_cnt);
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Fail to get IP address from stdin. Continue.");
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
#endif
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t destroy_services(void)
|
||||
{
|
||||
esp_err_t err = ESP_OK;
|
||||
master_destroy_slave_list(slave_ip_address_table, ip_table_sz);
|
||||
|
||||
err = example_disconnect();
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"example_disconnect fail, returns(0x%x).",
|
||||
(int)err);
|
||||
err = esp_event_loop_delete_default();
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"esp_event_loop_delete_default fail, returns(0x%x).",
|
||||
(int)err);
|
||||
err = esp_netif_deinit();
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK || err == ESP_ERR_NOT_SUPPORTED), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"esp_netif_deinit fail, returns(0x%x).",
|
||||
(int)err);
|
||||
err = nvs_flash_deinit();
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"nvs_flash_deinit fail, returns(0x%x).",
|
||||
(int)err);
|
||||
return err;
|
||||
}
|
||||
|
||||
// Modbus master initialization
|
||||
static esp_err_t master_init(mb_communication_info_t* comm_info)
|
||||
{
|
||||
void* master_handler = NULL;
|
||||
|
||||
esp_err_t err = mbc_master_init_tcp(&master_handler);
|
||||
MB_RETURN_ON_FALSE((master_handler != NULL), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"mb controller initialization fail.");
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"mb controller initialization fail, returns(0x%x).",
|
||||
(int)err);
|
||||
|
||||
err = mbc_master_setup((void*)comm_info);
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"mb controller setup fail, returns(0x%x).",
|
||||
(int)err);
|
||||
|
||||
err = mbc_master_set_descriptor(&device_parameters[0], num_device_parameters);
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"mb controller set descriptor fail, returns(0x%x).",
|
||||
(int)err);
|
||||
ESP_LOGI(TAG, "Modbus master stack initialized...");
|
||||
|
||||
err = mbc_master_start();
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"mb controller start fail, returns(0x%x).",
|
||||
(int)err);
|
||||
vTaskDelay(5);
|
||||
return err;
|
||||
}
|
||||
|
||||
static esp_err_t master_destroy(void)
|
||||
{
|
||||
esp_err_t err = mbc_master_destroy();
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"mbc_master_destroy fail, returns(0x%x).",
|
||||
(int)err);
|
||||
ESP_LOGI(TAG, "Modbus master stack destroy...");
|
||||
return err;
|
||||
}
|
||||
|
||||
void app_main(void)
|
||||
{
|
||||
mb_tcp_addr_type_t ip_addr_type;
|
||||
#if !CONFIG_EXAMPLE_CONNECT_IPV6
|
||||
ip_addr_type = MB_IPV4;
|
||||
#else
|
||||
ip_addr_type = MB_IPV6;
|
||||
#endif
|
||||
ESP_ERROR_CHECK(init_services(ip_addr_type));
|
||||
|
||||
mb_communication_info_t comm_info = { 0 };
|
||||
comm_info.ip_port = MB_TCP_PORT;
|
||||
comm_info.ip_addr_type = ip_addr_type;
|
||||
comm_info.ip_mode = MB_MODE_TCP;
|
||||
comm_info.ip_addr = (void*)slave_ip_address_table;
|
||||
comm_info.ip_netif_ptr = (void*)get_example_netif();
|
||||
|
||||
ESP_ERROR_CHECK(master_init(&comm_info));
|
||||
|
||||
master_operation_func(NULL);
|
||||
ESP_ERROR_CHECK(master_destroy());
|
||||
ESP_ERROR_CHECK(destroy_services());
|
||||
}
|
@@ -1,17 +0,0 @@
|
||||
#
|
||||
# Modbus configuration
|
||||
#
|
||||
CONFIG_FMB_COMM_MODE_TCP_EN=y
|
||||
CONFIG_FMB_TCP_PORT_DEFAULT=502
|
||||
CONFIG_FMB_TCP_CONNECTION_TOUT_SEC=20
|
||||
CONFIG_FMB_PORT_TASK_STACK_SIZE=4096
|
||||
CONFIG_FMB_PORT_TASK_PRIO=10
|
||||
CONFIG_FMB_COMM_MODE_RTU_EN=n
|
||||
CONFIG_FMB_COMM_MODE_ASCII_EN=n
|
||||
CONFIG_FMB_MASTER_TIMEOUT_MS_RESPOND=2000
|
||||
CONFIG_FMB_MASTER_DELAY_MS_CONVERT=300
|
||||
CONFIG_FMB_TIMER_PORT_ENABLED=y
|
||||
CONFIG_MB_MDNS_IP_RESOLVER=n
|
||||
CONFIG_MB_SLAVE_IP_FROM_STDIN=y
|
||||
CONFIG_EXAMPLE_CONNECT_IPV6=n
|
||||
CONFIG_FMB_TIMER_USE_ISR_DISPATCH_METHOD=y
|
@@ -1,11 +0,0 @@
|
||||
# The following lines of boilerplate have to be in your project's CMakeLists
|
||||
# in this exact order for cmake to work correctly
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
|
||||
# This component includes modbus example common definitions
|
||||
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
# "Trim" the build. Include the minimal set of components, main, and anything it depends on.
|
||||
idf_build_set_property(MINIMAL_BUILD ON)
|
||||
project(modbus_tcp_slave)
|
@@ -1,86 +0,0 @@
|
||||
| Supported Targets | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C5 | ESP32-C6 | ESP32-C61 | ESP32-H2 | ESP32-P4 | ESP32-S2 | ESP32-S3 |
|
||||
| ----------------- | ----- | -------- | -------- | -------- | -------- | --------- | -------- | -------- | -------- | -------- |
|
||||
|
||||
# Modbus Slave Example
|
||||
|
||||
This example demonstrates using of FreeModbus TCP slave stack port implementation for supported ESP32 target chips. The external Modbus host is able to read/write device parameters using Modbus protocol transport. The parameters accessible thorough Modbus are located in `mb_example_common/modbus_params.h\c` files and can be updated by user.
|
||||
These are represented in structures holding_reg_params, input_reg_params, coil_reg_params, discrete_reg_params for holding registers, input parameters, coils and discrete inputs accordingly. The app_main application demonstrates how to setup Modbus stack and use notifications about parameters change from host system.
|
||||
The FreeModbus stack located in `components/freemodbus` folder and contain `/port` folder inside which contains FreeModbus stack port for ESP32 target chips. There are some parameters that can be configured in KConfig file to start stack correctly (See description below for more information).
|
||||
|
||||
The slave example uses shared parameter structures defined in ```examples/protocols/modbus/mb_example_common``` folder.
|
||||
|
||||
## Hardware required :
|
||||
Option 1:
|
||||
The ESP32 based development board flashed with modbus_tcp_slave example + external Modbus master host software.
|
||||
|
||||
Option 2:
|
||||
The modbus_tcp_master example application configured as described in its README.md file and flashed into ESP32 based board.
|
||||
Note: The ```Example Data (Object) Dictionary``` in the modbus_tcp_master example can be edited to address parameters from other slaves connected into Modbus segment.
|
||||
|
||||
## How to setup and use an example:
|
||||
|
||||
### Configure the application
|
||||
Start the command below to show the configuration menu:
|
||||
```
|
||||
idf.py menuconfig
|
||||
```
|
||||
|
||||
To configure the example to use Wi-Fi or Ethernet connection, open the project configuration menu and navigate to "Example Connection Configuration" menu. Select either "Wi-Fi" or "Ethernet" in the "Connect using" choice.
|
||||
Follow the instructions in `examples/common_components/protocol_examples_common` for further configuration.
|
||||
|
||||
The communication parameters of freemodbus stack (Component config->Modbus configuration) allow to configure it appropriately but usually it is enough to use default settings.
|
||||
See the help strings of parameters for more information.
|
||||
|
||||
### Setup external Modbus master software
|
||||
Option 1:
|
||||
Configure the external Modbus master software according to port configuration parameters used in application.
|
||||
As an example the Modbus Poll application can be used with this example.
|
||||
Option 2:
|
||||
Setup ESP32 based development board and set modbus_tcp_master example configuration as described in its README.md file.
|
||||
Setup one or more slave boards and connect them into the same Modbus segment (See configuration above).
|
||||
|
||||
### Build and flash software
|
||||
Build the project and flash it to the board, then run monitor tool to view serial output:
|
||||
```
|
||||
idf.py -p PORT flash monitor
|
||||
```
|
||||
|
||||
(To exit the serial monitor, type ``Ctrl-]``.)
|
||||
|
||||
See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects.
|
||||
|
||||
## Example Output
|
||||
Example output of the application:
|
||||
```
|
||||
I (4235) esp_netif_handlers: example_connect: sta ip: 192.168.1.21, mask: 255.255.255.0, gw: 192.168.1.1
|
||||
I (4235) example_connect: Got IPv4 event: Interface "example_connect: sta" address: 192.168.1.21
|
||||
I (4465) example_connect: Got IPv6 event: Interface "example_connect: sta" address: fe80:0000:0000:0000:7edf:a1ff:fe00:4039, type: ESP_IP6_ADDR_IS_LINK_LOCAL
|
||||
I (4465) example_connect: Connected to example_connect: sta
|
||||
I (4475) example_connect: - IPv4 address: 192.168.1.21
|
||||
I (4475) example_connect: - IPv6 address: fe80:0000:0000:0000:7edf:a1ff:fe00:4039, type: ESP_IP6_ADDR_IS_LINK_LOCAL
|
||||
I (4495) MB_TCP_SLAVE_PORT: Socket (#54), listener on port: 502, errno=0
|
||||
I (4495) MB_TCP_SLAVE_PORT: Protocol stack initialized.
|
||||
I (4505) SLAVE_TEST: Modbus slave stack initialized.
|
||||
I (4505) SLAVE_TEST: Start modbus test...
|
||||
I (41035) MB_TCP_SLAVE_PORT: Socket (#55), accept client connection from address: 192.168.1.39
|
||||
I (41225) SLAVE_TEST: INPUT READ (41704766 us), ADDR:1, TYPE:8, INST_ADDR:0x3ffcb878, SIZE:2
|
||||
I (41235) SLAVE_TEST: HOLDING READ (41719746 us), ADDR:1, TYPE:2, INST_ADDR:0x3ffcb9b4, SIZE:2
|
||||
I (41255) SLAVE_TEST: INPUT READ (41732965 us), ADDR:3, TYPE:8, INST_ADDR:0x3ffcb87c, SIZE:2
|
||||
I (41265) SLAVE_TEST: HOLDING READ (41745923 us), ADDR:3, TYPE:2, INST_ADDR:0x3ffcb9b8, SIZE:2
|
||||
I (41275) SLAVE_TEST: INPUT READ (41759563 us), ADDR:5, TYPE:8, INST_ADDR:0x3ffcb880, SIZE:2
|
||||
I (41295) SLAVE_TEST: HOLDING READ (41772568 us), ADDR:5, TYPE:2, INST_ADDR:0x3ffcb9bc, SIZE:2
|
||||
I (41305) SLAVE_TEST: COILS WRITE (41785889 us), ADDR:0, TYPE:16, INST_ADDR:0x3ffcb874, SIZE:8
|
||||
I (41315) SLAVE_TEST: COILS WRITE (41799175 us), ADDR:8, TYPE:16, INST_ADDR:0x3ffcb875, SIZE:8
|
||||
I (41945) SLAVE_TEST: INPUT READ (42421629 us), ADDR:1, TYPE:8, INST_ADDR:0x3ffcb878, SIZE:2
|
||||
I (42145) SLAVE_TEST: HOLDING READ (42626497 us), ADDR:1, TYPE:2, INST_ADDR:0x3ffcb9b4, SIZE:2
|
||||
I (42345) SLAVE_TEST: INPUT READ (42831315 us), ADDR:3, TYPE:8, INST_ADDR:0x3ffcb87c, SIZE:2
|
||||
I (42555) SLAVE_TEST: HOLDING READ (43036111 us), ADDR:3, TYPE:2, INST_ADDR:0x3ffcb9b8, SIZE:2
|
||||
I (42755) SLAVE_TEST: INPUT READ (43240950 us), ADDR:5, TYPE:8, INST_ADDR:0x3ffcb880, SIZE:2
|
||||
I (42865) SLAVE_TEST: HOLDING READ (43343204 us), ADDR:5, TYPE:2, INST_ADDR:0x3ffcb9bc, SIZE:2
|
||||
......
|
||||
I (81265) SLAVE_TEST: HOLDING READ (81743698 us), ADDR:5, TYPE:2, INST_ADDR:0x3ffcb9bc, SIZE:2
|
||||
I (81465) SLAVE_TEST: COILS WRITE (81948482 us), ADDR:0, TYPE:16, INST_ADDR:0x3ffcb874, SIZE:8
|
||||
I (81465) SLAVE_TEST: Modbus controller destroyed.
|
||||
```
|
||||
The output lines describe type of operation, its timestamp, modbus address, access type, storage address in parameter structure and number of registers accordingly.
|
||||
|
@@ -1,4 +0,0 @@
|
||||
set(PROJECT_NAME "modbus_tcp_slave")
|
||||
|
||||
idf_component_register(SRCS "tcp_slave.c"
|
||||
INCLUDE_DIRS ".")
|
@@ -1,18 +0,0 @@
|
||||
menu "Modbus Example Configuration"
|
||||
|
||||
config MB_SLAVE_ADDR
|
||||
int "Modbus slave address"
|
||||
range 1 255
|
||||
default 1
|
||||
help
|
||||
This is the Modbus slave address in the network.
|
||||
The address is used as an index to resolve slave ip address.
|
||||
|
||||
config MB_MDNS_IP_RESOLVER
|
||||
bool "Resolve slave addresses using mDNS service"
|
||||
default y
|
||||
help
|
||||
This option allows to use mDNS service to resolve IP addresses of the Modbus slaves.
|
||||
If the option is disabled the ip addresses of slaves are defined in static table.
|
||||
|
||||
endmenu
|
@@ -1,9 +0,0 @@
|
||||
dependencies:
|
||||
espressif/mdns: "^1.0.3"
|
||||
idf: ">=4.1"
|
||||
espressif/esp-modbus:
|
||||
version: "^1.0"
|
||||
mb_example_common:
|
||||
path: ${IDF_PATH}/examples/protocols/modbus/mb_example_common
|
||||
protocol_examples_common:
|
||||
path: ${IDF_PATH}/examples/common_components/protocol_examples_common
|
@@ -1,441 +0,0 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2016-2023 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
// FreeModbus Slave Example ESP32
|
||||
|
||||
#include <stdio.h>
|
||||
#include "esp_err.h"
|
||||
#include "sdkconfig.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_system.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_event.h"
|
||||
#include "esp_log.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "mdns.h"
|
||||
#include "esp_netif.h"
|
||||
#include "esp_mac.h"
|
||||
|
||||
#include "protocol_examples_common.h"
|
||||
|
||||
#include "mbcontroller.h" // for mbcontroller defines and api
|
||||
#include "modbus_params.h" // for modbus parameters structures
|
||||
|
||||
#define MB_TCP_PORT_NUMBER (CONFIG_FMB_TCP_PORT_DEFAULT)
|
||||
#define MB_MDNS_PORT (502)
|
||||
|
||||
// Defines below are used to define register start address for each type of Modbus registers
|
||||
#define HOLD_OFFSET(field) ((uint16_t)(offsetof(holding_reg_params_t, field) >> 1))
|
||||
#define INPUT_OFFSET(field) ((uint16_t)(offsetof(input_reg_params_t, field) >> 1))
|
||||
#define MB_REG_DISCRETE_INPUT_START (0x0000)
|
||||
#define MB_REG_COILS_START (0x0000)
|
||||
#define MB_REG_INPUT_START_AREA0 (INPUT_OFFSET(input_data0)) // register offset input area 0
|
||||
#define MB_REG_INPUT_START_AREA1 (INPUT_OFFSET(input_data4)) // register offset input area 1
|
||||
#define MB_REG_HOLDING_START_AREA0 (HOLD_OFFSET(holding_data0))
|
||||
#define MB_REG_HOLDING_START_AREA1 (HOLD_OFFSET(holding_data4))
|
||||
|
||||
#define MB_PAR_INFO_GET_TOUT (10) // Timeout for get parameter info
|
||||
#define MB_CHAN_DATA_MAX_VAL (10)
|
||||
#define MB_CHAN_DATA_OFFSET (1.1f)
|
||||
|
||||
#define MB_READ_MASK (MB_EVENT_INPUT_REG_RD \
|
||||
| MB_EVENT_HOLDING_REG_RD \
|
||||
| MB_EVENT_DISCRETE_RD \
|
||||
| MB_EVENT_COILS_RD)
|
||||
#define MB_WRITE_MASK (MB_EVENT_HOLDING_REG_WR \
|
||||
| MB_EVENT_COILS_WR)
|
||||
#define MB_READ_WRITE_MASK (MB_READ_MASK | MB_WRITE_MASK)
|
||||
|
||||
#define MB_SLAVE_ADDR (CONFIG_MB_SLAVE_ADDR)
|
||||
|
||||
static const char *TAG = "SLAVE_TEST";
|
||||
|
||||
static portMUX_TYPE param_lock = portMUX_INITIALIZER_UNLOCKED;
|
||||
|
||||
#if CONFIG_MB_MDNS_IP_RESOLVER
|
||||
|
||||
#define MB_ID_BYTE0(id) ((uint8_t)(id))
|
||||
#define MB_ID_BYTE1(id) ((uint8_t)(((uint16_t)(id) >> 8) & 0xFF))
|
||||
#define MB_ID_BYTE2(id) ((uint8_t)(((uint32_t)(id) >> 16) & 0xFF))
|
||||
#define MB_ID_BYTE3(id) ((uint8_t)(((uint32_t)(id) >> 24) & 0xFF))
|
||||
|
||||
#define MB_ID2STR(id) MB_ID_BYTE0(id), MB_ID_BYTE1(id), MB_ID_BYTE2(id), MB_ID_BYTE3(id)
|
||||
|
||||
#if CONFIG_FMB_CONTROLLER_SLAVE_ID_SUPPORT
|
||||
#define MB_DEVICE_ID (uint32_t)CONFIG_FMB_CONTROLLER_SLAVE_ID
|
||||
#endif
|
||||
|
||||
#define MB_MDNS_INSTANCE(pref) pref"mb_slave_tcp"
|
||||
|
||||
// convert mac from binary format to string
|
||||
static inline char* gen_mac_str(const uint8_t* mac, char* pref, char* mac_str)
|
||||
{
|
||||
sprintf(mac_str, "%s%02X%02X%02X%02X%02X%02X", pref, MAC2STR(mac));
|
||||
return mac_str;
|
||||
}
|
||||
|
||||
static inline char* gen_id_str(char* service_name, char* slave_id_str)
|
||||
{
|
||||
sprintf(slave_id_str, "%s%02X%02X%02X%02X", service_name, MB_ID2STR(MB_DEVICE_ID));
|
||||
return slave_id_str;
|
||||
}
|
||||
|
||||
static inline char* gen_host_name_str(char* service_name, char* name)
|
||||
{
|
||||
sprintf(name, "%s_%02X", service_name, MB_SLAVE_ADDR);
|
||||
return name;
|
||||
}
|
||||
|
||||
static void start_mdns_service(void)
|
||||
{
|
||||
char temp_str[32] = {0};
|
||||
uint8_t sta_mac[6] = {0};
|
||||
ESP_ERROR_CHECK(esp_read_mac(sta_mac, ESP_MAC_WIFI_STA));
|
||||
char* hostname = gen_host_name_str(MB_MDNS_INSTANCE(""), temp_str);
|
||||
//initialize mDNS
|
||||
ESP_ERROR_CHECK(mdns_init());
|
||||
//set mDNS hostname (required if you want to advertise services)
|
||||
ESP_ERROR_CHECK(mdns_hostname_set(hostname));
|
||||
ESP_LOGI(TAG, "mdns hostname set to: [%s]", hostname);
|
||||
|
||||
//set default mDNS instance name
|
||||
ESP_ERROR_CHECK(mdns_instance_name_set(MB_MDNS_INSTANCE("esp32_")));
|
||||
|
||||
//structure with TXT records
|
||||
mdns_txt_item_t serviceTxtData[] = {
|
||||
{"board","esp32"}
|
||||
};
|
||||
|
||||
//initialize service
|
||||
ESP_ERROR_CHECK(mdns_service_add(hostname, "_modbus", "_tcp", MB_MDNS_PORT, serviceTxtData, 1));
|
||||
//add mac key string text item
|
||||
ESP_ERROR_CHECK(mdns_service_txt_item_set("_modbus", "_tcp", "mac", gen_mac_str(sta_mac, "\0", temp_str)));
|
||||
//add slave id key txt item
|
||||
ESP_ERROR_CHECK( mdns_service_txt_item_set("_modbus", "_tcp", "mb_id", gen_id_str("\0", temp_str)));
|
||||
}
|
||||
|
||||
static void stop_mdns_service(void)
|
||||
{
|
||||
mdns_free();
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
// Set register values into known state
|
||||
static void setup_reg_data(void)
|
||||
{
|
||||
// Define initial state of parameters
|
||||
discrete_reg_params.discrete_input0 = 1;
|
||||
discrete_reg_params.discrete_input1 = 0;
|
||||
discrete_reg_params.discrete_input2 = 1;
|
||||
discrete_reg_params.discrete_input3 = 0;
|
||||
discrete_reg_params.discrete_input4 = 1;
|
||||
discrete_reg_params.discrete_input5 = 0;
|
||||
discrete_reg_params.discrete_input6 = 1;
|
||||
discrete_reg_params.discrete_input7 = 0;
|
||||
|
||||
holding_reg_params.holding_data0 = 1.34;
|
||||
holding_reg_params.holding_data1 = 2.56;
|
||||
holding_reg_params.holding_data2 = 3.78;
|
||||
holding_reg_params.holding_data3 = 4.90;
|
||||
|
||||
holding_reg_params.holding_data4 = 5.67;
|
||||
holding_reg_params.holding_data5 = 6.78;
|
||||
holding_reg_params.holding_data6 = 7.79;
|
||||
holding_reg_params.holding_data7 = 8.80;
|
||||
coil_reg_params.coils_port0 = 0x55;
|
||||
coil_reg_params.coils_port1 = 0xAA;
|
||||
|
||||
input_reg_params.input_data0 = 1.12;
|
||||
input_reg_params.input_data1 = 2.34;
|
||||
input_reg_params.input_data2 = 3.56;
|
||||
input_reg_params.input_data3 = 4.78;
|
||||
input_reg_params.input_data4 = 1.12;
|
||||
input_reg_params.input_data5 = 2.34;
|
||||
input_reg_params.input_data6 = 3.56;
|
||||
input_reg_params.input_data7 = 4.78;
|
||||
}
|
||||
|
||||
static void slave_operation_func(void *arg)
|
||||
{
|
||||
mb_param_info_t reg_info; // keeps the Modbus registers access information
|
||||
|
||||
ESP_LOGI(TAG, "Modbus slave stack initialized.");
|
||||
ESP_LOGI(TAG, "Start modbus test...");
|
||||
// The cycle below will be terminated when parameter holding_data0
|
||||
// incremented each access cycle reaches the CHAN_DATA_MAX_VAL value.
|
||||
for(;holding_reg_params.holding_data0 < MB_CHAN_DATA_MAX_VAL;) {
|
||||
// Check for read/write events of Modbus master for certain events
|
||||
(void)mbc_slave_check_event(MB_READ_WRITE_MASK);
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(mbc_slave_get_param_info(®_info, MB_PAR_INFO_GET_TOUT));
|
||||
const char* rw_str = (reg_info.type & MB_READ_MASK) ? "READ" : "WRITE";
|
||||
// Filter events and process them accordingly
|
||||
if(reg_info.type & (MB_EVENT_HOLDING_REG_WR | MB_EVENT_HOLDING_REG_RD)) {
|
||||
// Get parameter information from parameter queue
|
||||
ESP_LOGI(TAG, "HOLDING %s (%" PRIu32 " us), ADDR:%u, TYPE:%u, INST_ADDR:0x%" PRIx32 ", SIZE:%u",
|
||||
rw_str,
|
||||
reg_info.time_stamp,
|
||||
(unsigned)reg_info.mb_offset,
|
||||
(unsigned)reg_info.type,
|
||||
(uint32_t)reg_info.address,
|
||||
(unsigned)reg_info.size);
|
||||
if (reg_info.address == (uint8_t*)&holding_reg_params.holding_data0)
|
||||
{
|
||||
portENTER_CRITICAL(¶m_lock);
|
||||
holding_reg_params.holding_data0 += MB_CHAN_DATA_OFFSET;
|
||||
if (holding_reg_params.holding_data0 >= (MB_CHAN_DATA_MAX_VAL - MB_CHAN_DATA_OFFSET)) {
|
||||
coil_reg_params.coils_port1 = 0xFF;
|
||||
}
|
||||
portEXIT_CRITICAL(¶m_lock);
|
||||
}
|
||||
} else if (reg_info.type & MB_EVENT_INPUT_REG_RD) {
|
||||
ESP_LOGI(TAG, "INPUT READ (%" PRIu32 " us), ADDR:%u, TYPE:%u, INST_ADDR:0x%" PRIx32 ", SIZE:%u",
|
||||
reg_info.time_stamp,
|
||||
(unsigned)reg_info.mb_offset,
|
||||
(unsigned)reg_info.type,
|
||||
(uint32_t)reg_info.address,
|
||||
(unsigned)reg_info.size);
|
||||
} else if (reg_info.type & MB_EVENT_DISCRETE_RD) {
|
||||
ESP_LOGI(TAG, "DISCRETE READ (%" PRIu32 " us), ADDR:%u, TYPE:%u, INST_ADDR:0x%" PRIx32 ", SIZE:%u",
|
||||
reg_info.time_stamp,
|
||||
(unsigned)reg_info.mb_offset,
|
||||
(unsigned)reg_info.type,
|
||||
(uint32_t)reg_info.address,
|
||||
(unsigned)reg_info.size);
|
||||
} else if (reg_info.type & (MB_EVENT_COILS_RD | MB_EVENT_COILS_WR)) {
|
||||
ESP_LOGI(TAG, "COILS %s (%" PRIu32 " us), ADDR:%u, TYPE:%u, INST_ADDR:0x%" PRIx32 ", SIZE:%u",
|
||||
rw_str,
|
||||
reg_info.time_stamp,
|
||||
(unsigned)reg_info.mb_offset,
|
||||
(unsigned)reg_info.type,
|
||||
(uint32_t)reg_info.address,
|
||||
(unsigned)reg_info.size);
|
||||
if (coil_reg_params.coils_port1 == 0xFF) break;
|
||||
}
|
||||
}
|
||||
// Destroy of Modbus controller on alarm
|
||||
ESP_LOGI(TAG,"Modbus controller destroyed.");
|
||||
vTaskDelay(100);
|
||||
}
|
||||
|
||||
static esp_err_t init_services(void)
|
||||
{
|
||||
esp_err_t result = nvs_flash_init();
|
||||
if (result == ESP_ERR_NVS_NO_FREE_PAGES || result == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
result = nvs_flash_init();
|
||||
}
|
||||
MB_RETURN_ON_FALSE((result == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"nvs_flash_init fail, returns(0x%x).",
|
||||
(int)result);
|
||||
result = esp_netif_init();
|
||||
MB_RETURN_ON_FALSE((result == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"esp_netif_init fail, returns(0x%x).",
|
||||
(int)result);
|
||||
result = esp_event_loop_create_default();
|
||||
MB_RETURN_ON_FALSE((result == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"esp_event_loop_create_default fail, returns(0x%x).",
|
||||
(int)result);
|
||||
#if CONFIG_MB_MDNS_IP_RESOLVER
|
||||
// Start mdns service and register device
|
||||
start_mdns_service();
|
||||
#endif
|
||||
// This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
|
||||
// Read "Establishing Wi-Fi or Ethernet Connection" section in
|
||||
// examples/protocols/README.md for more information about this function.
|
||||
result = example_connect();
|
||||
MB_RETURN_ON_FALSE((result == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"example_connect fail, returns(0x%x).",
|
||||
(int)result);
|
||||
#if CONFIG_EXAMPLE_CONNECT_WIFI
|
||||
result = esp_wifi_set_ps(WIFI_PS_NONE);
|
||||
MB_RETURN_ON_FALSE((result == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"esp_wifi_set_ps fail, returns(0x%x).",
|
||||
(int)result);
|
||||
#endif
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t destroy_services(void)
|
||||
{
|
||||
esp_err_t err = ESP_OK;
|
||||
|
||||
err = example_disconnect();
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"example_disconnect fail, returns(0x%x).",
|
||||
(int)err);
|
||||
err = esp_event_loop_delete_default();
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"esp_event_loop_delete_default fail, returns(0x%x).",
|
||||
(int)err);
|
||||
err = esp_netif_deinit();
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK || err == ESP_ERR_NOT_SUPPORTED), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"esp_netif_deinit fail, returns(0x%x).",
|
||||
(int)err);
|
||||
err = nvs_flash_deinit();
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"nvs_flash_deinit fail, returns(0x%x).",
|
||||
(int)err);
|
||||
#if CONFIG_MB_MDNS_IP_RESOLVER
|
||||
stop_mdns_service();
|
||||
#endif
|
||||
return err;
|
||||
}
|
||||
|
||||
// Modbus slave initialization
|
||||
static esp_err_t slave_init(mb_communication_info_t* comm_info)
|
||||
{
|
||||
mb_register_area_descriptor_t reg_area; // Modbus register area descriptor structure
|
||||
|
||||
void* slave_handler = NULL;
|
||||
|
||||
// Initialization of Modbus controller
|
||||
esp_err_t err = mbc_slave_init_tcp(&slave_handler);
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK && slave_handler != NULL), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"mb controller initialization fail.");
|
||||
|
||||
comm_info->ip_addr = NULL; // Bind to any address
|
||||
comm_info->ip_netif_ptr = (void*)get_example_netif();
|
||||
comm_info->slave_uid = MB_SLAVE_ADDR;
|
||||
|
||||
// Setup communication parameters and start stack
|
||||
err = mbc_slave_setup((void*)comm_info);
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"mbc_slave_setup fail, returns(0x%x).",
|
||||
(int)err);
|
||||
|
||||
// The code below initializes Modbus register area descriptors
|
||||
// for Modbus Holding Registers, Input Registers, Coils and Discrete Inputs
|
||||
// Initialization should be done for each supported Modbus register area according to register map.
|
||||
// When external master trying to access the register in the area that is not initialized
|
||||
// by mbc_slave_set_descriptor() API call then Modbus stack
|
||||
// will send exception response for this register area.
|
||||
reg_area.type = MB_PARAM_HOLDING; // Set type of register area
|
||||
reg_area.start_offset = MB_REG_HOLDING_START_AREA0; // Offset of register area in Modbus protocol
|
||||
reg_area.address = (void*)&holding_reg_params.holding_data0; // Set pointer to storage instance
|
||||
reg_area.size = (MB_REG_HOLDING_START_AREA1 - MB_REG_HOLDING_START_AREA0) << 1; // Set the size of register storage instance
|
||||
err = mbc_slave_set_descriptor(reg_area);
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"mbc_slave_set_descriptor fail, returns(0x%x).",
|
||||
(int)err);
|
||||
|
||||
reg_area.type = MB_PARAM_HOLDING; // Set type of register area
|
||||
reg_area.start_offset = MB_REG_HOLDING_START_AREA1; // Offset of register area in Modbus protocol
|
||||
reg_area.address = (void*)&holding_reg_params.holding_data4; // Set pointer to storage instance
|
||||
reg_area.size = sizeof(float) << 2; // Set the size of register storage instance
|
||||
err = mbc_slave_set_descriptor(reg_area);
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"mbc_slave_set_descriptor fail, returns(0x%x).",
|
||||
(int)err);
|
||||
|
||||
// Initialization of Input Registers area
|
||||
reg_area.type = MB_PARAM_INPUT;
|
||||
reg_area.start_offset = MB_REG_INPUT_START_AREA0;
|
||||
reg_area.address = (void*)&input_reg_params.input_data0;
|
||||
reg_area.size = sizeof(float) << 2;
|
||||
err = mbc_slave_set_descriptor(reg_area);
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"mbc_slave_set_descriptor fail, returns(0x%x).",
|
||||
(int)err);
|
||||
reg_area.type = MB_PARAM_INPUT;
|
||||
reg_area.start_offset = MB_REG_INPUT_START_AREA1;
|
||||
reg_area.address = (void*)&input_reg_params.input_data4;
|
||||
reg_area.size = sizeof(float) << 2;
|
||||
err = mbc_slave_set_descriptor(reg_area);
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"mbc_slave_set_descriptor fail, returns(0x%x).",
|
||||
(int)err);
|
||||
|
||||
// Initialization of Coils register area
|
||||
reg_area.type = MB_PARAM_COIL;
|
||||
reg_area.start_offset = MB_REG_COILS_START;
|
||||
reg_area.address = (void*)&coil_reg_params;
|
||||
reg_area.size = sizeof(coil_reg_params);
|
||||
err = mbc_slave_set_descriptor(reg_area);
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"mbc_slave_set_descriptor fail, returns(0x%x).",
|
||||
(int)err);
|
||||
|
||||
// Initialization of Discrete Inputs register area
|
||||
reg_area.type = MB_PARAM_DISCRETE;
|
||||
reg_area.start_offset = MB_REG_DISCRETE_INPUT_START;
|
||||
reg_area.address = (void*)&discrete_reg_params;
|
||||
reg_area.size = sizeof(discrete_reg_params);
|
||||
err = mbc_slave_set_descriptor(reg_area);
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"mbc_slave_set_descriptor fail, returns(0x%x).",
|
||||
(int)err);
|
||||
|
||||
// Set values into known state
|
||||
setup_reg_data();
|
||||
|
||||
// Starts of modbus controller and stack
|
||||
err = mbc_slave_start();
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"mbc_slave_start fail, returns(0x%x).",
|
||||
(int)err);
|
||||
vTaskDelay(5);
|
||||
return err;
|
||||
}
|
||||
|
||||
static esp_err_t slave_destroy(void)
|
||||
{
|
||||
esp_err_t err = mbc_slave_destroy();
|
||||
MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
|
||||
TAG,
|
||||
"mbc_slave_destroy fail, returns(0x%x).",
|
||||
(int)err);
|
||||
return err;
|
||||
}
|
||||
|
||||
// An example application of Modbus slave. It is based on freemodbus stack.
|
||||
// See deviceparams.h file for more information about assigned Modbus parameters.
|
||||
// These parameters can be accessed from main application and also can be changed
|
||||
// by external Modbus master host.
|
||||
void app_main(void)
|
||||
{
|
||||
ESP_ERROR_CHECK(init_services());
|
||||
|
||||
// Set UART log level
|
||||
|
||||
esp_log_level_set(TAG, ESP_LOG_INFO);
|
||||
|
||||
mb_communication_info_t comm_info = { 0 };
|
||||
|
||||
#if !CONFIG_EXAMPLE_CONNECT_IPV6
|
||||
comm_info.ip_addr_type = MB_IPV4;
|
||||
#else
|
||||
comm_info.ip_addr_type = MB_IPV6;
|
||||
#endif
|
||||
comm_info.ip_mode = MB_MODE_TCP;
|
||||
|
||||
comm_info.ip_port = MB_TCP_PORT_NUMBER;
|
||||
ESP_ERROR_CHECK(slave_init(&comm_info));
|
||||
|
||||
// The Modbus slave logic is located in this function (user handling of Modbus)
|
||||
slave_operation_func(NULL);
|
||||
|
||||
ESP_ERROR_CHECK(slave_destroy());
|
||||
ESP_ERROR_CHECK(destroy_services());
|
||||
}
|
@@ -1,18 +0,0 @@
|
||||
#
|
||||
# Modbus configuration
|
||||
#
|
||||
CONFIG_FMB_COMM_MODE_TCP_EN=y
|
||||
CONFIG_FMB_TCP_PORT_DEFAULT=502
|
||||
CONFIG_FMB_TCP_CONNECTION_TOUT_SEC=20
|
||||
CONFIG_FMB_PORT_TASK_STACK_SIZE=4096
|
||||
CONFIG_FMB_PORT_TASK_PRIO=10
|
||||
CONFIG_FMB_COMM_MODE_RTU_EN=n
|
||||
CONFIG_FMB_COMM_MODE_ASCII_EN=n
|
||||
CONFIG_FMB_MASTER_TIMEOUT_MS_RESPOND=1000
|
||||
CONFIG_FMB_MASTER_DELAY_MS_CONVERT=300
|
||||
CONFIG_FMB_TIMER_PORT_ENABLED=y
|
||||
CONFIG_MB_MDNS_IP_RESOLVER=n
|
||||
CONFIG_MB_SLAVE_ADDR=1
|
||||
CONFIG_LOG_DEFAULT_LEVEL_DEBUG=y
|
||||
CONFIG_EXAMPLE_CONNECT_IPV6=n
|
||||
CONFIG_FMB_TIMER_USE_ISR_DISPATCH_METHOD=y
|
Reference in New Issue
Block a user